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
9b3597dcd50fb8af77fe9fd32c1a5a3b4a7ad33c
0
trekawek/sling,headwirecom/sling,awadheshv/sling,headwirecom/sling,awadheshv/sling,anchela/sling,awadheshv/sling,vladbailescu/sling,awadheshv/sling,anchela/sling,ist-dresden/sling,trekawek/sling,tmaret/sling,tmaret/sling,tmaret/sling,trekawek/sling,headwirecom/sling,trekawek/sling,ieb/sling,anchela/sling,ist-dresden/sling,ieb/sling,ist-dresden/sling,ieb/sling,awadheshv/sling,headwirecom/sling,ieb/sling,ieb/sling,trekawek/sling,anchela/sling,awadheshv/sling,tmaret/sling,ist-dresden/sling,vladbailescu/sling,tmaret/sling,vladbailescu/sling,ieb/sling,vladbailescu/sling,ist-dresden/sling,headwirecom/sling,trekawek/sling,vladbailescu/sling,anchela/sling
/* * 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.sling.testing.mock.sling.loader; import java.io.IOException; import java.io.InputStream; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.JcrConstants; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.commons.mime.MimeTypeService; import org.apache.sling.jcr.contentparser.ContentParser; import org.apache.sling.jcr.contentparser.ContentParserFactory; import org.apache.sling.jcr.contentparser.ContentType; import org.apache.sling.jcr.contentparser.JsonParserFeature; import org.apache.sling.jcr.contentparser.ParseException; import org.apache.sling.jcr.contentparser.ParserOptions; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** * Imports JSON data and binary data into Sling resource hierarchy. * After all import operations from json or binaries {@link ResourceResolver#commit()} is called (when autocommit mode is active). */ public final class ContentLoader { private static final String CONTENTTYPE_OCTET_STREAM = "application/octet-stream"; private static final Set<String> IGNORED_NAMES = ImmutableSet.of( JcrConstants.JCR_MIXINTYPES, JcrConstants.JCR_UUID, JcrConstants.JCR_BASEVERSION, JcrConstants.JCR_PREDECESSORS, JcrConstants.JCR_SUCCESSORS, JcrConstants.JCR_CREATED, JcrConstants.JCR_VERSIONHISTORY, "jcr:checkedOut", "jcr:isCheckedOut", "rep:policy"); private static ContentParser JSON_PARSER = ContentParserFactory.create(ContentType.JSON, new ParserOptions() .detectCalendarValues(true) .ignorePropertyNames(IGNORED_NAMES) .ignoreResourceNames(IGNORED_NAMES) .jsonParserFeatures(EnumSet.of(JsonParserFeature.COMMENTS, JsonParserFeature.QUOTE_TICK))); private final ResourceResolver resourceResolver; private final BundleContext bundleContext; private final boolean autoCommit; /** * @param resourceResolver Resource resolver */ public ContentLoader(ResourceResolver resourceResolver) { this(resourceResolver, null); } /** * @param resourceResolver Resource resolver * @param bundleContext Bundle context */ public ContentLoader(ResourceResolver resourceResolver, BundleContext bundleContext) { this (resourceResolver, bundleContext, true); } /** * @param resourceResolver Resource resolver * @param bundleContext Bundle context * @param autoCommit Automatically commit changes after loading content (default: true) */ public ContentLoader(ResourceResolver resourceResolver, BundleContext bundleContext, boolean autoCommit) { this.resourceResolver = resourceResolver; this.bundleContext = bundleContext; this.autoCommit = autoCommit; } /** * Import content of JSON file into repository. * @param classpathResource Classpath resource URL for JSON content * @param parentResource Parent resource * @param childName Name of child resource to create with JSON content * @return Resource */ public Resource json(String classpathResource, Resource parentResource, String childName) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return json(is, parentResource, childName); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import content of JSON file into repository. Auto-creates parent * hierarchies as nt:unstrucured nodes if missing. * @param classpathResource Classpath resource URL for JSON content * @param destPath Path to import the JSON content to * @return Resource */ public Resource json(String classpathResource, String destPath) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return json(is, destPath); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import content of JSON file into repository. * @param inputStream Input stream with JSON content * @param parentResource Parent resource * @param childName Name of child resource to create with JSON content * @return Resource */ public Resource json(InputStream inputStream, Resource parentResource, String childName) { return json(inputStream, parentResource.getPath() + "/" + childName); } /** * Import content of JSON file into repository. Auto-creates parent * hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream with JSON content * @param destPath Path to import the JSON content to * @return Resource */ public Resource json(InputStream inputStream, String destPath) { try { String parentPath = ResourceUtil.getParent(destPath); String childName = ResourceUtil.getName(destPath); Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } if (parentResource.getChild(childName) != null) { throw new IllegalArgumentException("Resource does already exist: " + destPath); } LoaderContentHandler contentHandler = new LoaderContentHandler(destPath, resourceResolver); JSON_PARSER.parse(contentHandler, inputStream); if (autoCommit) { resourceResolver.commit(); } return resourceResolver.getResource(destPath); } catch (ParseException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } } private Resource createResourceHierarchy(String path) { String parentPath = ResourceUtil.getParent(path); if (parentPath == null) { return null; } Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } Map<String, Object> props = new HashMap<String, Object>(); props.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED); try { return resourceResolver.create(parentResource, ResourceUtil.getName(path), props); } catch (PersistenceException ex) { throw new RuntimeException(ex); } } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. Mime type is * auto-detected from resource name. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryFile(String classpathResource, String path) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryFile(is, path, detectMimeTypeFromName(path)); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryFile(String classpathResource, String path, String mimeType) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryFile(is, path, mimeType); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. Mime type is * auto-detected from resource name. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, String path) { return binaryFile(inputStream, path, detectMimeTypeFromName(path)); } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, String path, String mimeType) { String parentPath = ResourceUtil.getParent(path, 1); String name = ResourceUtil.getName(path); Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } return binaryFile(inputStream, parentResource, name, mimeType); } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. Mime type is * auto-detected from resource name. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:file * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, Resource parentResource, String name) { return binaryFile(inputStream, parentResource, name, detectMimeTypeFromName(name)); } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:file * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, Resource parentResource, String name, String mimeType) { try { Resource file = resourceResolver.create(parentResource, name, ImmutableMap.<String, Object> builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE) .build()); resourceResolver.create(file, JcrConstants.JCR_CONTENT, ImmutableMap.<String, Object> builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_RESOURCE) .put(JcrConstants.JCR_DATA, inputStream).put(JcrConstants.JCR_MIMETYPE, mimeType).build()); if (autoCommit) { resourceResolver.commit(); } return file; } catch (PersistenceException ex) { throw new RuntimeException("Unable to create resource at " + parentResource.getPath() + "/" + name, ex); } } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. Mime * type is auto-detected from resource name. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryResource(String classpathResource, String path) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryResource(is, path, detectMimeTypeFromName(path)); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryResource(String classpathResource, String path, String mimeType) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryResource(is, path, mimeType); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. Mime * type is auto-detected from resource name. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, String path) { return binaryResource(inputStream, path, detectMimeTypeFromName(path)); } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, String path, String mimeType) { String parentPath = ResourceUtil.getParent(path, 1); String name = ResourceUtil.getName(path); Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } return binaryResource(inputStream, parentResource, name, mimeType); } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. Mime * type is auto-detected from resource name. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:resource * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, Resource parentResource, String name) { return binaryResource(inputStream, parentResource, name, detectMimeTypeFromName(name)); } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:resource * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, Resource parentResource, String name, String mimeType) { try { Resource resource = resourceResolver.create(parentResource, name, ImmutableMap.<String, Object> builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_RESOURCE) .put(JcrConstants.JCR_DATA, inputStream).put(JcrConstants.JCR_MIMETYPE, mimeType).build()); if (autoCommit) { resourceResolver.commit(); } return resource; } catch (PersistenceException ex) { throw new RuntimeException("Unable to create resource at " + parentResource.getPath() + "/" + name, ex); } } /** * Detected mime type from name (file extension) using Mime Type service. * Fallback to application/octet-stream. * @param name Node name * @return Mime type (never null) */ private String detectMimeTypeFromName(String name) { String mimeType = null; String fileExtension = StringUtils.substringAfterLast(name, "."); if (bundleContext != null && StringUtils.isNotEmpty(fileExtension)) { ServiceReference<MimeTypeService> ref = bundleContext.getServiceReference(MimeTypeService.class); if (ref != null) { MimeTypeService mimeTypeService = (MimeTypeService)bundleContext.getService(ref); mimeType = mimeTypeService.getMimeType(fileExtension); } } return StringUtils.defaultString(mimeType, CONTENTTYPE_OCTET_STREAM); } }
testing/mocks/sling-mock/src/main/java/org/apache/sling/testing/mock/sling/loader/ContentLoader.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.sling.testing.mock.sling.loader; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.JcrConstants; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.commons.mime.MimeTypeService; import org.apache.sling.jcr.contentparser.ContentParser; import org.apache.sling.jcr.contentparser.ContentParserFactory; import org.apache.sling.jcr.contentparser.ContentType; import org.apache.sling.jcr.contentparser.ParseException; import org.apache.sling.jcr.contentparser.ParserOptions; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** * Imports JSON data and binary data into Sling resource hierarchy. * After all import operations from json or binaries {@link ResourceResolver#commit()} is called (when autocommit mode is active). */ public final class ContentLoader { private static final String CONTENTTYPE_OCTET_STREAM = "application/octet-stream"; private static final Set<String> IGNORED_NAMES = ImmutableSet.of( JcrConstants.JCR_MIXINTYPES, JcrConstants.JCR_UUID, JcrConstants.JCR_BASEVERSION, JcrConstants.JCR_PREDECESSORS, JcrConstants.JCR_SUCCESSORS, JcrConstants.JCR_CREATED, JcrConstants.JCR_VERSIONHISTORY, "jcr:checkedOut", "jcr:isCheckedOut", "rep:policy"); private static ContentParser JSON_PARSER = ContentParserFactory.create(ContentType.JSON, new ParserOptions() .detectCalendarValues(true) .ignorePropertyNames(IGNORED_NAMES) .ignoreResourceNames(IGNORED_NAMES)); private final ResourceResolver resourceResolver; private final BundleContext bundleContext; private final boolean autoCommit; /** * @param resourceResolver Resource resolver */ public ContentLoader(ResourceResolver resourceResolver) { this(resourceResolver, null); } /** * @param resourceResolver Resource resolver * @param bundleContext Bundle context */ public ContentLoader(ResourceResolver resourceResolver, BundleContext bundleContext) { this (resourceResolver, bundleContext, true); } /** * @param resourceResolver Resource resolver * @param bundleContext Bundle context * @param autoCommit Automatically commit changes after loading content (default: true) */ public ContentLoader(ResourceResolver resourceResolver, BundleContext bundleContext, boolean autoCommit) { this.resourceResolver = resourceResolver; this.bundleContext = bundleContext; this.autoCommit = autoCommit; } /** * Import content of JSON file into repository. * @param classpathResource Classpath resource URL for JSON content * @param parentResource Parent resource * @param childName Name of child resource to create with JSON content * @return Resource */ public Resource json(String classpathResource, Resource parentResource, String childName) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return json(is, parentResource, childName); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import content of JSON file into repository. Auto-creates parent * hierarchies as nt:unstrucured nodes if missing. * @param classpathResource Classpath resource URL for JSON content * @param destPath Path to import the JSON content to * @return Resource */ public Resource json(String classpathResource, String destPath) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return json(is, destPath); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import content of JSON file into repository. * @param inputStream Input stream with JSON content * @param parentResource Parent resource * @param childName Name of child resource to create with JSON content * @return Resource */ public Resource json(InputStream inputStream, Resource parentResource, String childName) { return json(inputStream, parentResource.getPath() + "/" + childName); } /** * Import content of JSON file into repository. Auto-creates parent * hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream with JSON content * @param destPath Path to import the JSON content to * @return Resource */ public Resource json(InputStream inputStream, String destPath) { try { String parentPath = ResourceUtil.getParent(destPath); String childName = ResourceUtil.getName(destPath); Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } if (parentResource.getChild(childName) != null) { throw new IllegalArgumentException("Resource does already exist: " + destPath); } LoaderContentHandler contentHandler = new LoaderContentHandler(destPath, resourceResolver); JSON_PARSER.parse(contentHandler, inputStream); if (autoCommit) { resourceResolver.commit(); } return resourceResolver.getResource(destPath); } catch (ParseException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } } private Resource createResourceHierarchy(String path) { String parentPath = ResourceUtil.getParent(path); if (parentPath == null) { return null; } Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } Map<String, Object> props = new HashMap<String, Object>(); props.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED); try { return resourceResolver.create(parentResource, ResourceUtil.getName(path), props); } catch (PersistenceException ex) { throw new RuntimeException(ex); } } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. Mime type is * auto-detected from resource name. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryFile(String classpathResource, String path) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryFile(is, path, detectMimeTypeFromName(path)); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryFile(String classpathResource, String path, String mimeType) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryFile(is, path, mimeType); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. Mime type is * auto-detected from resource name. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, String path) { return binaryFile(inputStream, path, detectMimeTypeFromName(path)); } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, String path, String mimeType) { String parentPath = ResourceUtil.getParent(path, 1); String name = ResourceUtil.getName(path); Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } return binaryFile(inputStream, parentResource, name, mimeType); } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. Mime type is * auto-detected from resource name. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:file * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, Resource parentResource, String name) { return binaryFile(inputStream, parentResource, name, detectMimeTypeFromName(name)); } /** * Import binary file as nt:file binary node into repository. Auto-creates * parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:file * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryFile(InputStream inputStream, Resource parentResource, String name, String mimeType) { try { Resource file = resourceResolver.create(parentResource, name, ImmutableMap.<String, Object> builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE) .build()); resourceResolver.create(file, JcrConstants.JCR_CONTENT, ImmutableMap.<String, Object> builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_RESOURCE) .put(JcrConstants.JCR_DATA, inputStream).put(JcrConstants.JCR_MIMETYPE, mimeType).build()); if (autoCommit) { resourceResolver.commit(); } return file; } catch (PersistenceException ex) { throw new RuntimeException("Unable to create resource at " + parentResource.getPath() + "/" + name, ex); } } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. Mime * type is auto-detected from resource name. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryResource(String classpathResource, String path) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryResource(is, path, detectMimeTypeFromName(path)); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. * @param classpathResource Classpath resource URL for binary file. * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryResource(String classpathResource, String path, String mimeType) { InputStream is = ContentLoader.class.getResourceAsStream(classpathResource); if (is == null) { throw new IllegalArgumentException("Classpath resource not found: " + classpathResource); } try { return binaryResource(is, path, mimeType); } finally { try { is.close(); } catch (IOException ex) { // ignore } } } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. Mime * type is auto-detected from resource name. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, String path) { return binaryResource(inputStream, path, detectMimeTypeFromName(path)); } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param path Path to mount binary data to (parent nodes created * automatically) * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, String path, String mimeType) { String parentPath = ResourceUtil.getParent(path, 1); String name = ResourceUtil.getName(path); Resource parentResource = resourceResolver.getResource(parentPath); if (parentResource == null) { parentResource = createResourceHierarchy(parentPath); } return binaryResource(inputStream, parentResource, name, mimeType); } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. Mime * type is auto-detected from resource name. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:resource * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, Resource parentResource, String name) { return binaryResource(inputStream, parentResource, name, detectMimeTypeFromName(name)); } /** * Import binary file as nt:resource binary node into repository. * Auto-creates parent hierarchies as nt:unstrucured nodes if missing. * @param inputStream Input stream for binary data * @param parentResource Parent resource * @param name Resource name for nt:resource * @param mimeType Mime type of binary data * @return Resource with binary data */ public Resource binaryResource(InputStream inputStream, Resource parentResource, String name, String mimeType) { try { Resource resource = resourceResolver.create(parentResource, name, ImmutableMap.<String, Object> builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_RESOURCE) .put(JcrConstants.JCR_DATA, inputStream).put(JcrConstants.JCR_MIMETYPE, mimeType).build()); if (autoCommit) { resourceResolver.commit(); } return resource; } catch (PersistenceException ex) { throw new RuntimeException("Unable to create resource at " + parentResource.getPath() + "/" + name, ex); } } /** * Detected mime type from name (file extension) using Mime Type service. * Fallback to application/octet-stream. * @param name Node name * @return Mime type (never null) */ private String detectMimeTypeFromName(String name) { String mimeType = null; String fileExtension = StringUtils.substringAfterLast(name, "."); if (bundleContext != null && StringUtils.isNotEmpty(fileExtension)) { ServiceReference<MimeTypeService> ref = bundleContext.getServiceReference(MimeTypeService.class); if (ref != null) { MimeTypeService mimeTypeService = (MimeTypeService)bundleContext.getService(ref); mimeType = mimeTypeService.getMimeType(fileExtension); } } return StringUtils.defaultString(mimeType, CONTENTTYPE_OCTET_STREAM); } }
SLING-6874 activate json quote tick parsing by default git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1796819 13f79535-47bb-0310-9956-ffa450edef68
testing/mocks/sling-mock/src/main/java/org/apache/sling/testing/mock/sling/loader/ContentLoader.java
SLING-6874 activate json quote tick parsing by default
<ide><path>esting/mocks/sling-mock/src/main/java/org/apache/sling/testing/mock/sling/loader/ContentLoader.java <ide> <ide> import java.io.IOException; <ide> import java.io.InputStream; <add>import java.util.EnumSet; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.Set; <ide> import org.apache.sling.jcr.contentparser.ContentParser; <ide> import org.apache.sling.jcr.contentparser.ContentParserFactory; <ide> import org.apache.sling.jcr.contentparser.ContentType; <add>import org.apache.sling.jcr.contentparser.JsonParserFeature; <ide> import org.apache.sling.jcr.contentparser.ParseException; <ide> import org.apache.sling.jcr.contentparser.ParserOptions; <ide> import org.osgi.framework.BundleContext; <ide> private static ContentParser JSON_PARSER = ContentParserFactory.create(ContentType.JSON, new ParserOptions() <ide> .detectCalendarValues(true) <ide> .ignorePropertyNames(IGNORED_NAMES) <del> .ignoreResourceNames(IGNORED_NAMES)); <add> .ignoreResourceNames(IGNORED_NAMES) <add> .jsonParserFeatures(EnumSet.of(JsonParserFeature.COMMENTS, JsonParserFeature.QUOTE_TICK))); <ide> <ide> private final ResourceResolver resourceResolver; <ide> private final BundleContext bundleContext;
JavaScript
mit
6b215fce3f803186f598158cd3e51738b7a1c295
0
PencilCode/pencilcode,PencilCode/pencilcode,PencilCode/pencilcode,PencilCode/pencilcode,cacticouncil/pencilcode,cacticouncil/pencilcode,cacticouncil/pencilcode,cacticouncil/pencilcode
function filterblocks(a) { // Show 'say' block only on browsers that support speech synthesis. if (!window.SpeechSynthesisUtterance || !window.speechSynthesis) { a = a.filter(function(b) { return !/^@?say\b/.test(b.block); }); } // Show 'listen' blocks only on browsers that support speech recognition. if (!window.webkitSpeechRecognition || window.SpeechRecognition) { a = a.filter(function(b) { return !/\blisten\b/.test(b.block); }); } return a.map(function(e) { if (!e.id) { // As the id (for logging), use the first (non-puncutation) word e.id = e.block.replace(/^\W*/, ''). replace(/^new /, '').replace(/\W.*$/, ''); // If that doesn't turn into anything, use the whole block text. if (!e.id) { e.id = e.block; } } return e; }); } // Recursive copy of a plain javascript object, while mapping // specified fields. function fieldmap(obj, map) { if (!obj || 'object' != typeof obj) { return obj; } var result; if (obj instanceof Array) { result = []; for (var j = 0; j < obj.length; ++j) { result.push(fieldmap(obj[j], map)); } } else { result = {}; for (var k in obj) if (obj.hasOwnProperty(k)) { if (map.hasOwnProperty(k)) { result[k] = map[k](obj[k]); } else { result[k] = fieldmap(obj[k], map); } } } return result; } function expand(palette, thisname) { var replacement = !thisname ? '' : (thisname + '.'); function replacer(s) { if (!s) return s; return s.replace(/@/, replacement); } return fieldmap(palette, { block: replacer, expansion: replacer }); } var distances = ['25', '50', '100', '200'], sdistances = ['100', '50', '-50', '-100'], angles = ['30', '45', '60', '90', '135', '144'], sangles = ['0', '90', '180', '270'], turntoarg = ['0', '90', '180', '270', 'lastclick', 'lastmouse'], sizes = ['10', '25', '50', '100'], scales = ['0.5', '2.0', '3.0'], randarg = ['100', '[true, false]', 'normal', 'position', 'color'], colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black']; var py_types = { distances: ['25', '50', '100', '200'], sdistances: ['100', '50', '-50', '-100'], angles: ['30', '45', '60', '90', '135', '144'], sangles: ['0', '90', '180', '270'], turntoarg: ['0', '90', '180', '270'],//, 'lastclick', 'lastmouse'], sizes: ['10', '25', '50', '100'], scales: ['0.5', '2.0', '3.0'], speeds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '0'], // randarg: ['100', '[true, false]', 'normal', 'position', 'color'], colors: ['\'red\'', '\'orange\'', '\'yellow\'', '\'green\'', '\'blue\'', '\'purple\'', '\'black\''] }; module.exports = { expand: expand, COFFEESCRIPT_PALETTE: [ { name: 'Move', color: 'lightblue', blocks: filterblocks([ { block: '@fd 100', title: 'Move forward' }, { block: '@rt 90', title: 'Turn right' }, { block: '@lt 90', title: 'Turn left' }, { block: '@bk 100', title: 'Move backward' }, { block: '@rt 180, 100', title: 'Make a wide right arc' }, { block: '@lt 180, 100', title: 'Make a wide left arc' }, { block: '@speed 10', title: 'Set the speed of the turtle' }, { block: '@speed Infinity', title: 'Use infinite speed' }, { block: '@home()', title: 'Jump to the origin, turned up' }, { block: '@turnto 270', title: 'Turn to an absolute direction' }, { block: '@moveto 100, 50', title: 'Move to coordinates' }, { block: '@movexy 30, 20', title: 'Move by changing x and y' }, { block: '@jumpto 100, 50', title: 'Jump to coordinates without drawing' }, { block: '@jumpxy 30, 20', title: 'Jump changing x and y without drawing' }, { block: '@pause 5', title: 'Do not move for five seconds' } ]) }, { name: 'Control', color: 'orange', blocks: filterblocks([ { block: 'for [1..3]\n ``', title: 'Do something multiple times' }, { block: 'for x in [0...10]\n ``', title: 'Repeat something while counting up x' }, { block: 'while `` < ``\n ``', title: ' Repeat while a condition is true' }, { block: 'if `` is ``\n ``', title: 'Do something only if a condition is true' }, { block: 'if `` is ``\n ``\nelse\n ``', title: 'Do something if a condition is true, otherwise something else', id: 'ifelse' }, { block: "forever 1, ->\n ``", title: 'Repeat something forever at qually-spaced times' }, { block: "button \'Click\', ->\n ``", title: 'Make a button and do something when clicked' }, { block: "keydown \'X\', ->\n ``", title: 'Do something when a keyboard key is pressed' }, { block: "click (e) ->\n ``", title: 'Do something when the mouse is clicked' } ]) }, { name: 'Art', color: 'purple', blocks: filterblocks([ { block: '@pen purple, 10', title: 'Set pen color and size' }, { block: '@dot green, 50', title: 'Make a dot' }, { block: '@box yellow, 50', title: 'Make a square' }, { block: '@fill blue', title: 'Fill traced shape' }, { block: '@wear \'apple\'', title: 'Use an image for the turtle' }, { block: 'img \'/img/bird\'', title: 'Write an image on the screen' }, { block: '@grow 3', title: 'Grow the size of the turtle' }, { block: '@hide()', title: 'Hide the main turtle' }, { block: '@show()', title: 'Show the main turtle' }, { block: 'cs()', title: 'Clear screen' }, { block: '@pu()', title: 'Lift the pen up' }, { block: '@pd()', title: 'Put the pen down' }, { block: '@drawon s', title: 'Draw on sprite s' }, { block: '@drawon document', title: 'Draw on the document' } ]) }, { name: 'Operators', color: 'lightgreen', blocks: filterblocks([ { block: 'x = 0', title: 'Set a variable', id: 'assign' }, { block: 'x += 1', title: 'Increase a variable', id: 'increment' }, { block: 'f = (x) ->\n ``', title: 'Define a new function', id: 'funcdef' }, { block: 'f(x)', title: 'Use a custom function', id: 'funccall' }, { block: '`` is ``', title: 'Compare two values', id: 'is' }, { block: '`` < ``', title: 'Compare two values', id: 'lessthan' }, { block: '`` > ``', title: 'Compare two values', id: 'greaterthan' }, { block: '`` + ``', title: 'Add two numbers', id: 'add' }, { block: '`` - ``', title: 'Subtract two numbers', id: 'subtract' }, { block: '`` * ``', title: 'Multiply two numbers', id: 'multiply' }, { block: '`` / ``', title: 'Divide two numbers', id: 'divide' }, { block: '`` and ``', title: 'True if both are true', id: 'and' }, { block: '`` or ``', title: 'True if either is true', id: 'or' }, { block: 'not ``', title: 'True if input is false', id: 'not' }, { block: 'random 6', title: 'Get a random number less than n' }, { block: 'round ``', title: 'Round to the nearest integer' }, { block: 'abs ``', title: 'Absolute value' }, { block: 'max ``, ``', title: 'Get the larger of two numbers' }, { block: 'min ``, ``', title: 'Get the smaller on two numbers' }, { block: 'x.match /pattern/', title: 'Test if a text pattern is found in x', id: 'match' } ]) }, { name: 'Text', color: 'pink', blocks: filterblocks([ { block: 'write \'Hello.\'', title: 'Write text in the document' }, { block: 'debug x', title: 'Log an object to debug' }, { block: 'type \'zz*(-.-)*zz\'', title: 'Typewrite text in the document' }, { block: 'typebox yellow', title: 'Type out a colored square' }, { block: 'typeline()', title: 'Type in a new line' }, { block: '@label \'spot\'', title: 'Write text at the turtle' }, { block: "await read '?', defer x", title: "Pause for input from the user" }, { block: "await readnum '?', defer x", title: "Pause for a number from the user" }, { block: 'read \'?\', (x) ->\n write x', title: 'Send input from the user to a function' }, { block: 'readnum \'?\', (x) ->\n write x', title: 'Send a number from the user to a function' } ]) }, { name: 'Sprites', color: 'teal', blocks: filterblocks([ { block: 't = new Turtle red', title: 'Make a new turtle', id: 'newturtle' }, { block: 's = new Sprite()', title: 'Make a blank sprite', id: 'newsprite' }, { block: 'p = new Piano()', title: 'Make a visible instrument', id: 'newpiano' }, { block: 'q = new Pencil()', title: 'Make an invisible and fast drawing sprite' }, { block: 'if @touches x\n ``', title: 'Do something only if touching the object x' }, { block: 'if @inside window\n ``', title: 'Do something only if inside the window' } ]) }, { name: 'Sound', color: 'indigo', blocks: filterblocks([ { block: '@play \'c G/G/ AG z\'', title: 'Play music notes in sequence' }, { block: '@play \'[fA] [ecG]2\'', title: 'Play notes in a chord' }, { block: '@tone \'B\', 2, 1', title: 'Sound a note immediately', id: 'toneNote' }, { block: '@tone \'B\', 0', title: 'Silence a note immediately', id: 'toneNote0' }, { block: '@tone 440, 2, 1', title: 'Sound a frequency immediately', id: 'toneHz' }, { block: '@tone 440, 0', title: 'Silence a frequency immediately', id: 'toneHz0' }, { block: '@silence()', title: 'Silence all notes' }, { block: "await listen defer x", title: "Pause for spoken words from the user" }, { block: 'listen (x) ->\n write x', title: 'Send spoken words from the user to a function' }, { block: '@say \'hello\'', title: 'Speak a word' }, { block: 'new Audio(url).play()', expansion: '(new Audio(\'https://upload.wikimedia.org/wikipedia/commons/1/11/06_-_Vivaldi_Summer_mvt_3_Presto_-_John_Harrison_violin.ogg\')).play()', title: 'Play an audio file' } ]) }, { name: 'Snippets', color: 'deeporange', blocks: filterblocks([ { block: "forever 10, ->\n turnto lastmouse\n fd 2", title: 'Continually move towards the last mouse position', id: "foreverFollowMouse" }, { block: "forever 10, ->\n if pressed 'W'\n fd 2", title: 'Poll a key and move while it is depressed', id: "foreverPollKey" }, { block: "forever 1, ->\n fd 25\n if not inside window\n stop()", title: 'Move once per second until not inside window', id: "foreverInsideWindow" }, { block: "click (e) ->\n moveto e", title: 'Move to a location when document is clicked', id: "foreverMovetoClick" }, { block: "button \'Click\', ->\n write 'clicked'", title: 'Make a button and do something when clicked', id: "buttonWrite" }, { block: "keydown \'X\', ->\n write 'x pressed'", title: 'Do something when a keyboard key is pressed', id: "keydownWrite" }, { block: "click (e) ->\n moveto e", title: 'Move to a location when document is clicked', id: "clickMove" } ]) } ], JAVASCRIPT_PALETTE: [ { name: 'Move', color: 'lightblue', blocks: filterblocks([ { block: '@fd(100);', title: 'Move forward' }, { block: '@rt(90);', title: 'Turn right' }, { block: '@lt(90);', title: 'Turn left' }, { block: '@bk(100);', title: 'Move backward' }, { block: '@rt(180, 100);', title: 'Make a wide right arc' }, { block: '@lt(180, 100);', title: 'Make a wide left arc' }, { block: '@speed(10);', title: 'Set the speed of the turtle' }, { block: '@speed(Infinity);', title: 'Use infinite speed' }, { block: '@home();', title: 'Jump to the origin, turned up' }, { block: '@turnto(270);', title: 'Turn to an absolute direction' }, { block: '@moveto(100, 50);', title: 'Move to coordinates' }, { block: '@movexy(30, 20);', title: 'Move by changing x and y' }, { block: '@jumpto(100, 50);', title: 'Jump to coordinates without drawing' }, { block: '@jumpxy(30, 20);', title: 'Jump changing x and y without drawing' } ]) }, { name: 'Control', color: 'orange', blocks: filterblocks([ { block: 'for (var j = 0; j < 3; ++j) {\n __\n}', title: 'Do something multiple times' }, { block: 'while (__ < __) {\n __\n}', title: ' Repeat while a condition is true' }, { block: 'if (__ === __) {\n __\n}', title: 'Do something only if a condition is true' }, { block: 'if (__ === __) {\n __\n} else {\n __\n}', title: 'Do something if a condition is true, otherwise something else', id: 'ifelse' }, { block: "forever(1, function() {\n __\n})", title: 'Repeat something forever at qually-spaced times' }, { block: "button(\'Click\', function() {\n __\n});", title: 'Make a button and do something when clicked' }, { block: "keydown(\'X\', function() {\n __\n});", title: 'Do something when a keyboard key is pressed' }, { block: "click(function(e) {\n __\n});", title: 'Do something when the mouse is clicked' } ]) }, { name: 'Art', color: 'purple', blocks: filterblocks([ { block: '@pen(purple, 10);', title: 'Set pen color and size' }, { block: '@dot(green, 50);', title: 'Make a dot' }, { block: '@box(yellow, 50);', title: 'Make a square' }, { block: '@fill(blue);', title: 'Fill traced shape' }, { block: '@wear(\'apple\');', title: 'Use an image for the turtle' }, { block: '@grow(3);', title: 'Grow the size of the turtle' }, { block: '@hide();', title: 'Hide the main turtle' }, { block: '@show();', title: 'Show the main turtle' }, { block: 'cs();', title: 'Clear screen' }, { block: '@pu();', title: 'Lift the pen up' }, { block: '@pd();', title: 'Put the pen down' }, { block: '@drawon(s);', title: 'Draw on sprite s' }, { block: '@drawon(document);', title: 'Draw on the document' } ]) }, { name: 'Operators', color: 'lightgreen', blocks: filterblocks([ { block: 'x = 0;', title: 'Set a variable', id: 'assign' }, { block: 'x += 1;', title: 'Increase a variable', }, { block: 'function f(x) {\n __\n}', title: 'Define a new function' }, { block: 'f(x)', title: 'Use a custom function' }, { block: '__ === __', title: 'Compare two values' }, { block: '__ < __', title: 'Compare two values' }, { block: '__ > __', title: 'Compare two values' }, { block: '__ + __', title: 'Add two numbers', id: 'add' }, { block: '__ - __', title: 'Subtract two numbers', id: 'subtract' }, { block: '__ * __', title: 'Multiply two numbers', id: 'multiply' }, { block: '__ / __', title: 'Divide two numbers', id: 'divide' }, { block: '__ && __', title: 'True if both are true', id: 'and' }, { block: '__ || __', title: 'True if either is true', id: 'or' }, { block: '!__', title: 'True if input is false', id: 'not' }, { block: 'random(6)', title: 'Get a random number less than n' }, { block: 'round(__)', title: 'Round to the nearest integer' }, { block: 'abs(__)', title: 'Absolute value' }, { block: 'max(__, __)', title: 'Get the larger of two numbers' }, { block: 'min(__, __)', title: 'Get the smaller on two numbers' }, { block: 'x.match(/pattern/)', title: 'Test if a text pattern is found in x' } ]) }, { name: 'Text', color: 'pink', blocks: filterblocks([ { block: 'write(\'Hello.\');', title: 'Write text in the document' }, { block: 'debug(x);', title: 'Log an object to debug' }, { block: 'type(\'zz*(-.-)*zz\');', title: 'Typewrite text in the document' }, { block: 'typebox(yellow);', title: 'Type out a colored square' }, { block: 'typeline();', title: 'Type in a new line' }, { block: '@label(\'spot\');', title: 'Write text at the turtle' }, { block: 'read(\'?\', function(x) {\n write(x);\n});', title: 'Send input from the user to a function' }, { block: 'readnum(\'?\', function(x) {\n write(x);\n});', title: 'Send a number from the user to a function' } ]) }, { name: 'Sprites', color: 'teal', blocks: filterblocks([ { block: 'var t = new Turtle(red);', title: 'Make a new turtle', id: 'newturtle' }, { block: 'var s = new Sprite();', title: 'Make a blank sprite', id: 'newsprite' }, { block: 'var p = new Piano();', title: 'Make a visible instrument', id: 'newpiano' }, { block: 'var q = new Pencil();', title: 'Make an invisible and fast drawing sprite' }, { block: 'if (@touches(x)) {\n __\n}', title: 'Do something only if touching the object x' }, { block: 'if (@inside(window)) {\n __\n}', title: 'Do something only if inside the window' } ]) }, { name: 'Sound', color: 'indigo', blocks: filterblocks([ { block: '@play(\'c G/G/ AG z\');', title: 'Play music notes in sequence' }, { block: '@play(\'[fA] [ecG]2\');', title: 'Play notes in a chord' }, { block: '@tone(\'B\', 2, 1);', title: 'Sound a note immediately' }, { block: '@tone(\'B\', 0);', title: 'Silence a note immediately' }, { block: '@tone(440, 2, 1);', title: 'Sound a frequency immediately' }, { block: '@tone(440, 0);', title: 'Silence a frequency immediately' }, { block: '@silence();', title: 'Silence all notes' }, { block: 'listen (function(x) {\n write(x);\n});', title: 'Send spoken words from the user to a function' }, { block: '@say(\'hello\');', title: 'Speak a word' }, { block: 'new Audio(url).play();', expansion: '(new Audio(\'https://upload.wikimedia.org/wikipedia/commons/1/11/06_-_Vivaldi_Summer_mvt_3_Presto_-_John_Harrison_violin.ogg\')).play();', title: 'Play an audio file' } ]) }, { name: 'Snippets', color: 'deeporange', blocks: filterblocks([ { block: "forever(10, function() {\n turnto(lastmouse);\n fd(2);\n});", title: 'Continually move towards the last mouse position' }, { block: "forever(10, function() {\n if (pressed('W')) {\n" + " fd(2);\n }\n});", title: 'Poll a key and move while it is depressed' }, { block: "forever(1, function() {\n fd(25);\n" + " if (!inside(window)) {\n stop();\n }\n});", title: 'Move once per second until not inside window' }, { block: "click(function(e) {\n moveto(e);\n});", title: 'Move to a location when document is clicked' }, { block: "button(\'Click\', function() {\n write('clicked');\n});", title: 'Make a button and do something when clicked' }, { block: "keydown(\'X\', function() {\n write('x pressed');\n});", title: 'Do something when a keyboard key is pressed' }, { block: "click(function(e) {\n moveto(e);\n});", title: 'Move to a location when document is clicked' } ]) } ], PYTHON_PALETTE: [ { name: 'Move', color: 'lightblue', blocks: filterblocks([ { block: 'fd(100)', title: 'Move forward' }, { block: 'bk(100)', title: 'Move backward' }, { block: 'rt(90)', title: 'Turn right' }, { block: 'lt(90)', title: 'Turn left' }, { block: 'ra(180, 100)', title: 'Make a wide right arc' }, { block: 'la(180, 100)', title: 'Make a wide left arc' }, { block: 'speed(10)', title: 'Set the speed of the turtle' }, { block: 'speed(0)', title: 'Use infinite speed' }, { block: 'home()', title: 'Jump to the origin, turned up' }, { block: 'turnto(270)', title: 'Turn to an absolute direction' }, { // block: '@turnto lastclick', // title: 'Turn toward a located object' // }, { block: 'moveto(100, 50)', title: 'Move to coordinates' }, { block: 'movexy(30, 20)', title: 'Move by changing x and y' }, { block: 'jumpto(100, 50)', title: 'Jump to coordinates without drawing' }, { block: 'jumpxy(30, 20)', title: 'Jump changing x and y without drawing' } ]) }, { name: 'Control', color: 'orange', blocks: filterblocks([ { block: "for x in range(0, 10):\n pass", title: 'Repeat something while counting up x' }, { block: 'while 0 < 10:\n pass', title: ' Repeat while a condition is true' }, { block: 'if 0 == 0:\n pass', title: 'Do something only if a condition is true' }, { block: 'if 0 == 0:\n pass\nelse:\n pass', title: 'Do something if a condition is true, otherwise something else', id: 'ifelse' /* }, { block: "forever 1, ->\n ``", title: 'Repeat something forever at qually-spaced times' }, { block: "button \'Click\', ->\n ``", title: 'Make a button and do something when clicked' }, { block: "keydown \'X\', ->\n ``", title: 'Do something when a keyboard key is pressed' }, { block: "click (e) ->\n ``", title: 'Do something when the mouse is clicked'*/ } ]) }, { name: 'Art', color: 'purple', blocks: filterblocks([ { block: 'pen(\'purple\', 10)', title: 'Set pen color and size' }, { block: 'dot(\'green\', 50)', title: 'Make a dot' }, { // block: 'box(yellow, 50)', // title: 'Make a square' // }, { // block: '@fill blue', // title: 'Fill traced shape' // }, { // block: '@wear \'/img/apple\'', // title: 'Use an image for the turtle' // }, { // block: '@scale 3', // title: 'Scale turtle drawing' // }, { block: 'ht()', title: 'Hide the main turtle' }, { block: 'st()', title: 'Show the main turtle' }, { block: 'cs()', title: 'Clear screen' }, { block: 'pu()', title: 'Lift the pen up' }, { block: 'pd()', title: 'Put the pen down' // }, { // block: 'drawon s', // title: 'Draw on sprite s' // }, { // block: '@drawon document', // title: 'Draw on the document' } ]) } ], HTML_PALETTE: [ { name: "Metadata", color: "lightblue", blocks: [ { block: "<!DOCTYPE html>", title: "Defines document type" }, { block: "<html></html>", expansion: "<html>\n <head>\n \n </head>\n <body>\n \n </body>\n</html>", title: "Root of an HTML document" }, { block: "<head></head>", expansion: "<head>\n \n</head>", title: "Represents a collection of metadata" }, { block: "<title></title>", title: "Document's title or name" }, { block: "<link rel=\"\" href=\"\">", title: "Link between a document and an external resource" }, { block: "<meta charset=\"\">", title: "Metadata about the HTML document" }, { block: "<style></style>", expansion: "<style>\n \n</style>", title: "Define style information" }, { block: "<script></script>", expansion: "<script>\n \n</script>", title: "Define a client-side script, such as a JavaScript" } ] }, { name: "Grouping", color: "purple", blocks: [ { block: "<p></p>", expansion: "<p>\n \n</p>", title: "Represents a paragraph" }, { block: "<hr>", title: "Paragraph-level thematic break" }, { block: "<div></div>", expansion: "<div>\n \n</div>", title: "Defines a division" }, { block: "<span></span>", title: "Group inline-elements" }, { block: "<center></center>", title: "Defines a centered group" }, { block: "<ul></ul>", expansion: "<ul>\n \n</ul>", title: "Unordered list - Use 'ol' for ordered list" }, { block: "<li></li>", title: "List item" }, { block: "<dl></dl>", expansion: "<dl>\n \n</dl>", title: "Description list" }, { block: "<dt></dt>", title: "Term/name in a description list" }, { block: "<dd></dd>", title: "Description of a term" } ] }, { name: "Content", color: "lightgreen", blocks: [ { block: "<a href=\"\"></a>", title: "Defines a hyperlink, which is used to link from one page to another" }, { block: "<img src=\"\">", title: "Image" }, { block: "<iframe src=\"\"></iframe>", expansion: "<iframe>\n \n</iframe>", title: "Nested browsing context" }, { block: "<strong></strong>", title: "Strong importance, seriousness, or urgency for its contents" }, { block: "<em></em>", title: "Stress emphasis of its contents" }, { block: "<i></i>", title: "Italic" }, { block: "<b></b>", title: "Bold" }, { block: "<u></u>", title: "Underline" }, { block: "<sub></sub>", title: "Subscript" }, { block: "<sup></sup>", title: "Superscript" }, { block: "<br>", title: "Line break" } ] }, { name: "Sections", color: "orange", blocks: [ { block: "<body></body>", expansion: "<body>\n \n</body>", title: "Main content of the document" }, { block: "<h1></h1>", title: "Heading for its section" }, { block: "<h2></h2>", title: "Heading for its section" }, { block: "<h3></h3>", title: "Heading for its section" }, { block: "<article></article>", expansion: "<article>\n \n</article>", title: "Independent, self-contained content" }, { block: "<section></section>", expansion: "<section>\n \n</section>", title: "Generic section of a document or application" }, { block: "<nav></nav>", expansion: "<nav>\n \n</nav>", title: "Set of navigation links" }, { block: "<header></header>", expansion: "<header>\n \n</header>", title: "Group of introductory or navigational aids" }, { block: "<footer></footer>", expansion: "<footer>\n \n</footer>", title: "Footer for a document or section" } ] }, { name: "Table", color: "indigo", blocks: [ { block: "<table></table>", expansion: "<table>\n \n</table>", title: "Defines a table" }, { block: "<tr></tr>", expansion: "<tr>\n \n</tr>", title: "Row in a table" }, { block: "<td></td>", title: "Standard cell inside a table row" }, { block: "<th></th>", title: "Header cell inside a table row" } ] }, { name: "Form", color: "deeporange", blocks: [ { block: "<form action=\"\"></form>", expansion: "<form action=\"\">\n \n</form>", title: "Create an HTML form" }, { block: "<input type=\"\">", title: "Input field where user can enter data" }, { block: "<textarea></textarea>", expansion: "<textarea>\n \n</textarea>", title: "Multi-line text input" }, { block: "<label></label>", title: "Label for an input element" }, { block: "<button></button>", title: "Clickable button" }, { block: "<select></select>", expansion: "<select>\n \n</select>", title: "Drop-down list" }, { block: "<option></option>", expansion: "<option value=\"\"></option>", title: "Option in a <select> list" } ] } ], KNOWN_FUNCTIONS: { '?.fd': {color: 'lightblue', dropdown: [distances]}, '?.bk': {color: 'lightblue', dropdown: [distances]}, '?.rt': {color: 'lightblue', dropdown: [angles]}, '?.lt': {color: 'lightblue', dropdown: [angles]}, '?.slide': {color: 'lightblue', dropdown: [sdistances]}, '?.move': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.movexy': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.moveto': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.jump': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.jumpxy': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.jumpto': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.turnto': {color: 'lightblue', dropdown: [turntoarg]}, '?.home': {color: 'lightblue'}, '?.pen': {color: 'purple', dropdown: [colors]}, '?.fill': {color: 'purple', dropdown: [colors]}, '?.dot': {color: 'purple', dropdown: [colors, sizes]}, '?.box': {color: 'purple', dropdown: [colors, sizes]}, '?.img': {color: 'purple'}, '?.mirror': {color: 'purple'}, '?.twist': {color: 'purple', dropdown: [sangles]}, '?.scale': {color: 'purple', dropdown: [scales]}, '?.grow': {color: 'purple', dropdown: [scales]}, '?.pause': {color: 'lightblue'}, '?.st': {color: 'purple'}, '?.ht': {color: 'purple'}, '?.show': {color: 'purple'}, '?.hide': {color: 'purple'}, '?.cs': {color: 'purple'}, '?.cg': {color: 'purple'}, '?.ct': {color: 'purple'}, '?.pu': {color: 'purple'}, '?.pd': {color: 'purple'}, '?.pe': {}, '?.pf': {}, '?.say': {color: 'indigo'}, '?.play': {color: 'indigo'}, '?.tone': {color: 'indigo'}, '?.silence': {color: 'indigo'}, '?.speed': {color:'lightblue'}, '?.wear': {color:'purple'}, '?.drawon': {color:'purple'}, '?.label': {color: 'pink'}, '?.reload': {}, remove: {color: 'pink'}, see: {}, sync: {}, send: {}, recv: {}, '?.click': {color: 'orange'}, '?.mousemove': {color: 'orange'}, '?.mouseup': {color: 'orange'}, '?.mousedown': {color: 'orange'}, '?.keyup': {color: 'orange'}, '?.keydown': {color: 'orange'}, '?.keypress': {color: 'orange'}, alert: {}, prompt: {}, '?.done': {}, tick: {color: 'orange'}, forever: {color: 'orange'}, stop: {color: 'orange'}, await: {color: 'orange'}, defer: {color: 'orange'}, type: {color: 'pink'}, typebox: {color: 'pink', dropdown: [colors]}, typeline: {color: 'pink'}, '*.sort': {}, debug: {color: 'pink'}, abs: {value: true, color: 'lightgreen'}, acos: {value: true, color: 'lightgreen'}, asin: {value: true, color: 'lightgreen'}, atan: {value: true, color: 'lightgreen'}, cos: {value: true, color: 'lightgreen'}, sin: {value: true, color: 'lightgreen'}, tan: {value: true, color: 'lightgreen'}, acosd: {value: true, color: 'lightgreen'}, asind: {value: true, color: 'lightgreen'}, atand: {value: true, color: 'lightgreen'}, cosd: {value: true, color: 'lightgreen'}, sind: {value: true, color: 'lightgreen'}, tand: {value: true, color: 'lightgreen'}, ceil: {value: true, color: 'lightgreen'}, floor: {value: true, color: 'lightgreen'}, round: {value: true, color: 'lightgreen'}, exp: {value: true, color: 'lightgreen'}, ln: {value: true, color: 'lightgreen'}, log10: {value: true, color: 'lightgreen'}, pow: {value: true, color: 'lightgreen'}, sqrt: {value: true, color: 'lightgreen'}, max: {value: true, color: 'lightgreen'}, min: {value: true, color: 'lightgreen'}, random: {value: true, color: 'lightgreen', dropdown: [randarg]}, 'Math.abs': {value: true, color: 'lightgreen'}, 'Math.acos': {value: true, color: 'lightgreen'}, 'Math.asin': {value: true, color: 'lightgreen'}, 'Math.atan': {value: true, color: 'lightgreen'}, 'Math.atan2': {value: true, color: 'lightgreen'}, 'Math.cos': {value: true, color: 'lightgreen'}, 'Math.sin': {value: true, color: 'lightgreen'}, 'Math.tan': {value: true, color: 'lightgreen'}, 'Math.ceil': {value: true, color: 'lightgreen'}, 'Math.floor': {value: true, color: 'lightgreen'}, 'Math.round': {value: true, color: 'lightgreen'}, 'Math.exp': {value: true, color: 'lightgreen'}, 'Math.log10': {value: true, color: 'lightgreen'}, 'Math.log2': {value: true, color: 'lightgreen'}, 'Math.log': {value: true, color: 'lightgreen'}, 'Math.pow': {value: true, color: 'lightgreen'}, 'Math.sqrt': {value: true, color: 'lightgreen'}, 'Math.max': {value: true, color: 'lightgreen'}, 'Math.min': {value: true, color: 'lightgreen'}, 'Math.random': {value: true, color: 'lightgreen'}, '?.pagexy': {value: true}, '?.getxy': {value: true, color:'lightblue'}, '?.direction': {value: true, color:'lightblue'}, '?.distance': {value: true, color:'lightblue'}, '?.shown': {value: true, color:'lightgreen'}, '?.hidden': {value: true, color:'lightgreen'}, '?.inside': {value: true, color:'lightgreen'}, '?.touches': {value: true, color:'lightgreen'}, '?.within': {value: true, color:'lightgreen'}, '?.notwithin': {value: true, color:'lightgreen'}, '?.nearest': {value: true}, '?.pressed': {value: true, color:'lightgreen'}, '?.canvas': {value: true}, hsl: {value: true}, hsla: {value: true}, rgb: {value: true}, rgba: {value: true}, '*.cell': {value: true}, '$': {value: true}, '*.match': {value: true, color:'lightgreen'}, '*.toString': {value: true}, '*.charCodeAt': {value: true}, '*.fromCharCode': {value: true}, '*.exec': {value: true}, '*.test': {value: true}, '*.split': {value: true}, '*.join': {value: true}, button: {value: true, command: true, color: 'orange'}, read: {value: true, command: true, color: 'pink'}, readstr: {value: true, command: true, color: 'pink'}, readnum: {value: true, command: true, color: 'pink'}, listen: {value: true, command: true, color: 'indigo'}, write: {value: true, command: true, color: 'pink'}, img: {value: true, command: true, color: 'purple'}, table: {value: true, command: true, color: 'yellow'}, '*.splice': {value: true, command: true}, '*.append': {value: true, command: true}, '*.finish': {value: true, command: true}, '*.text': {value: true, command: true, color: 'pink'}, loadscript: {value: true, command: true}, Date: {value: true, color: 'lightgreen'}, Audio: {value: true, color: 'indigo'}, Turtle: {value: true, color: 'teal'}, Sprite: {value: true, color: 'teal'}, Piano: {value: true, color: 'teal'}, Pencil: {value: true, color: 'teal'} }, PYTHON_FUNCTIONS: { // '*.fd': {color: 'purple'} // '?.fd': {color: 'purple'} 'fd': {color: 'lightblue', dropdown: [py_types.distances]}, 'bk': {color: 'lightblue', dropdown: [py_types.distances]}, 'rt': {color: 'lightblue', dropdown: [py_types.angles]}, 'lt': {color: 'lightblue', dropdown: [py_types.angles]}, 'ra': {color: 'lightblue', dropdown: [py_types.angles, py_types.distances]}, 'la': {color: 'lightblue', dropdown: [py_types.angles, py_types.distances]}, 'speed': {color: 'lightblue', drown: [py_types.speeds]}, 'home': {color: 'lightblue'}, 'turnto': {color: 'lightblue', dropdown: [py_types.angles]}, 'moveto': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'movexy': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'jumpto': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'jumpxy': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'pen': {color: 'purple', dropdown: [py_types.colors, py_types.sizes]}, 'dot': {color: 'purple', dropdown: [py_types.colors, py_types.sizes]}, 'st': {color: 'purple'}, 'ht': {color: 'purple'}, 'cs': {color: 'purple'}, 'pu': {color: 'purple'}, 'pd': {color: 'purple'}, /* '?.slide': {color: 'lightblue', dropdown: [sdistances]}, '?.fill': {color: 'purple', dropdown: [colors]}, '?.box': {color: 'purple', dropdown: [colors, sizes]}, '?.mirror': {color: 'purple'}, '?.twist': {color: 'purple', dropdown: [sangles]}, '?.scale': {color: 'purple', dropdown: [scales]}, '?.pause': {}, '?.cg': {color: 'purple'}, '?.ct': {color: 'purple'}, '?.pe': {}, '?.pf': {}, '?.say': {color: 'indigo'}, '?.play': {color: 'indigo'}, '?.tone': {color: 'indigo'}, '?.silence': {color: 'indigo'}, '?.speed': {color:'lightblue'}, '?.wear': {color:'purple'}, '?.drawon': {color:'purple'}, '?.label': {color: 'pink'}, '?.reload': {}, see: {}, sync: {}, send: {}, recv: {}, '?.click': {color: 'orange'}, '?.mousemove': {color: 'orange'}, '?.mouseup': {color: 'orange'}, '?.mousedown': {color: 'orange'}, '?.keyup': {color: 'orange'}, '?.keydown': {color: 'orange'}, '?.keypress': {color: 'orange'}, alert: {}, prompt: {}, '?.done': {}, tick: {color: 'orange'}, forever: {color: 'orange'}, stop: {color: 'orange'}, await: {color: 'orange'}, defer: {color: 'orange'}, type: {color: 'pink'}, '*.sort': {}, log: {color: 'pink'}, abs: {value: true, color: 'lightgreen'}, acos: {value: true, color: 'lightgreen'}, asin: {value: true, color: 'lightgreen'}, atan: {value: true, color: 'lightgreen'}, atan2: {value: true, color: 'lightgreen'}, cos: {value: true, color: 'lightgreen'}, sin: {value: true, color: 'lightgreen'}, tan: {value: true, color: 'lightgreen'}, ceil: {value: true, color: 'lightgreen'}, floor: {value: true, color: 'lightgreen'}, round: {value: true, color: 'lightgreen'}, exp: {value: true, color: 'lightgreen'}, ln: {value: true, color: 'lightgreen'}, log10: {value: true, color: 'lightgreen'}, pow: {value: true, color: 'lightgreen'}, sqrt: {value: true, color: 'lightgreen'}, max: {value: true, color: 'lightgreen'}, min: {value: true, color: 'lightgreen'}, random: {value: true, color: 'lightgreen'}, 'Math.abs': {value: true, color: 'lightgreen'}, 'Math.acos': {value: true, color: 'lightgreen'}, 'Math.asin': {value: true, color: 'lightgreen'}, 'Math.atan': {value: true, color: 'lightgreen'}, 'Math.atan2': {value: true, color: 'lightgreen'}, 'Math.cos': {value: true, color: 'lightgreen'}, 'Math.sin': {value: true, color: 'lightgreen'}, 'Math.tan': {value: true, color: 'lightgreen'}, 'Math.ceil': {value: true, color: 'lightgreen'}, 'Math.floor': {value: true, color: 'lightgreen'}, 'Math.round': {value: true, color: 'lightgreen'}, 'Math.exp': {value: true, color: 'lightgreen'}, 'Math.log10': {value: true, color: 'lightgreen'}, 'Math.log2': {value: true, color: 'lightgreen'}, 'Math.log': {value: true, color: 'lightgreen'}, 'Math.pow': {value: true, color: 'lightgreen'}, 'Math.sqrt': {value: true, color: 'lightgreen'}, 'Math.max': {value: true, color: 'lightgreen'}, 'Math.min': {value: true, color: 'lightgreen'}, 'Math.random': {value: true, color: 'lightgreen'}, '?.pagexy': {value: true}, '?.getxy': {value: true, color:'lightblue'}, '?.direction': {value: true, color:'lightblue'}, '?.distance': {value: true, color:'lightblue'}, '?.shown': {value: true, color:'lightgreen'}, '?.hidden': {value: true, color:'lightgreen'}, '?.inside': {value: true, color:'lightgreen'}, '?.touches': {value: true, color:'lightgreen'}, '?.within': {value: true, color:'lightgreen'}, '?.notwithin': {value: true, color:'lightgreen'}, '?.nearest': {value: true}, '?.pressed': {value: true, color:'lightgreen'}, '?.canvas': {value: true}, hsl: {value: true}, hsla: {value: true}, rgb: {value: true}, rgba: {value: true}, '*.cell': {value: true}, '$': {value: true}, '*.match': {value: true, color:'lightgreen'}, '*.toString': {value: true}, '*.charCodeAt': {value: true}, '*.fromCharCode': {value: true}, '*.exec': {value: true}, '*.test': {value: true}, '*.split': {value: true}, '*.join': {value: true}, button: {value: true, command: true, color: 'orange'}, read: {value: true, command: true, color: 'pink'}, readstr: {value: true, command: true, color: 'pink'}, readnum: {value: true, command: true, color: 'pink'}, write: {value: true, command: true, color: 'pink'}, table: {value: true, command: true, color: 'yellow'}, '*.splice': {value: true, command: true}, '*.append': {value: true, command: true}, '*.finish': {value: true, command: true}, '*.text': {value: true, command: true, color: 'pink'}, loadscript: {value: true, command: true}, Turtle: {value: true, color: 'teal'}, Sprite: {value: true, color: 'teal'}, Piano: {value: true, color: 'teal'}, Pencil: {value: true, color: 'teal'}*/ }, CATEGORIES: { functions: {color: 'lightgreen'}, returns: {color: 'yellow'}, comments: {color: 'gray'}, arithmetic: {color: 'lightgreen'}, logic: {color: 'lightgreen'}, containers: {color: 'teal'}, assignments: {color: 'lightgreen'}, loops: {color: 'orange'}, conditionals: {color: 'orange'}, value: {color: 'lightgreen'}, command: {color: 'lightgreen'}, errors: {color: '#f00'} }, // PYTHON_CATEGORIES: { // functions: {color: 'lightgreen'}, // returns: {color: 'yellow'}, // comments: {color: 'gray'}, // arithmetic: {color: 'lightgreen'}, // logic: {color: 'lightgreen'}, // containers: {color: 'teal'}, // assignments: {color: 'lightgreen'}, // loops: {color: 'orange'}, // conditionals: {color: 'orange'}, // value: {color: 'lightgreen'}, // command: {color: 'lightgreen'}, // errors: {color: '#f00'} // }, // Overrides to make the palette colors match KNOWN_HTML_TAGS: { img: {category: 'content'}, iframe: {category: 'content'}, span: {category: 'grouping'}, // Add center even though deprecated by WHATWG. center: {category: 'grouping'} } };
content/src/palette.js
function filterblocks(a) { // Show 'say' block only on browsers that support speech synthesis. if (!window.SpeechSynthesisUtterance || !window.speechSynthesis) { a = a.filter(function(b) { return !/^@?say\b/.test(b.block); }); } // Show 'listen' blocks only on browsers that support speech recognition. if (!window.webkitSpeechRecognition || window.SpeechRecognition) { a = a.filter(function(b) { return !/\blisten\b/.test(b.block); }); } return a.map(function(e) { if (!e.id) { // As the id (for logging), use the first (non-puncutation) word e.id = e.block.replace(/^\W*/, ''). replace(/^new /, '').replace(/\W.*$/, ''); // If that doesn't turn into anything, use the whole block text. if (!e.id) { e.id = e.block; } } return e; }); } // Recursive copy of a plain javascript object, while mapping // specified fields. function fieldmap(obj, map) { if (!obj || 'object' != typeof obj) { return obj; } var result; if (obj instanceof Array) { result = []; for (var j = 0; j < obj.length; ++j) { result.push(fieldmap(obj[j], map)); } } else { result = {}; for (var k in obj) if (obj.hasOwnProperty(k)) { if (map.hasOwnProperty(k)) { result[k] = map[k](obj[k]); } else { result[k] = fieldmap(obj[k], map); } } } return result; } function expand(palette, thisname) { var replacement = !thisname ? '' : (thisname + '.'); function replacer(s) { if (!s) return s; return s.replace(/@/, replacement); } return fieldmap(palette, { block: replacer, expansion: replacer }); } var distances = ['25', '50', '100', '200'], sdistances = ['100', '50', '-50', '-100'], angles = ['30', '45', '60', '90', '135', '144'], sangles = ['0', '90', '180', '270'], turntoarg = ['0', '90', '180', '270', 'lastclick', 'lastmouse'], sizes = ['10', '25', '50', '100'], scales = ['0.5', '2.0', '3.0'], randarg = ['100', '[true, false]', 'normal', 'position', 'color'], colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black']; var py_types = { distances: ['25', '50', '100', '200'], sdistances: ['100', '50', '-50', '-100'], angles: ['30', '45', '60', '90', '135', '144'], sangles: ['0', '90', '180', '270'], turntoarg: ['0', '90', '180', '270'],//, 'lastclick', 'lastmouse'], sizes: ['10', '25', '50', '100'], scales: ['0.5', '2.0', '3.0'], speeds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '0'], // randarg: ['100', '[true, false]', 'normal', 'position', 'color'], colors: ['\'red\'', '\'orange\'', '\'yellow\'', '\'green\'', '\'blue\'', '\'purple\'', '\'black\''] }; module.exports = { expand: expand, COFFEESCRIPT_PALETTE: [ { name: 'Move', color: 'lightblue', blocks: filterblocks([ { block: '@fd 100', title: 'Move forward' }, { block: '@rt 90', title: 'Turn right' }, { block: '@lt 90', title: 'Turn left' }, { block: '@bk 100', title: 'Move backward' }, { block: '@rt 180, 100', title: 'Make a wide right arc' }, { block: '@lt 180, 100', title: 'Make a wide left arc' }, { block: '@speed 10', title: 'Set the speed of the turtle' }, { block: '@speed Infinity', title: 'Use infinite speed' }, { block: '@home()', title: 'Jump to the origin, turned up' }, { block: '@turnto 270', title: 'Turn to an absolute direction' }, { block: '@moveto 100, 50', title: 'Move to coordinates' }, { block: '@movexy 30, 20', title: 'Move by changing x and y' }, { block: '@jumpto 100, 50', title: 'Jump to coordinates without drawing' }, { block: '@jumpxy 30, 20', title: 'Jump changing x and y without drawing' }, { block: '@pause 5', title: 'Do not move for five seconds' } ]) }, { name: 'Control', color: 'orange', blocks: filterblocks([ { block: 'for [1..3]\n ``', title: 'Do something multiple times' }, { block: 'for x in [0...10]\n ``', title: 'Repeat something while counting up x' }, { block: 'while `` < ``\n ``', title: ' Repeat while a condition is true' }, { block: 'if `` is ``\n ``', title: 'Do something only if a condition is true' }, { block: 'if `` is ``\n ``\nelse\n ``', title: 'Do something if a condition is true, otherwise something else', id: 'ifelse' }, { block: "forever 1, ->\n ``", title: 'Repeat something forever at qually-spaced times' }, { block: "button \'Click\', ->\n ``", title: 'Make a button and do something when clicked' }, { block: "keydown \'X\', ->\n ``", title: 'Do something when a keyboard key is pressed' }, { block: "click (e) ->\n ``", title: 'Do something when the mouse is clicked' } ]) }, { name: 'Art', color: 'purple', blocks: filterblocks([ { block: '@pen purple, 10', title: 'Set pen color and size' }, { block: '@dot green, 50', title: 'Make a dot' }, { block: '@box yellow, 50', title: 'Make a square' }, { block: '@fill blue', title: 'Fill traced shape' }, { block: '@wear \'apple\'', title: 'Use an image for the turtle' }, { block: 'img \'/img/bird\'', title: 'Write an image on the screen' }, { block: '@grow 3', title: 'Grow the size of the turtle' }, { block: '@hide()', title: 'Hide the main turtle' }, { block: '@show()', title: 'Show the main turtle' }, { block: 'cs()', title: 'Clear screen' }, { block: '@pu()', title: 'Lift the pen up' }, { block: '@pd()', title: 'Put the pen down' }, { block: '@drawon s', title: 'Draw on sprite s' }, { block: '@drawon document', title: 'Draw on the document' } ]) }, { name: 'Operators', color: 'lightgreen', blocks: filterblocks([ { block: 'x = 0', title: 'Set a variable', id: 'assign' }, { block: 'x += 1', title: 'Increase a variable', id: 'increment' }, { block: 'f = (x) ->\n ``', title: 'Define a new function', id: 'funcdef' }, { block: 'f(x)', title: 'Use a custom function', id: 'funccall' }, { block: '`` is ``', title: 'Compare two values', id: 'is' }, { block: '`` < ``', title: 'Compare two values', id: 'lessthan' }, { block: '`` > ``', title: 'Compare two values', id: 'greaterthan' }, { block: '`` + ``', title: 'Add two numbers', id: 'add' }, { block: '`` - ``', title: 'Subtract two numbers', id: 'subtract' }, { block: '`` * ``', title: 'Multiply two numbers', id: 'multiply' }, { block: '`` / ``', title: 'Divide two numbers', id: 'divide' }, { block: '`` and ``', title: 'True if both are true', id: 'and' }, { block: '`` or ``', title: 'True if either is true', id: 'or' }, { block: 'not ``', title: 'True if input is false', id: 'not' }, { block: 'random 6', title: 'Get a random number less than n' }, { block: 'round ``', title: 'Round to the nearest integer' }, { block: 'abs ``', title: 'Absolute value' }, { block: 'max ``, ``', title: 'Get the larger of two numbers' }, { block: 'min ``, ``', title: 'Get the smaller on two numbers' }, { block: 'x.match /pattern/', title: 'Test if a text pattern is found in x', id: 'match' } ]) }, { name: 'Text', color: 'pink', blocks: filterblocks([ { block: 'write \'Hello.\'', title: 'Write text in the document' }, { block: 'debug x', title: 'Log an object to debug' }, { block: 'type \'zz*(-.-)*zz\'', title: 'Typewrite text in the document' }, { block: 'typebox yellow', title: 'Type out a colored square' }, { block: 'typeline()', title: 'Type in a new line' }, { block: '@label \'spot\'', title: 'Write text at the turtle' }, { block: "await read '?', defer x", title: "Pause for input from the user" }, { block: "await readnum '?', defer x", title: "Pause for a number from the user" }, { block: 'read \'?\', (x) ->\n write x', title: 'Send input from the user to a function' }, { block: 'readnum \'?\', (x) ->\n write x', title: 'Send a number from the user to a function' } ]) }, { name: 'Sprites', color: 'teal', blocks: filterblocks([ { block: 't = new Turtle red', title: 'Make a new turtle', id: 'newturtle' }, { block: 's = new Sprite()', title: 'Make a blank sprite', id: 'newsprite' }, { block: 'p = new Piano()', title: 'Make a visible instrument', id: 'newpiano' }, { block: 'q = new Pencil()', title: 'Make an invisible and fast drawing sprite' }, { block: 'if @touches x\n ``', title: 'Do something only if touching the object x' }, { block: 'if @inside window\n ``', title: 'Do something only if inside the window' } ]) }, { name: 'Sound', color: 'indigo', blocks: filterblocks([ { block: '@play \'c G/G/ AG z\'', title: 'Play music notes in sequence' }, { block: '@play \'[fA] [ecG]2\'', title: 'Play notes in a chord' }, { block: '@tone \'B\', 2, 1', title: 'Sound a note immediately', id: 'toneNote' }, { block: '@tone \'B\', 0', title: 'Silence a note immediately', id: 'toneNote0' }, { block: '@tone 440, 2, 1', title: 'Sound a frequency immediately', id: 'toneHz' }, { block: '@tone 440, 0', title: 'Silence a frequency immediately', id: 'toneHz0' }, { block: '@silence()', title: 'Silence all notes' }, { block: "await listen defer x", title: "Pause for spoken words from the user" }, { block: 'listen (x) ->\n write x', title: 'Send spoken words from the user to a function' }, { block: '@say \'hello\'', title: 'Speak a word' }, { block: 'new Audio(url).play()', expansion: '(new Audio(\'https://upload.wikimedia.org/wikipedia/commons/1/11/06_-_Vivaldi_Summer_mvt_3_Presto_-_John_Harrison_violin.ogg\')).play()', title: 'Play an audio file' } ]) }, { name: 'Snippets', color: 'deeporange', blocks: filterblocks([ { block: "forever 10, ->\n turnto lastmouse\n fd 2", title: 'Continually move towards the last mouse position', id: "foreverFollowMouse" }, { block: "forever 10, ->\n if pressed 'W'\n fd 2", title: 'Poll a key and move while it is depressed', id: "foreverPollKey" }, { block: "forever 1, ->\n fd 25\n if not inside window\n stop()", title: 'Move once per second until not inside window', id: "foreverInsideWindow" }, { block: "click (e) ->\n moveto e", title: 'Move to a location when document is clicked', id: "foreverMovetoClick" }, { block: "button \'Click\', ->\n write 'clicked'", title: 'Make a button and do something when clicked', id: "buttonWrite" }, { block: "keydown \'X\', ->\n write 'x pressed'", title: 'Do something when a keyboard key is pressed', id: "keydownWrite" }, { block: "click (e) ->\n moveto e", title: 'Move to a location when document is clicked', id: "clickMove" } ]) } ], JAVASCRIPT_PALETTE: [ { name: 'Move', color: 'lightblue', blocks: filterblocks([ { block: '@fd(100);', title: 'Move forward' }, { block: '@rt(90);', title: 'Turn right' }, { block: '@lt(90);', title: 'Turn left' }, { block: '@bk(100);', title: 'Move backward' }, { block: '@rt(180, 100);', title: 'Make a wide right arc' }, { block: '@lt(180, 100);', title: 'Make a wide left arc' }, { block: '@speed(10);', title: 'Set the speed of the turtle' }, { block: '@speed(Infinity);', title: 'Use infinite speed' }, { block: '@home();', title: 'Jump to the origin, turned up' }, { block: '@turnto(270);', title: 'Turn to an absolute direction' }, { block: '@moveto(100, 50);', title: 'Move to coordinates' }, { block: '@movexy(30, 20);', title: 'Move by changing x and y' }, { block: '@jumpto(100, 50);', title: 'Jump to coordinates without drawing' }, { block: '@jumpxy(30, 20);', title: 'Jump changing x and y without drawing' } ]) }, { name: 'Control', color: 'orange', blocks: filterblocks([ { block: 'for (var j = 0; j < 3; ++j) {\n __\n}', title: 'Do something multiple times' }, { block: 'while (__ < __) {\n __\n}', title: ' Repeat while a condition is true' }, { block: 'if (__ === __) {\n __\n}', title: 'Do something only if a condition is true' }, { block: 'if (__ === __) {\n __\n} else {\n __\n}', title: 'Do something if a condition is true, otherwise something else', id: 'ifelse' }, { block: "forever(1, function() {\n __\n})", title: 'Repeat something forever at qually-spaced times' }, { block: "button(\'Click\', function() {\n __\n});", title: 'Make a button and do something when clicked' }, { block: "keydown(\'X\', function() {\n __\n});", title: 'Do something when a keyboard key is pressed' }, { block: "click(function(e) {\n __\n});", title: 'Do something when the mouse is clicked' } ]) }, { name: 'Art', color: 'purple', blocks: filterblocks([ { block: '@pen(purple, 10);', title: 'Set pen color and size' }, { block: '@dot(green, 50);', title: 'Make a dot' }, { block: '@box(yellow, 50);', title: 'Make a square' }, { block: '@fill(blue);', title: 'Fill traced shape' }, { block: '@wear(\'apple\');', title: 'Use an image for the turtle' }, { block: '@grow(3);', title: 'Grow the size of the turtle' }, { block: '@hide();', title: 'Hide the main turtle' }, { block: '@show();', title: 'Show the main turtle' }, { block: 'cs();', title: 'Clear screen' }, { block: '@pu();', title: 'Lift the pen up' }, { block: '@pd();', title: 'Put the pen down' }, { block: '@drawon(s);', title: 'Draw on sprite s' }, { block: '@drawon(document);', title: 'Draw on the document' } ]) }, { name: 'Operators', color: 'lightgreen', blocks: filterblocks([ { block: 'x = 0;', title: 'Set a variable', id: 'assign' }, { block: 'x += 1;', title: 'Increase a variable', }, { block: 'function f(x) {\n __\n}', title: 'Define a new function' }, { block: 'f(x)', title: 'Use a custom function' }, { block: '__ === __', title: 'Compare two values' }, { block: '__ < __', title: 'Compare two values' }, { block: '__ > __', title: 'Compare two values' }, { block: '__ + __', title: 'Add two numbers', id: 'add' }, { block: '__ - __', title: 'Subtract two numbers', id: 'subtract' }, { block: '__ * __', title: 'Multiply two numbers', id: 'multiply' }, { block: '__ / __', title: 'Divide two numbers', id: 'divide' }, { block: '__ && __', title: 'True if both are true', id: 'and' }, { block: '__ || __', title: 'True if either is true', id: 'or' }, { block: '!__', title: 'True if input is false', id: 'not' }, { block: 'random(6)', title: 'Get a random number less than n' }, { block: 'round(__)', title: 'Round to the nearest integer' }, { block: 'abs(__)', title: 'Absolute value' }, { block: 'max(__, __)', title: 'Get the larger of two numbers' }, { block: 'min(__, __)', title: 'Get the smaller on two numbers' }, { block: 'x.match(/pattern/)', title: 'Test if a text pattern is found in x' } ]) }, { name: 'Text', color: 'pink', blocks: filterblocks([ { block: 'write(\'Hello.\');', title: 'Write text in the document' }, { block: 'debug(x);', title: 'Log an object to debug' }, { block: 'type(\'zz*(-.-)*zz\');', title: 'Typewrite text in the document' }, { block: 'typebox(yellow);', title: 'Type out a colored square' }, { block: 'typeline();', title: 'Type in a new line' }, { block: '@label(\'spot\');', title: 'Write text at the turtle' }, { block: 'read(\'?\', function(x) {\n write(x);\n});', title: 'Send input from the user to a function' }, { block: 'readnum(\'?\', function(x) {\n write(x);\n});', title: 'Send a number from the user to a function' } ]) }, { name: 'Sprites', color: 'teal', blocks: filterblocks([ { block: 'var t = new Turtle(red);', title: 'Make a new turtle', id: 'newturtle' }, { block: 'var s = new Sprite();', title: 'Make a blank sprite', id: 'newsprite' }, { block: 'var p = new Piano();', title: 'Make a visible instrument', id: 'newpiano' }, { block: 'var q = new Pencil();', title: 'Make an invisible and fast drawing sprite' }, { block: 'if (@touches(x)) {\n __\n}', title: 'Do something only if touching the object x' }, { block: 'if (@inside(window)) {\n __\n}', title: 'Do something only if inside the window' } ]) }, { name: 'Sound', color: 'indigo', blocks: filterblocks([ { block: '@play(\'c G/G/ AG z\');', title: 'Play music notes in sequence' }, { block: '@play(\'[fA] [ecG]2\');', title: 'Play notes in a chord' }, { block: '@tone(\'B\', 2, 1);', title: 'Sound a note immediately' }, { block: '@tone(\'B\', 0);', title: 'Silence a note immediately' }, { block: '@tone(440, 2, 1);', title: 'Sound a frequency immediately' }, { block: '@tone(440, 0);', title: 'Silence a frequency immediately' }, { block: '@silence();', title: 'Silence all notes' }, { block: 'listen (function(x) {\n write(x);\n});', title: 'Send spoken words from the user to a function' }, { block: '@say(\'hello\');', title: 'Speak a word' }, { block: 'new Audio(url).play();', expansion: '(new Audio(\'https://upload.wikimedia.org/wikipedia/commons/1/11/06_-_Vivaldi_Summer_mvt_3_Presto_-_John_Harrison_violin.ogg\')).play();', title: 'Play an audio file' } ]) }, { name: 'Snippets', color: 'deeporange', blocks: filterblocks([ { block: "forever(10, function() {\n turnto(lastmouse);\n fd(2);\n});", title: 'Continually move towards the last mouse position' }, { block: "forever(10, function() {\n if (pressed('W')) {\n" + " fd(2);\n }\n});", title: 'Poll a key and move while it is depressed' }, { block: "forever(1, function() {\n fd(25);\n" + " if (!inside(window)) {\n stop();\n }\n});", title: 'Move once per second until not inside window' }, { block: "click(function(e) {\n moveto(e);\n});", title: 'Move to a location when document is clicked' }, { block: "button(\'Click\', function() {\n write('clicked');\n});", title: 'Make a button and do something when clicked' }, { block: "keydown(\'X\', function() {\n write('x pressed');\n});", title: 'Do something when a keyboard key is pressed' }, { block: "click(function(e) {\n moveto(e);\n});", title: 'Move to a location when document is clicked' } ]) } ], PYTHON_PALETTE: [ { name: 'Move', color: 'lightblue', blocks: filterblocks([ { block: 'fd(100)', title: 'Move forward' }, { block: 'bk(100)', title: 'Move backward' }, { block: 'rt(90)', title: 'Turn right' }, { block: 'lt(90)', title: 'Turn left' }, { block: 'ra(180, 100)', title: 'Make a wide right arc' }, { block: 'la(180, 100)', title: 'Make a wide left arc' }, { block: 'speed(10)', title: 'Set the speed of the turtle' }, { block: 'speed(0)', title: 'Use infinite speed' }, { block: 'home()', title: 'Jump to the origin, turned up' }, { block: 'turnto(270)', title: 'Turn to an absolute direction' }, { // block: '@turnto lastclick', // title: 'Turn toward a located object' // }, { block: 'moveto(100, 50)', title: 'Move to coordinates' }, { block: 'movexy(30, 20)', title: 'Move by changing x and y' }, { block: 'jumpto(100, 50)', title: 'Jump to coordinates without drawing' }, { block: 'jumpxy(30, 20)', title: 'Jump changing x and y without drawing' } ]) }, { name: 'Control', color: 'orange', blocks: filterblocks([ { block: 'for range(0,3):\n ``', title: 'Do something multiple times' }, { block: 'for x in range([0,10):\n ``', title: 'Repeat something while counting up x' }, { block: 'while `` < ``:\n ``', title: ' Repeat while a condition is true' }, { block: 'if `` == ``:\n ``', title: 'Do something only if a condition is true' }, { block: 'if `` == ``:\n ``\nelse:\n ``', title: 'Do something if a condition is true, otherwise something else', id: 'ifelse' // }, { // block: "forever 1, ->\n ``", // title: 'Repeat something forever at qually-spaced times' // }, { // block: "button \'Click\', ->\n ``", // title: 'Make a button and do something when clicked' // }, { // block: "keydown \'X\', ->\n ``", // title: 'Do something when a keyboard key is pressed' // }, { // block: "click (e) ->\n ``", // title: 'Do something when the mouse is clicked' } ]) }, { name: 'Art', color: 'purple', blocks: filterblocks([ { block: 'pen(\'purple\', 10)', title: 'Set pen color and size' }, { block: 'dot(\'green\', 50)', title: 'Make a dot' }, { // block: 'box(yellow, 50)', // title: 'Make a square' // }, { // block: '@fill blue', // title: 'Fill traced shape' // }, { // block: '@wear \'/img/apple\'', // title: 'Use an image for the turtle' // }, { // block: '@scale 3', // title: 'Scale turtle drawing' // }, { block: 'ht()', title: 'Hide the main turtle' }, { block: 'st()', title: 'Show the main turtle' }, { block: 'cs()', title: 'Clear screen' }, { block: 'pu()', title: 'Lift the pen up' }, { block: 'pd()', title: 'Put the pen down' // }, { // block: 'drawon s', // title: 'Draw on sprite s' // }, { // block: '@drawon document', // title: 'Draw on the document' } ]) } ], HTML_PALETTE: [ { name: "Metadata", color: "lightblue", blocks: [ { block: "<!DOCTYPE html>", title: "Defines document type" }, { block: "<html></html>", expansion: "<html>\n <head>\n \n </head>\n <body>\n \n </body>\n</html>", title: "Root of an HTML document" }, { block: "<head></head>", expansion: "<head>\n \n</head>", title: "Represents a collection of metadata" }, { block: "<title></title>", title: "Document's title or name" }, { block: "<link rel=\"\" href=\"\">", title: "Link between a document and an external resource" }, { block: "<meta charset=\"\">", title: "Metadata about the HTML document" }, { block: "<style></style>", expansion: "<style>\n \n</style>", title: "Define style information" }, { block: "<script></script>", expansion: "<script>\n \n</script>", title: "Define a client-side script, such as a JavaScript" } ] }, { name: "Grouping", color: "purple", blocks: [ { block: "<p></p>", expansion: "<p>\n \n</p>", title: "Represents a paragraph" }, { block: "<hr>", title: "Paragraph-level thematic break" }, { block: "<div></div>", expansion: "<div>\n \n</div>", title: "Defines a division" }, { block: "<span></span>", title: "Group inline-elements" }, { block: "<center></center>", title: "Defines a centered group" }, { block: "<ul></ul>", expansion: "<ul>\n \n</ul>", title: "Unordered list - Use 'ol' for ordered list" }, { block: "<li></li>", title: "List item" }, { block: "<dl></dl>", expansion: "<dl>\n \n</dl>", title: "Description list" }, { block: "<dt></dt>", title: "Term/name in a description list" }, { block: "<dd></dd>", title: "Description of a term" } ] }, { name: "Content", color: "lightgreen", blocks: [ { block: "<a href=\"\"></a>", title: "Defines a hyperlink, which is used to link from one page to another" }, { block: "<img src=\"\">", title: "Image" }, { block: "<iframe src=\"\"></iframe>", expansion: "<iframe>\n \n</iframe>", title: "Nested browsing context" }, { block: "<strong></strong>", title: "Strong importance, seriousness, or urgency for its contents" }, { block: "<em></em>", title: "Stress emphasis of its contents" }, { block: "<i></i>", title: "Italic" }, { block: "<b></b>", title: "Bold" }, { block: "<u></u>", title: "Underline" }, { block: "<sub></sub>", title: "Subscript" }, { block: "<sup></sup>", title: "Superscript" }, { block: "<br>", title: "Line break" } ] }, { name: "Sections", color: "orange", blocks: [ { block: "<body></body>", expansion: "<body>\n \n</body>", title: "Main content of the document" }, { block: "<h1></h1>", title: "Heading for its section" }, { block: "<h2></h2>", title: "Heading for its section" }, { block: "<h3></h3>", title: "Heading for its section" }, { block: "<article></article>", expansion: "<article>\n \n</article>", title: "Independent, self-contained content" }, { block: "<section></section>", expansion: "<section>\n \n</section>", title: "Generic section of a document or application" }, { block: "<nav></nav>", expansion: "<nav>\n \n</nav>", title: "Set of navigation links" }, { block: "<header></header>", expansion: "<header>\n \n</header>", title: "Group of introductory or navigational aids" }, { block: "<footer></footer>", expansion: "<footer>\n \n</footer>", title: "Footer for a document or section" } ] }, { name: "Table", color: "indigo", blocks: [ { block: "<table></table>", expansion: "<table>\n \n</table>", title: "Defines a table" }, { block: "<tr></tr>", expansion: "<tr>\n \n</tr>", title: "Row in a table" }, { block: "<td></td>", title: "Standard cell inside a table row" }, { block: "<th></th>", title: "Header cell inside a table row" } ] }, { name: "Form", color: "deeporange", blocks: [ { block: "<form action=\"\"></form>", expansion: "<form action=\"\">\n \n</form>", title: "Create an HTML form" }, { block: "<input type=\"\">", title: "Input field where user can enter data" }, { block: "<textarea></textarea>", expansion: "<textarea>\n \n</textarea>", title: "Multi-line text input" }, { block: "<label></label>", title: "Label for an input element" }, { block: "<button></button>", title: "Clickable button" }, { block: "<select></select>", expansion: "<select>\n \n</select>", title: "Drop-down list" }, { block: "<option></option>", expansion: "<option value=\"\"></option>", title: "Option in a <select> list" } ] } ], KNOWN_FUNCTIONS: { '?.fd': {color: 'lightblue', dropdown: [distances]}, '?.bk': {color: 'lightblue', dropdown: [distances]}, '?.rt': {color: 'lightblue', dropdown: [angles]}, '?.lt': {color: 'lightblue', dropdown: [angles]}, '?.slide': {color: 'lightblue', dropdown: [sdistances]}, '?.move': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.movexy': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.moveto': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.jump': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.jumpxy': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.jumpto': {color: 'lightblue', dropdown: [sdistances, sdistances]}, '?.turnto': {color: 'lightblue', dropdown: [turntoarg]}, '?.home': {color: 'lightblue'}, '?.pen': {color: 'purple', dropdown: [colors]}, '?.fill': {color: 'purple', dropdown: [colors]}, '?.dot': {color: 'purple', dropdown: [colors, sizes]}, '?.box': {color: 'purple', dropdown: [colors, sizes]}, '?.img': {color: 'purple'}, '?.mirror': {color: 'purple'}, '?.twist': {color: 'purple', dropdown: [sangles]}, '?.scale': {color: 'purple', dropdown: [scales]}, '?.grow': {color: 'purple', dropdown: [scales]}, '?.pause': {color: 'lightblue'}, '?.st': {color: 'purple'}, '?.ht': {color: 'purple'}, '?.show': {color: 'purple'}, '?.hide': {color: 'purple'}, '?.cs': {color: 'purple'}, '?.cg': {color: 'purple'}, '?.ct': {color: 'purple'}, '?.pu': {color: 'purple'}, '?.pd': {color: 'purple'}, '?.pe': {}, '?.pf': {}, '?.say': {color: 'indigo'}, '?.play': {color: 'indigo'}, '?.tone': {color: 'indigo'}, '?.silence': {color: 'indigo'}, '?.speed': {color:'lightblue'}, '?.wear': {color:'purple'}, '?.drawon': {color:'purple'}, '?.label': {color: 'pink'}, '?.reload': {}, remove: {color: 'pink'}, see: {}, sync: {}, send: {}, recv: {}, '?.click': {color: 'orange'}, '?.mousemove': {color: 'orange'}, '?.mouseup': {color: 'orange'}, '?.mousedown': {color: 'orange'}, '?.keyup': {color: 'orange'}, '?.keydown': {color: 'orange'}, '?.keypress': {color: 'orange'}, alert: {}, prompt: {}, '?.done': {}, tick: {color: 'orange'}, forever: {color: 'orange'}, stop: {color: 'orange'}, await: {color: 'orange'}, defer: {color: 'orange'}, type: {color: 'pink'}, typebox: {color: 'pink', dropdown: [colors]}, typeline: {color: 'pink'}, '*.sort': {}, debug: {color: 'pink'}, abs: {value: true, color: 'lightgreen'}, acos: {value: true, color: 'lightgreen'}, asin: {value: true, color: 'lightgreen'}, atan: {value: true, color: 'lightgreen'}, cos: {value: true, color: 'lightgreen'}, sin: {value: true, color: 'lightgreen'}, tan: {value: true, color: 'lightgreen'}, acosd: {value: true, color: 'lightgreen'}, asind: {value: true, color: 'lightgreen'}, atand: {value: true, color: 'lightgreen'}, cosd: {value: true, color: 'lightgreen'}, sind: {value: true, color: 'lightgreen'}, tand: {value: true, color: 'lightgreen'}, ceil: {value: true, color: 'lightgreen'}, floor: {value: true, color: 'lightgreen'}, round: {value: true, color: 'lightgreen'}, exp: {value: true, color: 'lightgreen'}, ln: {value: true, color: 'lightgreen'}, log10: {value: true, color: 'lightgreen'}, pow: {value: true, color: 'lightgreen'}, sqrt: {value: true, color: 'lightgreen'}, max: {value: true, color: 'lightgreen'}, min: {value: true, color: 'lightgreen'}, random: {value: true, color: 'lightgreen', dropdown: [randarg]}, 'Math.abs': {value: true, color: 'lightgreen'}, 'Math.acos': {value: true, color: 'lightgreen'}, 'Math.asin': {value: true, color: 'lightgreen'}, 'Math.atan': {value: true, color: 'lightgreen'}, 'Math.atan2': {value: true, color: 'lightgreen'}, 'Math.cos': {value: true, color: 'lightgreen'}, 'Math.sin': {value: true, color: 'lightgreen'}, 'Math.tan': {value: true, color: 'lightgreen'}, 'Math.ceil': {value: true, color: 'lightgreen'}, 'Math.floor': {value: true, color: 'lightgreen'}, 'Math.round': {value: true, color: 'lightgreen'}, 'Math.exp': {value: true, color: 'lightgreen'}, 'Math.log10': {value: true, color: 'lightgreen'}, 'Math.log2': {value: true, color: 'lightgreen'}, 'Math.log': {value: true, color: 'lightgreen'}, 'Math.pow': {value: true, color: 'lightgreen'}, 'Math.sqrt': {value: true, color: 'lightgreen'}, 'Math.max': {value: true, color: 'lightgreen'}, 'Math.min': {value: true, color: 'lightgreen'}, 'Math.random': {value: true, color: 'lightgreen'}, '?.pagexy': {value: true}, '?.getxy': {value: true, color:'lightblue'}, '?.direction': {value: true, color:'lightblue'}, '?.distance': {value: true, color:'lightblue'}, '?.shown': {value: true, color:'lightgreen'}, '?.hidden': {value: true, color:'lightgreen'}, '?.inside': {value: true, color:'lightgreen'}, '?.touches': {value: true, color:'lightgreen'}, '?.within': {value: true, color:'lightgreen'}, '?.notwithin': {value: true, color:'lightgreen'}, '?.nearest': {value: true}, '?.pressed': {value: true, color:'lightgreen'}, '?.canvas': {value: true}, hsl: {value: true}, hsla: {value: true}, rgb: {value: true}, rgba: {value: true}, '*.cell': {value: true}, '$': {value: true}, '*.match': {value: true, color:'lightgreen'}, '*.toString': {value: true}, '*.charCodeAt': {value: true}, '*.fromCharCode': {value: true}, '*.exec': {value: true}, '*.test': {value: true}, '*.split': {value: true}, '*.join': {value: true}, button: {value: true, command: true, color: 'orange'}, read: {value: true, command: true, color: 'pink'}, readstr: {value: true, command: true, color: 'pink'}, readnum: {value: true, command: true, color: 'pink'}, listen: {value: true, command: true, color: 'indigo'}, write: {value: true, command: true, color: 'pink'}, img: {value: true, command: true, color: 'purple'}, table: {value: true, command: true, color: 'yellow'}, '*.splice': {value: true, command: true}, '*.append': {value: true, command: true}, '*.finish': {value: true, command: true}, '*.text': {value: true, command: true, color: 'pink'}, loadscript: {value: true, command: true}, Date: {value: true, color: 'lightgreen'}, Audio: {value: true, color: 'indigo'}, Turtle: {value: true, color: 'teal'}, Sprite: {value: true, color: 'teal'}, Piano: {value: true, color: 'teal'}, Pencil: {value: true, color: 'teal'} }, PYTHON_FUNCTIONS: { // '*.fd': {color: 'purple'} // '?.fd': {color: 'purple'} 'fd': {color: 'lightblue', dropdown: [py_types.distances]}, 'bk': {color: 'lightblue', dropdown: [py_types.distances]}, 'rt': {color: 'lightblue', dropdown: [py_types.angles]}, 'lt': {color: 'lightblue', dropdown: [py_types.angles]}, 'ra': {color: 'lightblue', dropdown: [py_types.angles, py_types.distances]}, 'la': {color: 'lightblue', dropdown: [py_types.angles, py_types.distances]}, 'speed': {color: 'lightblue', drown: [py_types.speeds]}, 'home': {color: 'lightblue'}, 'turnto': {color: 'lightblue', dropdown: [py_types.angles]}, 'moveto': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'movexy': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'jumpto': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'jumpxy': {color: 'lightblue', dropdown: [py_types.sdistances, py_types.sdistances]}, 'pen': {color: 'purple', dropdown: [py_types.colors, py_types.sizes]}, 'dot': {color: 'purple', dropdown: [py_types.colors, py_types.sizes]}, 'st': {color: 'purple'}, 'ht': {color: 'purple'}, 'cs': {color: 'purple'}, 'pu': {color: 'purple'}, 'pd': {color: 'purple'}, /* '?.slide': {color: 'lightblue', dropdown: [sdistances]}, '?.fill': {color: 'purple', dropdown: [colors]}, '?.box': {color: 'purple', dropdown: [colors, sizes]}, '?.mirror': {color: 'purple'}, '?.twist': {color: 'purple', dropdown: [sangles]}, '?.scale': {color: 'purple', dropdown: [scales]}, '?.pause': {}, '?.cg': {color: 'purple'}, '?.ct': {color: 'purple'}, '?.pe': {}, '?.pf': {}, '?.say': {color: 'indigo'}, '?.play': {color: 'indigo'}, '?.tone': {color: 'indigo'}, '?.silence': {color: 'indigo'}, '?.speed': {color:'lightblue'}, '?.wear': {color:'purple'}, '?.drawon': {color:'purple'}, '?.label': {color: 'pink'}, '?.reload': {}, see: {}, sync: {}, send: {}, recv: {}, '?.click': {color: 'orange'}, '?.mousemove': {color: 'orange'}, '?.mouseup': {color: 'orange'}, '?.mousedown': {color: 'orange'}, '?.keyup': {color: 'orange'}, '?.keydown': {color: 'orange'}, '?.keypress': {color: 'orange'}, alert: {}, prompt: {}, '?.done': {}, tick: {color: 'orange'}, forever: {color: 'orange'}, stop: {color: 'orange'}, await: {color: 'orange'}, defer: {color: 'orange'}, type: {color: 'pink'}, '*.sort': {}, log: {color: 'pink'}, abs: {value: true, color: 'lightgreen'}, acos: {value: true, color: 'lightgreen'}, asin: {value: true, color: 'lightgreen'}, atan: {value: true, color: 'lightgreen'}, atan2: {value: true, color: 'lightgreen'}, cos: {value: true, color: 'lightgreen'}, sin: {value: true, color: 'lightgreen'}, tan: {value: true, color: 'lightgreen'}, ceil: {value: true, color: 'lightgreen'}, floor: {value: true, color: 'lightgreen'}, round: {value: true, color: 'lightgreen'}, exp: {value: true, color: 'lightgreen'}, ln: {value: true, color: 'lightgreen'}, log10: {value: true, color: 'lightgreen'}, pow: {value: true, color: 'lightgreen'}, sqrt: {value: true, color: 'lightgreen'}, max: {value: true, color: 'lightgreen'}, min: {value: true, color: 'lightgreen'}, random: {value: true, color: 'lightgreen'}, 'Math.abs': {value: true, color: 'lightgreen'}, 'Math.acos': {value: true, color: 'lightgreen'}, 'Math.asin': {value: true, color: 'lightgreen'}, 'Math.atan': {value: true, color: 'lightgreen'}, 'Math.atan2': {value: true, color: 'lightgreen'}, 'Math.cos': {value: true, color: 'lightgreen'}, 'Math.sin': {value: true, color: 'lightgreen'}, 'Math.tan': {value: true, color: 'lightgreen'}, 'Math.ceil': {value: true, color: 'lightgreen'}, 'Math.floor': {value: true, color: 'lightgreen'}, 'Math.round': {value: true, color: 'lightgreen'}, 'Math.exp': {value: true, color: 'lightgreen'}, 'Math.log10': {value: true, color: 'lightgreen'}, 'Math.log2': {value: true, color: 'lightgreen'}, 'Math.log': {value: true, color: 'lightgreen'}, 'Math.pow': {value: true, color: 'lightgreen'}, 'Math.sqrt': {value: true, color: 'lightgreen'}, 'Math.max': {value: true, color: 'lightgreen'}, 'Math.min': {value: true, color: 'lightgreen'}, 'Math.random': {value: true, color: 'lightgreen'}, '?.pagexy': {value: true}, '?.getxy': {value: true, color:'lightblue'}, '?.direction': {value: true, color:'lightblue'}, '?.distance': {value: true, color:'lightblue'}, '?.shown': {value: true, color:'lightgreen'}, '?.hidden': {value: true, color:'lightgreen'}, '?.inside': {value: true, color:'lightgreen'}, '?.touches': {value: true, color:'lightgreen'}, '?.within': {value: true, color:'lightgreen'}, '?.notwithin': {value: true, color:'lightgreen'}, '?.nearest': {value: true}, '?.pressed': {value: true, color:'lightgreen'}, '?.canvas': {value: true}, hsl: {value: true}, hsla: {value: true}, rgb: {value: true}, rgba: {value: true}, '*.cell': {value: true}, '$': {value: true}, '*.match': {value: true, color:'lightgreen'}, '*.toString': {value: true}, '*.charCodeAt': {value: true}, '*.fromCharCode': {value: true}, '*.exec': {value: true}, '*.test': {value: true}, '*.split': {value: true}, '*.join': {value: true}, button: {value: true, command: true, color: 'orange'}, read: {value: true, command: true, color: 'pink'}, readstr: {value: true, command: true, color: 'pink'}, readnum: {value: true, command: true, color: 'pink'}, write: {value: true, command: true, color: 'pink'}, table: {value: true, command: true, color: 'yellow'}, '*.splice': {value: true, command: true}, '*.append': {value: true, command: true}, '*.finish': {value: true, command: true}, '*.text': {value: true, command: true, color: 'pink'}, loadscript: {value: true, command: true}, Turtle: {value: true, color: 'teal'}, Sprite: {value: true, color: 'teal'}, Piano: {value: true, color: 'teal'}, Pencil: {value: true, color: 'teal'}*/ }, CATEGORIES: { functions: {color: 'lightgreen'}, returns: {color: 'yellow'}, comments: {color: 'gray'}, arithmetic: {color: 'lightgreen'}, logic: {color: 'lightgreen'}, containers: {color: 'teal'}, assignments: {color: 'lightgreen'}, loops: {color: 'orange'}, conditionals: {color: 'orange'}, value: {color: 'lightgreen'}, command: {color: 'lightgreen'}, errors: {color: '#f00'} }, // PYTHON_CATEGORIES: { // functions: {color: 'lightgreen'}, // returns: {color: 'yellow'}, // comments: {color: 'gray'}, // arithmetic: {color: 'lightgreen'}, // logic: {color: 'lightgreen'}, // containers: {color: 'teal'}, // assignments: {color: 'lightgreen'}, // loops: {color: 'orange'}, // conditionals: {color: 'orange'}, // value: {color: 'lightgreen'}, // command: {color: 'lightgreen'}, // errors: {color: '#f00'} // }, // Overrides to make the palette colors match KNOWN_HTML_TAGS: { img: {category: 'content'}, iframe: {category: 'content'}, span: {category: 'grouping'}, // Add center even though deprecated by WHATWG. center: {category: 'grouping'} } };
Updated palette to fix issues temporarily
content/src/palette.js
Updated palette to fix issues temporarily
<ide><path>ontent/src/palette.js <ide> color: 'orange', <ide> blocks: filterblocks([ <ide> { <del> block: 'for range(0,3):\n ``', <del> title: 'Do something multiple times' <del> }, { <del> block: 'for x in range([0,10):\n ``', <add> block: "for x in range(0, 10):\n pass", <ide> title: 'Repeat something while counting up x' <ide> }, { <del> block: 'while `` < ``:\n ``', <add> block: 'while 0 < 10:\n pass', <ide> title: ' Repeat while a condition is true' <ide> }, { <del> block: 'if `` == ``:\n ``', <add> block: 'if 0 == 0:\n pass', <ide> title: 'Do something only if a condition is true' <ide> }, { <del> block: 'if `` == ``:\n ``\nelse:\n ``', <add> block: 'if 0 == 0:\n pass\nelse:\n pass', <ide> title: <ide> 'Do something if a condition is true, otherwise something else', <ide> id: 'ifelse' <del>// }, { <del>// block: "forever 1, ->\n ``", <del>// title: 'Repeat something forever at qually-spaced times' <del>// }, { <del>// block: "button \'Click\', ->\n ``", <del>// title: 'Make a button and do something when clicked' <del>// }, { <del>// block: "keydown \'X\', ->\n ``", <del>// title: 'Do something when a keyboard key is pressed' <del>// }, { <del>// block: "click (e) ->\n ``", <del>// title: 'Do something when the mouse is clicked' <add>/* }, { <add> block: "forever 1, ->\n ``", <add> title: 'Repeat something forever at qually-spaced times' <add> }, { <add> block: "button \'Click\', ->\n ``", <add> title: 'Make a button and do something when clicked' <add> }, { <add> block: "keydown \'X\', ->\n ``", <add> title: 'Do something when a keyboard key is pressed' <add> }, { <add> block: "click (e) ->\n ``", <add> title: 'Do something when the mouse is clicked'*/ <ide> } <ide> ]) <ide> }, {
Java
apache-2.0
c98d19d884d0f4115b9eb439be5097b3e80ab5d7
0
dslomov/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,petteyg/intellij-community,apixandru/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,izonder/intellij-community,izonder/intellij-community,FHannes/intellij-community,ryano144/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,dslomov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,signed/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,da1z/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,diorcety/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,retomerz/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,kdwink/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,kool79/intellij-community,amith01994/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,kool79/intellij-community,kool79/intellij-community,caot/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,allotria/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,kdwink/intellij-community,supersven/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,asedunov/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,petteyg/intellij-community,clumsy/intellij-community,hurricup/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,holmes/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,signed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,FHannes/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,caot/intellij-community,kool79/intellij-community,kool79/intellij-community,kool79/intellij-community,wreckJ/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,signed/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,samthor/intellij-community,caot/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,hurricup/intellij-community,asedunov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ibinti/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ibinti/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,holmes/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,da1z/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,signed/intellij-community,hurricup/intellij-community,slisson/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,SerCeMan/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,ryano144/intellij-community,clumsy/intellij-community,fnouama/intellij-community,allotria/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,kdwink/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,jagguli/intellij-community,vladmm/intellij-community,da1z/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,samthor/intellij-community,robovm/robovm-studio,hurricup/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ibinti/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,diorcety/intellij-community,semonte/intellij-community,tmpgit/intellij-community,semonte/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,da1z/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,izonder/intellij-community,asedunov/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,slisson/intellij-community,caot/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,signed/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,petteyg/intellij-community,slisson/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,izonder/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,signed/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,clumsy/intellij-community,kdwink/intellij-community,signed/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,da1z/intellij-community,ibinti/intellij-community,signed/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,caot/intellij-community,vladmm/intellij-community,supersven/intellij-community,ibinti/intellij-community,FHannes/intellij-community,kool79/intellij-community,ibinti/intellij-community,semonte/intellij-community,holmes/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,clumsy/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,supersven/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,slisson/intellij-community,hurricup/intellij-community,diorcety/intellij-community,da1z/intellij-community,samthor/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,samthor/intellij-community,ibinti/intellij-community,dslomov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,orekyuu/intellij-community,allotria/intellij-community,caot/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,apixandru/intellij-community,robovm/robovm-studio,blademainer/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,caot/intellij-community,caot/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,kool79/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,petteyg/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,diorcety/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,suncycheng/intellij-community,holmes/intellij-community,izonder/intellij-community,Distrotech/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,adedayo/intellij-community,da1z/intellij-community,Distrotech/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,caot/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,hurricup/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,apixandru/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,allotria/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,dslomov/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,diorcety/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,xfournet/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,allotria/intellij-community,supersven/intellij-community,fitermay/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,dslomov/intellij-community,supersven/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,allotria/intellij-community,semonte/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,adedayo/intellij-community,holmes/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,nicolargo/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community
package com.intellij.remoteServer.impl.configuration; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonShortcuts; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.OptionalConfigurable; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.openapi.ui.NamedConfigurable; import com.intellij.openapi.util.Condition; import com.intellij.remoteServer.ServerType; import com.intellij.remoteServer.configuration.RemoteServer; import com.intellij.remoteServer.configuration.RemoteServersManager; import com.intellij.util.IconUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.text.UniqueNameGenerator; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author nik */ public class RemoteServerListConfigurable extends MasterDetailsComponent implements OptionalConfigurable, SearchableConfigurable { private final RemoteServersManager myServersManager; @Nullable private final ServerType<?> myServerType; private RemoteServer<?> myLastSelectedServer; public RemoteServerListConfigurable(@NotNull RemoteServersManager manager) { this(manager, null); } private RemoteServerListConfigurable(@NotNull RemoteServersManager manager, @Nullable ServerType<?> type) { myServersManager = manager; myServerType = type; initTree(); } public static RemoteServerListConfigurable createConfigurable(@NotNull ServerType<?> type) { return new RemoteServerListConfigurable(RemoteServersManager.getInstance(), type); } @Nls @Override public String getDisplayName() { return "Clouds"; } @Override public void reset() { myRoot.removeAllChildren(); List<RemoteServer<?>> servers = getServers(); for (RemoteServer<?> server : servers) { addServerNode(server, false); } super.reset(); } private List<RemoteServer<?>> getServers() { if (myServerType == null) { return myServersManager.getServers(); } else { //code won't compile without this ugly cast (at least in jdk 1.6) return (List<RemoteServer<?>>)((List)myServersManager.getServers(myServerType)); } } private MyNode addServerNode(RemoteServer<?> server, boolean isNew) { MyNode node = new MyNode(new SingleRemoteServerConfigurable(server, TREE_UPDATER, isNew)); addNode(node, myRoot); return node; } @NotNull @Override public String getId() { return "RemoteServers"; } @Nullable @Override public Runnable enableSearch(String option) { return null; } @Override protected void processRemovedItems() { Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(); for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) { servers.add(configurable.getEditableObject()); } List<RemoteServer<?>> toDelete = new ArrayList<RemoteServer<?>>(); for (RemoteServer<?> server : getServers()) { if (!servers.contains(server)) { toDelete.add(server); } } for (RemoteServer<?> server : toDelete) { myServersManager.removeServer(server); } } @Override public void apply() throws ConfigurationException { super.apply(); Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(getServers()); for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) { RemoteServer<?> server = configurable.getEditableObject(); server.setName(configurable.getDisplayName()); if (!servers.contains(server)) { myServersManager.addServer(server); } } } @Nullable @Override protected ArrayList<AnAction> createActions(boolean fromPopup) { ArrayList<AnAction> actions = new ArrayList<AnAction>(); if (myServerType == null) { actions.add(new AddRemoteServerGroup()); } else { actions.add(new AddRemoteServerAction(myServerType, IconUtil.getAddIcon())); } actions.add(new MyDeleteAction()); return actions; } @Override public boolean needDisplay() { return ServerType.EP_NAME.getExtensions().length > 0; } @Override protected boolean wasObjectStored(Object editableObject) { return true; } @Override public String getHelpTopic() { return ObjectUtils.notNull(super.getHelpTopic(), "reference.settings.clouds"); } @Override public void disposeUIResources() { Object selectedObject = getSelectedObject(); myLastSelectedServer = selectedObject instanceof RemoteServer<?> ? (RemoteServer)selectedObject : null; super.disposeUIResources(); } @Nullable public RemoteServer<?> getLastSelectedServer() { return myLastSelectedServer; } private List<NamedConfigurable<RemoteServer<?>>> getConfiguredServers() { List<NamedConfigurable<RemoteServer<?>>> configurables = new ArrayList<NamedConfigurable<RemoteServer<?>>>(); for (int i = 0; i < myRoot.getChildCount(); i++) { MyNode node = (MyNode)myRoot.getChildAt(i); configurables.add((NamedConfigurable<RemoteServer<?>>)node.getConfigurable()); } return configurables; } private class AddRemoteServerGroup extends ActionGroup implements ActionGroupWithPreselection { private AddRemoteServerGroup() { super("Add", "", IconUtil.getAddIcon()); registerCustomShortcutSet(CommonShortcuts.INSERT, myTree); } @NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { ServerType[] serverTypes = ServerType.EP_NAME.getExtensions(); AnAction[] actions = new AnAction[serverTypes.length]; for (int i = 0; i < serverTypes.length; i++) { actions[i] = new AddRemoteServerAction(serverTypes[i], serverTypes[i].getIcon()); } return actions; } @Override public ActionGroup getActionGroup() { return this; } @Override public int getDefaultIndex() { return 0; } } private class AddRemoteServerAction extends DumbAwareAction { private final ServerType<?> myServerType; private AddRemoteServerAction(ServerType<?> serverType, final Icon icon) { super(serverType.getPresentableName(), null, icon); myServerType = serverType; } @Override public void actionPerformed(AnActionEvent e) { String name = UniqueNameGenerator.generateUniqueName(myServerType.getPresentableName(), new Condition<String>() { @Override public boolean value(String s) { for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) { if (configurable.getDisplayName().equals(s)) { return false; } } return true; } }); MyNode node = addServerNode(myServersManager.createServer(myServerType, name), true); selectNodeInTree(node); } } }
platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java
package com.intellij.remoteServer.impl.configuration; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonShortcuts; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.OptionalConfigurable; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.MasterDetailsComponent; import com.intellij.openapi.ui.NamedConfigurable; import com.intellij.openapi.util.Condition; import com.intellij.remoteServer.ServerType; import com.intellij.remoteServer.configuration.RemoteServer; import com.intellij.remoteServer.configuration.RemoteServersManager; import com.intellij.util.IconUtil; import com.intellij.util.text.UniqueNameGenerator; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author nik */ public class RemoteServerListConfigurable extends MasterDetailsComponent implements OptionalConfigurable, SearchableConfigurable { private final RemoteServersManager myServersManager; @Nullable private final ServerType<?> myServerType; private RemoteServer<?> myLastSelectedServer; public RemoteServerListConfigurable(@NotNull RemoteServersManager manager) { this(manager, null); } private RemoteServerListConfigurable(@NotNull RemoteServersManager manager, @Nullable ServerType<?> type) { myServersManager = manager; myServerType = type; initTree(); } public static RemoteServerListConfigurable createConfigurable(@NotNull ServerType<?> type) { return new RemoteServerListConfigurable(RemoteServersManager.getInstance(), type); } @Nls @Override public String getDisplayName() { return "Clouds"; } @Override public void reset() { myRoot.removeAllChildren(); List<RemoteServer<?>> servers = getServers(); for (RemoteServer<?> server : servers) { addServerNode(server, false); } super.reset(); } private List<RemoteServer<?>> getServers() { if (myServerType == null) { return myServersManager.getServers(); } else { //code won't compile without this ugly cast (at least in jdk 1.6) return (List<RemoteServer<?>>)((List)myServersManager.getServers(myServerType)); } } private MyNode addServerNode(RemoteServer<?> server, boolean isNew) { MyNode node = new MyNode(new SingleRemoteServerConfigurable(server, TREE_UPDATER, isNew)); addNode(node, myRoot); return node; } @NotNull @Override public String getId() { return "RemoteServers"; } @Nullable @Override public Runnable enableSearch(String option) { return null; } @Override protected void processRemovedItems() { Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(); for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) { servers.add(configurable.getEditableObject()); } List<RemoteServer<?>> toDelete = new ArrayList<RemoteServer<?>>(); for (RemoteServer<?> server : getServers()) { if (!servers.contains(server)) { toDelete.add(server); } } for (RemoteServer<?> server : toDelete) { myServersManager.removeServer(server); } } @Override public void apply() throws ConfigurationException { super.apply(); Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(getServers()); for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) { RemoteServer<?> server = configurable.getEditableObject(); server.setName(configurable.getDisplayName()); if (!servers.contains(server)) { myServersManager.addServer(server); } } } @Nullable @Override protected ArrayList<AnAction> createActions(boolean fromPopup) { ArrayList<AnAction> actions = new ArrayList<AnAction>(); if (myServerType == null) { actions.add(new AddRemoteServerGroup()); } else { actions.add(new AddRemoteServerAction(myServerType, IconUtil.getAddIcon())); } actions.add(new MyDeleteAction()); return actions; } @Override public boolean needDisplay() { return ServerType.EP_NAME.getExtensions().length > 0; } @Override protected boolean wasObjectStored(Object editableObject) { return true; } @Override public void disposeUIResources() { Object selectedObject = getSelectedObject(); myLastSelectedServer = selectedObject instanceof RemoteServer<?> ? (RemoteServer)selectedObject : null; super.disposeUIResources(); } @Nullable public RemoteServer<?> getLastSelectedServer() { return myLastSelectedServer; } private List<NamedConfigurable<RemoteServer<?>>> getConfiguredServers() { List<NamedConfigurable<RemoteServer<?>>> configurables = new ArrayList<NamedConfigurable<RemoteServer<?>>>(); for (int i = 0; i < myRoot.getChildCount(); i++) { MyNode node = (MyNode)myRoot.getChildAt(i); configurables.add((NamedConfigurable<RemoteServer<?>>)node.getConfigurable()); } return configurables; } private class AddRemoteServerGroup extends ActionGroup implements ActionGroupWithPreselection { private AddRemoteServerGroup() { super("Add", "", IconUtil.getAddIcon()); registerCustomShortcutSet(CommonShortcuts.INSERT, myTree); } @NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent e) { ServerType[] serverTypes = ServerType.EP_NAME.getExtensions(); AnAction[] actions = new AnAction[serverTypes.length]; for (int i = 0; i < serverTypes.length; i++) { actions[i] = new AddRemoteServerAction(serverTypes[i], serverTypes[i].getIcon()); } return actions; } @Override public ActionGroup getActionGroup() { return this; } @Override public int getDefaultIndex() { return 0; } } private class AddRemoteServerAction extends DumbAwareAction { private final ServerType<?> myServerType; private AddRemoteServerAction(ServerType<?> serverType, final Icon icon) { super(serverType.getPresentableName(), null, icon); myServerType = serverType; } @Override public void actionPerformed(AnActionEvent e) { String name = UniqueNameGenerator.generateUniqueName(myServerType.getPresentableName(), new Condition<String>() { @Override public boolean value(String s) { for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) { if (configurable.getDisplayName().equals(s)) { return false; } } return true; } }); MyNode node = addServerNode(myServersManager.createServer(myServerType, name), true); selectNodeInTree(node); } } }
IDEA-130752: Help available for Settings/Clouds
platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java
IDEA-130752: Help available for Settings/Clouds
<ide><path>latform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java <ide> import com.intellij.remoteServer.configuration.RemoteServer; <ide> import com.intellij.remoteServer.configuration.RemoteServersManager; <ide> import com.intellij.util.IconUtil; <add>import com.intellij.util.ObjectUtils; <ide> import com.intellij.util.text.UniqueNameGenerator; <ide> import org.jetbrains.annotations.Nls; <ide> import org.jetbrains.annotations.NotNull; <ide> @Override <ide> protected boolean wasObjectStored(Object editableObject) { <ide> return true; <add> } <add> <add> @Override <add> public String getHelpTopic() { <add> return ObjectUtils.notNull(super.getHelpTopic(), "reference.settings.clouds"); <ide> } <ide> <ide> @Override
Java
apache-2.0
c10c80d56ccc99bbf9c01d1b3f68b0276306b676
0
allotria/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,izonder/intellij-community,petteyg/intellij-community,ibinti/intellij-community,amith01994/intellij-community,xfournet/intellij-community,supersven/intellij-community,hurricup/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,FHannes/intellij-community,izonder/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,signed/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,allotria/intellij-community,slisson/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,slisson/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,supersven/intellij-community,dslomov/intellij-community,kool79/intellij-community,holmes/intellij-community,izonder/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,kool79/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,allotria/intellij-community,dslomov/intellij-community,clumsy/intellij-community,kool79/intellij-community,jagguli/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,kool79/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,clumsy/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,supersven/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,clumsy/intellij-community,dslomov/intellij-community,allotria/intellij-community,ryano144/intellij-community,holmes/intellij-community,amith01994/intellij-community,amith01994/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,samthor/intellij-community,da1z/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,asedunov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,signed/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,fnouama/intellij-community,holmes/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,fitermay/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,izonder/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,holmes/intellij-community,semonte/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,diorcety/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,semonte/intellij-community,jagguli/intellij-community,holmes/intellij-community,clumsy/intellij-community,semonte/intellij-community,youdonghai/intellij-community,kool79/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ibinti/intellij-community,slisson/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,ibinti/intellij-community,kool79/intellij-community,supersven/intellij-community,allotria/intellij-community,caot/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,supersven/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,kool79/intellij-community,semonte/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,signed/intellij-community,signed/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ryano144/intellij-community,vladmm/intellij-community,robovm/robovm-studio,petteyg/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fitermay/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,dslomov/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,signed/intellij-community,kdwink/intellij-community,amith01994/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,kdwink/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,gnuhub/intellij-community,supersven/intellij-community,vladmm/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,amith01994/intellij-community,fnouama/intellij-community,holmes/intellij-community,asedunov/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,adedayo/intellij-community,izonder/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,da1z/intellij-community,xfournet/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,samthor/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,caot/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,retomerz/intellij-community,robovm/robovm-studio,caot/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,apixandru/intellij-community,semonte/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,allotria/intellij-community,samthor/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,signed/intellij-community,supersven/intellij-community,da1z/intellij-community,diorcety/intellij-community,asedunov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,vladmm/intellij-community,clumsy/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,TangHao1987/intellij-community,caot/intellij-community,gnuhub/intellij-community,samthor/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,caot/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ryano144/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,slisson/intellij-community,diorcety/intellij-community,amith01994/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ibinti/intellij-community,hurricup/intellij-community,supersven/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,kool79/intellij-community,apixandru/intellij-community,samthor/intellij-community,wreckJ/intellij-community,izonder/intellij-community,gnuhub/intellij-community,caot/intellij-community,allotria/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,retomerz/intellij-community,da1z/intellij-community,tmpgit/intellij-community,da1z/intellij-community,petteyg/intellij-community,FHannes/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,hurricup/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,holmes/intellij-community,amith01994/intellij-community,signed/intellij-community,jagguli/intellij-community,asedunov/intellij-community,semonte/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,jagguli/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,kool79/intellij-community,signed/intellij-community,semonte/intellij-community,supersven/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,retomerz/intellij-community,signed/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,robovm/robovm-studio,semonte/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,izonder/intellij-community,Lekanich/intellij-community,slisson/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,caot/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ibinti/intellij-community,da1z/intellij-community,caot/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,petteyg/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,dslomov/intellij-community,dslomov/intellij-community,ibinti/intellij-community,allotria/intellij-community,slisson/intellij-community,dslomov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,semonte/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community
/* * Copyright 2000-2013 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 com.intellij.openapi.fileEditor.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorProvider; import com.intellij.openapi.fileEditor.FileEditorState; import com.intellij.openapi.fileEditor.FileEditorStateLevel; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; /** * Author: msk */ public class EditorWithProviderComposite extends EditorComposite { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.EditorWithProviderComposite"); private FileEditorProvider[] myProviders; EditorWithProviderComposite(@NotNull VirtualFile file, @NotNull FileEditor[] editors, @NotNull FileEditorProvider[] providers, @NotNull FileEditorManagerEx fileEditorManager) { super(file, editors, fileEditorManager); myProviders = providers; } @NotNull public FileEditorProvider[] getProviders() { return myProviders; } @Override public boolean isModified() { final FileEditor[] editors = getEditors(); for (FileEditor editor : editors) { if (editor.isModified()) { return true; } } return false; } @Override @NotNull public Pair<FileEditor, FileEditorProvider> getSelectedEditorWithProvider() { LOG.assertTrue(myEditors.length > 0, myEditors.length); if (myEditors.length == 1) { LOG.assertTrue(myTabbedPaneWrapper == null); return Pair.create(myEditors[0], myProviders[0]); } else { // we have to get myEditor from tabbed pane LOG.assertTrue(myTabbedPaneWrapper != null); int index = myTabbedPaneWrapper.getSelectedIndex(); if (index == -1) { index = 0; } LOG.assertTrue(index >= 0, index); LOG.assertTrue(index < myEditors.length, index); return Pair.create(myEditors[index], myProviders[index]); } } @NotNull public HistoryEntry currentStateAsHistoryEntry() { final FileEditor[] editors = getEditors(); final FileEditorState[] states = new FileEditorState[editors.length]; for (int j = 0; j < states.length; j++) { states[j] = editors[j].getState(FileEditorStateLevel.FULL); LOG.assertTrue(states[j] != null); } final int selectedProviderIndex = ArrayUtil.find(editors, getSelectedEditor()); LOG.assertTrue(selectedProviderIndex != -1); final FileEditorProvider[] providers = getProviders(); return new HistoryEntry(getFile(), providers, states, providers[selectedProviderIndex]); } public void addEditor(FileEditor editor, FileEditorProvider provider) { addEditor(editor); myProviders = ArrayUtil.append(myProviders, provider); } }
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWithProviderComposite.java
/* * Copyright 2000-2013 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 com.intellij.openapi.fileEditor.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorProvider; import com.intellij.openapi.fileEditor.FileEditorState; import com.intellij.openapi.fileEditor.FileEditorStateLevel; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; /** * Author: msk */ public class EditorWithProviderComposite extends EditorComposite { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.EditorWithProviderComposite"); private FileEditorProvider[] myProviders; EditorWithProviderComposite(@NotNull VirtualFile file, @NotNull FileEditor[] editors, @NotNull FileEditorProvider[] providers, @NotNull FileEditorManagerEx fileEditorManager) { super(file, editors, fileEditorManager); myProviders = providers; } @NotNull public FileEditorProvider[] getProviders() { return myProviders; } @Override public boolean isModified() { final FileEditor[] editors = getEditors(); for (FileEditor editor : editors) { if (editor.isModified()) { return true; } } return false; } @Override @NotNull public Pair<FileEditor, FileEditorProvider> getSelectedEditorWithProvider() { LOG.assertTrue(myEditors.length > 0, myEditors.length); if (myEditors.length == 1) { LOG.assertTrue(myTabbedPaneWrapper == null); return Pair.create(myEditors[0], myProviders[0]); } else { // we have to get myEditor from tabbed pane LOG.assertTrue(myTabbedPaneWrapper != null); int index = myTabbedPaneWrapper.getSelectedIndex(); if (index == -1) { index = 0; } LOG.assertTrue(index >= 0, index); LOG.assertTrue(index < myEditors.length, index); return Pair.create(myEditors[index], myProviders[index]); } } @NotNull public HistoryEntry currentStateAsHistoryEntry() { final FileEditor[] editors = getEditors(); final FileEditorState[] states = new FileEditorState[editors.length]; for (int j = 0; j < states.length; j++) { states[j] = editors[j].getState(FileEditorStateLevel.FULL); LOG.assertTrue(states[j] != null); } final int selectedProviderIndex = ArrayUtil.find(editors, getSelectedEditor()); LOG.assertTrue(selectedProviderIndex != -1); final FileEditorProvider[] providers = getProviders(); return new HistoryEntry(getFile(), providers, states, providers[selectedProviderIndex]); } void addEditor(FileEditor editor, FileEditorProvider provider) { addEditor(editor); myProviders = ArrayUtil.append(myProviders, provider); } }
Convert CSV editor editor provider to explicit action
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWithProviderComposite.java
Convert CSV editor editor provider to explicit action
<ide><path>latform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorWithProviderComposite.java <ide> return new HistoryEntry(getFile(), providers, states, providers[selectedProviderIndex]); <ide> } <ide> <del> void addEditor(FileEditor editor, FileEditorProvider provider) { <add> public void addEditor(FileEditor editor, FileEditorProvider provider) { <ide> addEditor(editor); <ide> myProviders = ArrayUtil.append(myProviders, provider); <ide> }
JavaScript
mit
aaf3c8dc5fc6cc10eb81a0e637421188ffae6f64
0
javiercejudo/arbitrary-precision
/*jshint node:true, mocha:true */ 'use strict'; require('should'); var adapter = require('floating-adapter'); var Decimal = require('../src/arbitrary-precision')(adapter); describe('linear operations with floating', function() { var ONE = new Decimal('1'); it('should have all linear arbitrary precision methods', function() { ONE.plus.should.have.type('function'); ONE.minus.should.have.type('function'); ONE.times.should.have.type('function'); ONE.div.should.have.type('function'); ONE.mod.should.have.type('function'); ONE.equals.should.have.type('function'); }); it('should extend linear arbitrary precision', function() { ONE.pow.should.have.type('function'); ONE.sqrt.should.have.type('function'); }); });
test/spec.js
/*jshint node:true, mocha:true */ 'use strict'; require('should'); var adapter = require('floating-adapter'); var Decimal = require('../src/arbitrary-precision')(adapter); describe('linear operations with floating', function() { var ONE = new Decimal('1'); it('should have all linear arbitrary precision methods', function() { ONE.plus.should.have.type('function'); ONE.minus.should.have.type('function'); ONE.times.should.have.type('function'); ONE.div.should.have.type('function'); ONE.equals.should.have.type('function'); }); it('should extend linear arbitrary precision', function() { ONE.pow.should.have.type('function'); ONE.sqrt.should.have.type('function'); }); });
test: presence of mod
test/spec.js
test: presence of mod
<ide><path>est/spec.js <ide> ONE.minus.should.have.type('function'); <ide> ONE.times.should.have.type('function'); <ide> ONE.div.should.have.type('function'); <add> ONE.mod.should.have.type('function'); <ide> ONE.equals.should.have.type('function'); <ide> }); <ide>
Java
mit
b36dd6d094f78fd635ec81c05631ae99c9f1fab4
0
dreamhead/moco,dreamhead/moco
package com.github.dreamhead.moco.resource; import com.github.dreamhead.moco.ConfigApplier; import com.github.dreamhead.moco.MocoConfig; import com.github.dreamhead.moco.Request; import com.github.dreamhead.moco.model.MessageContent; import com.google.common.base.Optional; public final class Resource implements Identifiable, ConfigApplier<Resource>, ResourceReader { private final Identifiable identifiable; private final ResourceConfigApplier configApplier; private final ResourceReader reader; public Resource(final Identifiable identifiable, final ResourceConfigApplier configApplier, final ResourceReader reader) { this.identifiable = identifiable; this.configApplier = configApplier; this.reader = reader; } @Override public Resource apply(final MocoConfig config) { return configApplier.apply(config, this); } @Override public String id() { return identifiable.id(); } @Override public MessageContent readFor(final Optional<? extends Request> request) { return reader.readFor(request); } public <T extends ResourceReader> T reader(final Class<T> clazz) { return clazz.cast(reader); } }
moco-core/src/main/java/com/github/dreamhead/moco/resource/Resource.java
package com.github.dreamhead.moco.resource; import com.github.dreamhead.moco.ConfigApplier; import com.github.dreamhead.moco.MocoConfig; import com.github.dreamhead.moco.Request; import com.github.dreamhead.moco.model.MessageContent; import com.google.common.base.Optional; public class Resource implements Identifiable, ConfigApplier<Resource>, ResourceReader { private final Identifiable identifiable; private final ResourceConfigApplier configApplier; private final ResourceReader reader; public Resource(final Identifiable identifiable, final ResourceConfigApplier configApplier, final ResourceReader reader) { this.identifiable = identifiable; this.configApplier = configApplier; this.reader = reader; } @Override public Resource apply(final MocoConfig config) { return configApplier.apply(config, this); } @Override public String id() { return identifiable.id(); } @Override public MessageContent readFor(final Optional<? extends Request> request) { return reader.readFor(request); } public <T extends ResourceReader> T reader(final Class<T> clazz) { return clazz.cast(reader); } }
added missing final to resource
moco-core/src/main/java/com/github/dreamhead/moco/resource/Resource.java
added missing final to resource
<ide><path>oco-core/src/main/java/com/github/dreamhead/moco/resource/Resource.java <ide> import com.github.dreamhead.moco.model.MessageContent; <ide> import com.google.common.base.Optional; <ide> <del>public class Resource implements Identifiable, ConfigApplier<Resource>, ResourceReader { <add>public final class Resource implements Identifiable, ConfigApplier<Resource>, ResourceReader { <ide> private final Identifiable identifiable; <ide> private final ResourceConfigApplier configApplier; <ide> private final ResourceReader reader;
Java
apache-2.0
8338d633bbc1fa445ee5aa7066569845dcd038aa
0
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* * $Log: IfsaMessagingSource.java,v $ * Revision 1.3 2010-02-10 09:36:24 L190409 * fixed getPhysicalName() * * Revision 1.2 2010/01/28 15:01:57 Gerrit van Brakel <[email protected]> * removed unused imports * * Revision 1.1 2010/01/28 14:49:06 Gerrit van Brakel <[email protected]> * renamed 'Connection' classes to 'MessageSource' * * Revision 1.3 2008/07/24 12:26:26 Gerrit van Brakel <[email protected]> * added support for authenticated JMS * * Revision 1.2 2007/10/16 08:39:30 Gerrit van Brakel <[email protected]> * moved IfsaException and IfsaMessageProtocolEnum back to main package * * Revision 1.1 2007/10/16 08:15:43 Gerrit van Brakel <[email protected]> * introduced switch class for jms and ejb * * Revision 1.12 2007/10/08 12:17:00 Gerrit van Brakel <[email protected]> * changed HashMap to Map where possible * * Revision 1.11 2007/09/05 15:46:37 Gerrit van Brakel <[email protected]> * moved XA determination capabilities to IfsaConnection * * Revision 1.10 2006/02/28 08:44:16 Gerrit van Brakel <[email protected]> * cleanUp on close configurable * * Revision 1.9 2005/11/02 09:40:52 Gerrit van Brakel <[email protected]> * made useSingleDynamicReplyQueue configurable from appConstants * * Revision 1.8 2005/11/02 09:08:06 Gerrit van Brakel <[email protected]> * ifsa-mode connection not for single dynamic reply queue * * Revision 1.7 2005/10/26 08:24:54 Gerrit van Brakel <[email protected]> * pulled dynamic reply code out of IfsaConnection to ConnectionBase * * Revision 1.6 2005/10/20 15:34:09 Gerrit van Brakel <[email protected]> * renamed JmsConnection into ConnectionBase * * Revision 1.5 2005/10/18 07:04:47 Gerrit van Brakel <[email protected]> * better handling of dynamic reply queues * * Revision 1.4 2005/08/31 16:29:50 Gerrit van Brakel <[email protected]> * corrected code for static reply queues * * Revision 1.3 2005/07/19 12:34:50 Gerrit van Brakel <[email protected]> * corrected version-string * * Revision 1.2 2005/07/19 12:33:56 Gerrit van Brakel <[email protected]> * implements IXAEnabled * polishing of serviceIds, to work around problems with ':' and '/' * * Revision 1.1 2005/05/03 15:58:49 Gerrit van Brakel <[email protected]> * rework of shared connection code * * Revision 1.2 2005/04/26 15:16:07 Gerrit van Brakel <[email protected]> * removed most bugs * * Revision 1.1 2005/04/26 09:36:16 Gerrit van Brakel <[email protected]> * introduction of IfsaApplicationConnection */ package nl.nn.adapterframework.extensions.ifsa.jms; import java.util.Map; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.naming.NamingException; import nl.nn.adapterframework.extensions.ifsa.IfsaException; import nl.nn.adapterframework.jms.MessagingSource; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.ClassUtils; import com.ing.ifsa.IFSAContext; import com.ing.ifsa.IFSAQueue; import com.ing.ifsa.IFSAQueueConnectionFactory; /** * {@link nl.nn.adapterframework.jms.MessagingSource} for IFSA connections. * * IFSA related IBIS objects can obtain an connection from this class. The physical connection is shared * between all IBIS objects that have the same ApplicationID. * * @author Gerrit van Brakel * @version Id */ public class IfsaMessagingSource extends MessagingSource { private final static String CLEANUP_ON_CLOSE_KEY="ifsa.cleanUpOnClose"; private static Boolean cleanUpOnClose=null; private boolean preJms22Api; private boolean xaEnabled; public IfsaMessagingSource(String applicationId, IFSAContext context, IFSAQueueConnectionFactory connectionFactory, Map messagingSourceMap, boolean preJms22Api, boolean xaEnabled) { super(applicationId,context,connectionFactory,messagingSourceMap,null); this.preJms22Api=preJms22Api; this.xaEnabled=xaEnabled; log.debug("created new IfsaMessagingSource for ["+applicationId+"] context ["+context+"] connectionfactory ["+connectionFactory+"]"); } public boolean hasDynamicReplyQueue() throws IfsaException { try { if (preJms22Api) { return !((IFSAQueueConnectionFactory) getConnectionFactory()).IsClientTransactional(); } else { return ((IFSAContext) getContext()).hasDynamicReplyQueue(); } } catch (NamingException e) { throw new IfsaException("could not find IfsaContext",e); } } public boolean canUseIfsaModeSessions() throws IfsaException { return hasDynamicReplyQueue() && !useSingleDynamicReplyQueue(); } /** * Retrieves the reply queue for a <b>client</b> connection. If the * client is transactional the replyqueue is retrieved from IFSA, * otherwise a temporary (dynamic) queue is created. */ public Queue getClientReplyQueue(QueueSession session) throws IfsaException { Queue replyQueue = null; try { /* * if we don't know if we're using a dynamic reply queue, we can * check this using the function IsClientTransactional * Yes -> we're using a static reply queue * No -> dynamic reply queue */ if (hasDynamicReplyQueue()) { // Temporary Dynamic replyQueue = getDynamicReplyQueue(session); log.debug("got dynamic reply queue [" +replyQueue.getQueueName()+"]"); } else { // Static replyQueue = (Queue) ((IFSAContext)getContext()).lookupReply(getId()); log.debug("got static reply queue [" +replyQueue.getQueueName()+"]"); } return replyQueue; } catch (Exception e) { throw new IfsaException(e); } } protected void releaseClientReplyQueue(Queue replyQueue) throws IfsaException { if (hasDynamicReplyQueue()) { // Temporary Dynamic releaseDynamicReplyQueue(replyQueue); } } /** * Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/> * For serverside getQueueReceiver() the creating of the QueueReceiver is done * without the <code>selector</code> information, as this is not allowed * by IFSA.<br/> * For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code> */ public QueueReceiver getReplyReceiver(QueueSession session, Message sentMessage) throws IfsaException { QueueReceiver queueReceiver; String correlationId; Queue replyQueue; try { correlationId = sentMessage.getJMSMessageID(); // IFSA uses the messageId as correlationId replyQueue=(Queue)sentMessage.getJMSReplyTo(); } catch (JMSException e) { throw new IfsaException(e); } try { if (hasDynamicReplyQueue() && !useSingleDynamicReplyQueue()) { queueReceiver = session.createReceiver(replyQueue); log.debug("created receiver on individual dynamic reply queue" ); } else { String selector="JMSCorrelationID='" + correlationId + "'"; queueReceiver = session.createReceiver(replyQueue, selector); log.debug("created receiver on static or shared-dynamic reply queue - selector ["+selector+"]"); } } catch (JMSException e) { throw new IfsaException(e); } return queueReceiver; } public void closeReplyReceiver(QueueReceiver receiver) throws IfsaException { try { if (receiver!=null) { Queue replyQueue = receiver.getQueue(); receiver.close(); releaseClientReplyQueue(replyQueue); } } catch (JMSException e) { throw new IfsaException(e); } } public IFSAQueue lookupService(String serviceId) throws IfsaException { try { return (IFSAQueue) ((IFSAContext)getContext()).lookupService(serviceId); } catch (NamingException e) { throw new IfsaException("cannot lookup queue for service ["+serviceId+"]",e); } } public IFSAQueue lookupProviderInput() throws IfsaException { try { return (IFSAQueue) ((IFSAContext)getContext()).lookupProviderInput(); } catch (NamingException e) { throw new IfsaException("cannot lookup provider queue",e); } } protected String replaceLast(String string, char from, char to) { int lastTo=string.lastIndexOf(to); int lastFrom=string.lastIndexOf(from); if (lastFrom>0 && lastTo<lastFrom) { String result = string.substring(0,lastFrom)+to+string.substring(lastFrom+1); log.info("replacing for Ifsa-compatibility ["+string+"] by ["+result+"]"); return result; } return string; } public String polishServiceId(String serviceId) { if (preJms22Api) { return replaceLast(serviceId, '/',':'); } else { return replaceLast(serviceId, ':','/'); } } public synchronized boolean cleanUpOnClose() { if (cleanUpOnClose==null) { boolean cleanup=AppConstants.getInstance().getBoolean(CLEANUP_ON_CLOSE_KEY, true); cleanUpOnClose = new Boolean(cleanup); } return cleanUpOnClose.booleanValue(); } public String getPhysicalName() { String result=""; try { QueueConnectionFactory qcf = (QueueConnectionFactory)ClassUtils.getDeclaredFieldValue(getConnectionFactory(),"qcf"); result+=ClassUtils.reflectionToString(qcf, "factory"); } catch (Exception e) { result+=ClassUtils.nameOf(e)+": "+e.getMessage(); } return result; } public boolean xaCapabilityCanBeDetermined() { return !preJms22Api; } public boolean isXaEnabled() { return xaEnabled; } public boolean isXaEnabledForSure() { return xaCapabilityCanBeDetermined() && isXaEnabled(); } public boolean isNotXaEnabledForSure() { return xaCapabilityCanBeDetermined() && !isXaEnabled(); } }
JavaSource/nl/nn/adapterframework/extensions/ifsa/jms/IfsaMessagingSource.java
/* * $Log: IfsaMessagingSource.java,v $ * Revision 1.2 2010-01-28 15:01:57 L190409 * removed unused imports * * Revision 1.1 2010/01/28 14:49:06 Gerrit van Brakel <[email protected]> * renamed 'Connection' classes to 'MessageSource' * * Revision 1.3 2008/07/24 12:26:26 Gerrit van Brakel <[email protected]> * added support for authenticated JMS * * Revision 1.2 2007/10/16 08:39:30 Gerrit van Brakel <[email protected]> * moved IfsaException and IfsaMessageProtocolEnum back to main package * * Revision 1.1 2007/10/16 08:15:43 Gerrit van Brakel <[email protected]> * introduced switch class for jms and ejb * * Revision 1.12 2007/10/08 12:17:00 Gerrit van Brakel <[email protected]> * changed HashMap to Map where possible * * Revision 1.11 2007/09/05 15:46:37 Gerrit van Brakel <[email protected]> * moved XA determination capabilities to IfsaConnection * * Revision 1.10 2006/02/28 08:44:16 Gerrit van Brakel <[email protected]> * cleanUp on close configurable * * Revision 1.9 2005/11/02 09:40:52 Gerrit van Brakel <[email protected]> * made useSingleDynamicReplyQueue configurable from appConstants * * Revision 1.8 2005/11/02 09:08:06 Gerrit van Brakel <[email protected]> * ifsa-mode connection not for single dynamic reply queue * * Revision 1.7 2005/10/26 08:24:54 Gerrit van Brakel <[email protected]> * pulled dynamic reply code out of IfsaConnection to ConnectionBase * * Revision 1.6 2005/10/20 15:34:09 Gerrit van Brakel <[email protected]> * renamed JmsConnection into ConnectionBase * * Revision 1.5 2005/10/18 07:04:47 Gerrit van Brakel <[email protected]> * better handling of dynamic reply queues * * Revision 1.4 2005/08/31 16:29:50 Gerrit van Brakel <[email protected]> * corrected code for static reply queues * * Revision 1.3 2005/07/19 12:34:50 Gerrit van Brakel <[email protected]> * corrected version-string * * Revision 1.2 2005/07/19 12:33:56 Gerrit van Brakel <[email protected]> * implements IXAEnabled * polishing of serviceIds, to work around problems with ':' and '/' * * Revision 1.1 2005/05/03 15:58:49 Gerrit van Brakel <[email protected]> * rework of shared connection code * * Revision 1.2 2005/04/26 15:16:07 Gerrit van Brakel <[email protected]> * removed most bugs * * Revision 1.1 2005/04/26 09:36:16 Gerrit van Brakel <[email protected]> * introduction of IfsaApplicationConnection */ package nl.nn.adapterframework.extensions.ifsa.jms; import java.util.Map; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.naming.NamingException; import nl.nn.adapterframework.extensions.ifsa.IfsaException; import nl.nn.adapterframework.jms.MessagingSource; import nl.nn.adapterframework.util.AppConstants; import com.ing.ifsa.IFSAContext; import com.ing.ifsa.IFSAQueue; import com.ing.ifsa.IFSAQueueConnectionFactory; /** * {@link nl.nn.adapterframework.jms.MessagingSource} for IFSA connections. * * IFSA related IBIS objects can obtain an connection from this class. The physical connection is shared * between all IBIS objects that have the same ApplicationID. * * @author Gerrit van Brakel * @version Id */ public class IfsaMessagingSource extends MessagingSource { private final static String CLEANUP_ON_CLOSE_KEY="ifsa.cleanUpOnClose"; private static Boolean cleanUpOnClose=null; private boolean preJms22Api; private boolean xaEnabled; public IfsaMessagingSource(String applicationId, IFSAContext context, IFSAQueueConnectionFactory connectionFactory, Map messagingSourceMap, boolean preJms22Api, boolean xaEnabled) { super(applicationId,context,connectionFactory,messagingSourceMap,null); this.preJms22Api=preJms22Api; this.xaEnabled=xaEnabled; log.debug("created new IfsaMessagingSource for ["+applicationId+"] context ["+context+"] connectionfactory ["+connectionFactory+"]"); } public boolean hasDynamicReplyQueue() throws IfsaException { try { if (preJms22Api) { return !((IFSAQueueConnectionFactory) getConnectionFactory()).IsClientTransactional(); } else { return ((IFSAContext) getContext()).hasDynamicReplyQueue(); } } catch (NamingException e) { throw new IfsaException("could not find IfsaContext",e); } } public boolean canUseIfsaModeSessions() throws IfsaException { return hasDynamicReplyQueue() && !useSingleDynamicReplyQueue(); } /** * Retrieves the reply queue for a <b>client</b> connection. If the * client is transactional the replyqueue is retrieved from IFSA, * otherwise a temporary (dynamic) queue is created. */ public Queue getClientReplyQueue(QueueSession session) throws IfsaException { Queue replyQueue = null; try { /* * if we don't know if we're using a dynamic reply queue, we can * check this using the function IsClientTransactional * Yes -> we're using a static reply queue * No -> dynamic reply queue */ if (hasDynamicReplyQueue()) { // Temporary Dynamic replyQueue = getDynamicReplyQueue(session); log.debug("got dynamic reply queue [" +replyQueue.getQueueName()+"]"); } else { // Static replyQueue = (Queue) ((IFSAContext)getContext()).lookupReply(getId()); log.debug("got static reply queue [" +replyQueue.getQueueName()+"]"); } return replyQueue; } catch (Exception e) { throw new IfsaException(e); } } protected void releaseClientReplyQueue(Queue replyQueue) throws IfsaException { if (hasDynamicReplyQueue()) { // Temporary Dynamic releaseDynamicReplyQueue(replyQueue); } } /** * Gets the queueReceiver, by utilizing the <code>getInputQueue()</code> method.<br/> * For serverside getQueueReceiver() the creating of the QueueReceiver is done * without the <code>selector</code> information, as this is not allowed * by IFSA.<br/> * For a clientconnection, the receiver is done with the <code>getClientReplyQueue</code> */ public QueueReceiver getReplyReceiver(QueueSession session, Message sentMessage) throws IfsaException { QueueReceiver queueReceiver; String correlationId; Queue replyQueue; try { correlationId = sentMessage.getJMSMessageID(); // IFSA uses the messageId as correlationId replyQueue=(Queue)sentMessage.getJMSReplyTo(); } catch (JMSException e) { throw new IfsaException(e); } try { if (hasDynamicReplyQueue() && !useSingleDynamicReplyQueue()) { queueReceiver = session.createReceiver(replyQueue); log.debug("created receiver on individual dynamic reply queue" ); } else { String selector="JMSCorrelationID='" + correlationId + "'"; queueReceiver = session.createReceiver(replyQueue, selector); log.debug("created receiver on static or shared-dynamic reply queue - selector ["+selector+"]"); } } catch (JMSException e) { throw new IfsaException(e); } return queueReceiver; } public void closeReplyReceiver(QueueReceiver receiver) throws IfsaException { try { if (receiver!=null) { Queue replyQueue = receiver.getQueue(); receiver.close(); releaseClientReplyQueue(replyQueue); } } catch (JMSException e) { throw new IfsaException(e); } } public IFSAQueue lookupService(String serviceId) throws IfsaException { try { return (IFSAQueue) ((IFSAContext)getContext()).lookupService(serviceId); } catch (NamingException e) { throw new IfsaException("cannot lookup queue for service ["+serviceId+"]",e); } } public IFSAQueue lookupProviderInput() throws IfsaException { try { return (IFSAQueue) ((IFSAContext)getContext()).lookupProviderInput(); } catch (NamingException e) { throw new IfsaException("cannot lookup provider queue",e); } } protected String replaceLast(String string, char from, char to) { int lastTo=string.lastIndexOf(to); int lastFrom=string.lastIndexOf(from); if (lastFrom>0 && lastTo<lastFrom) { String result = string.substring(0,lastFrom)+to+string.substring(lastFrom+1); log.info("replacing for Ifsa-compatibility ["+string+"] by ["+result+"]"); return result; } return string; } public String polishServiceId(String serviceId) { if (preJms22Api) { return replaceLast(serviceId, '/',':'); } else { return replaceLast(serviceId, ':','/'); } } public synchronized boolean cleanUpOnClose() { if (cleanUpOnClose==null) { boolean cleanup=AppConstants.getInstance().getBoolean(CLEANUP_ON_CLOSE_KEY, true); cleanUpOnClose = new Boolean(cleanup); } return cleanUpOnClose.booleanValue(); } public String getPhysicalName() { String result=""; // try { // result+=ToStringBuilder.reflectionToString(getClass().getDeclaredField("qcf").get(this)); // } catch (Exception e) { // result+=ClassUtils.nameOf(e)+": "+e.getMessage(); // } return result; } public boolean xaCapabilityCanBeDetermined() { return !preJms22Api; } public boolean isXaEnabled() { return xaEnabled; } public boolean isXaEnabledForSure() { return xaCapabilityCanBeDetermined() && isXaEnabled(); } public boolean isNotXaEnabledForSure() { return xaCapabilityCanBeDetermined() && !isXaEnabled(); } }
fixed getPhysicalName()
JavaSource/nl/nn/adapterframework/extensions/ifsa/jms/IfsaMessagingSource.java
fixed getPhysicalName()
<ide><path>avaSource/nl/nn/adapterframework/extensions/ifsa/jms/IfsaMessagingSource.java <ide> /* <ide> * $Log: IfsaMessagingSource.java,v $ <del> * Revision 1.2 2010-01-28 15:01:57 L190409 <add> * Revision 1.3 2010-02-10 09:36:24 L190409 <add> * fixed getPhysicalName() <add> * <add> * Revision 1.2 2010/01/28 15:01:57 Gerrit van Brakel <[email protected]> <ide> * removed unused imports <ide> * <ide> * Revision 1.1 2010/01/28 14:49:06 Gerrit van Brakel <[email protected]> <ide> import javax.jms.JMSException; <ide> import javax.jms.Message; <ide> import javax.jms.Queue; <add>import javax.jms.QueueConnectionFactory; <ide> import javax.jms.QueueReceiver; <ide> import javax.jms.QueueSession; <ide> import javax.naming.NamingException; <ide> import nl.nn.adapterframework.extensions.ifsa.IfsaException; <ide> import nl.nn.adapterframework.jms.MessagingSource; <ide> import nl.nn.adapterframework.util.AppConstants; <add>import nl.nn.adapterframework.util.ClassUtils; <ide> <ide> import com.ing.ifsa.IFSAContext; <ide> import com.ing.ifsa.IFSAQueue; <ide> <ide> public String getPhysicalName() { <ide> String result=""; <del>// try { <del>// result+=ToStringBuilder.reflectionToString(getClass().getDeclaredField("qcf").get(this)); <del>// } catch (Exception e) { <del>// result+=ClassUtils.nameOf(e)+": "+e.getMessage(); <del>// } <add> try { <add> QueueConnectionFactory qcf = (QueueConnectionFactory)ClassUtils.getDeclaredFieldValue(getConnectionFactory(),"qcf"); <add> result+=ClassUtils.reflectionToString(qcf, "factory"); <add> } catch (Exception e) { <add> result+=ClassUtils.nameOf(e)+": "+e.getMessage(); <add> } <ide> return result; <ide> } <ide>
Java
apache-2.0
743001023bb5eae9b9d86edc2d4af2fad442924c
0
amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak
/* * 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.jackrabbit.oak.plugins.index.lucene; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.management.openmbean.TabularData; import com.google.common.base.StandardSystemProperty; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ForwardingListeningExecutorService; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.oak.commons.IOUtils; import org.apache.jackrabbit.oak.plugins.index.IndexConstants; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FilterDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; import static org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent.INITIAL_CONTENT; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; public class IndexCopierTest { private Random rnd = new Random(); private int maxFileSize = 7896; private NodeState root = INITIAL_CONTENT; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target")); private NodeBuilder builder = root.builder(); private String indexPath = "/oak:index/test"; @Before public void setUp(){ builder.setProperty(IndexConstants.INDEX_PATH, indexPath); LuceneIndexEditorContext.configureUniqueId(builder); } @Test public void basicTest() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , "t1"); byte[] t2 = writeFile(remote , "t2"); assertEquals(2, wrapped.listAll().length); assertTrue(wrapped.fileExists("t1")); assertTrue(wrapped.fileExists("t2")); assertEquals(t1.length, wrapped.fileLength("t1")); assertEquals(t2.length, wrapped.fileLength("t2")); readAndAssert(wrapped, "t1", t1); //t1 should now be added to testDir assertTrue(baseDir.fileExists("t1")); } @Test public void basicTestWithPrefetch() throws Exception{ final List<String> syncedFiles = Lists.newArrayList(); Directory baseDir = new RAMDirectory(){ @Override public void sync(Collection<String> names) throws IOException { syncedFiles.addAll(names); super.sync(names); } }; IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir(), true); Directory remote = new RAMDirectory(); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote , "t2"); Directory wrapped = c1.wrapForRead("/foo", defn, remote); assertEquals(2, wrapped.listAll().length); assertThat(syncedFiles, containsInAnyOrder("t1", "t2")); assertTrue(wrapped.fileExists("t1")); assertTrue(wrapped.fileExists("t2")); assertTrue(baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); assertEquals(t1.length, wrapped.fileLength("t1")); assertEquals(t2.length, wrapped.fileLength("t2")); readAndAssert(wrapped, "t1", t1); } @Test public void nonExistentFile() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); CollectingExecutor executor = new CollectingExecutor(); IndexCopier c1 = new RAMIndexCopier(baseDir, executor, getWorkDir(), true); Directory remote = new RAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); try { wrapped.openInput("foo.txt", IOContext.DEFAULT); fail(); } catch(FileNotFoundException ignore){ } assertEquals(0, executor.commands.size()); } @Test public void basicTestWithFS() throws Exception{ IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new IndexCopier(sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote , "t2"); assertEquals(2, wrapped.listAll().length); assertTrue(wrapped.fileExists("t1")); assertTrue(wrapped.fileExists("t2")); assertEquals(t1.length, wrapped.fileLength("t1")); assertEquals(t2.length, wrapped.fileLength("t2")); readAndAssert(wrapped, "t1", t1); //t1 should now be added to testDir File indexDir = c1.getIndexDir(defn, "/foo"); assertTrue(new File(indexDir, "t1").exists()); TabularData td = c1.getIndexPathMapping(); assertEquals(1, td.size()); } @Test public void deleteOldPostReindex() throws Exception{ IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new IndexCopier(sameThreadExecutor(), getWorkDir()); Directory remote = new CloseSafeDir(); Directory w1 = c1.wrapForRead(indexPath, defn, remote); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote , "t2"); readAndAssert(w1, "t1", t1); readAndAssert(w1, "t2", t2); //t1 should now be added to testDir File indexDir = c1.getIndexDir(defn, indexPath); assertTrue(new File(indexDir, "t1").exists()); doReindex(builder); defn = new IndexDefinition(root, builder.getNodeState()); //Close old version w1.close(); //Get a new one with updated reindexCount Directory w2 = c1.wrapForRead(indexPath, defn, remote); readAndAssert(w2, "t1", t1); w2.close(); assertFalse("Old index directory should have been removed", indexDir.exists()); //Assert that new index file do exist and not get removed File indexDir2 = c1.getIndexDir(defn, indexPath); assertTrue(new File(indexDir2, "t1").exists()); //Check if parent directory is also removed i.e. //index count should be 1 now assertEquals(1, c1.getIndexRootDirectory().getLocalIndexes(indexPath).size()); } @Test public void concurrentRead() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); CollectingExecutor executor = new CollectingExecutor(); IndexCopier c1 = new RAMIndexCopier(baseDir, executor, getWorkDir()); TestRAMDirectory remote = new TestRAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , "t1"); //1. Trigger a read which should go to remote readAndAssert(wrapped, "t1", t1); assertEquals(1, c1.getScheduledForCopyCount()); assertEquals(1, remote.openedFiles.size()); assertEquals(1, executor.commands.size()); //2. Trigger another read and this should also be //served from remote readAndAssert(wrapped, "t1", t1); assertEquals(1, c1.getScheduledForCopyCount()); assertEquals(2, remote.openedFiles.size()); //Second read should not add a new copy task assertEquals(1, executor.commands.size()); //3. Perform copy executor.executeAll(); remote.reset(); //4. Now read again after copy is done readAndAssert(wrapped, "t1", t1); // Now read should be served from local and not from remote assertEquals(0, remote.openedFiles.size()); assertEquals(0, c1.getScheduledForCopyCount()); } @Test public void copyInProgressStats() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); final List<ListenableFuture<?>> submittedTasks = Lists.newArrayList(); ExecutorService executor = new ForwardingListeningExecutorService() { @Override protected ListeningExecutorService delegate() { return MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); } @Override public void execute(Runnable command) { submittedTasks.add(super.submit(command)); } }; IndexCopier c1 = new RAMIndexCopier(baseDir, executor, getWorkDir()); final CountDownLatch copyProceed = new CountDownLatch(1); final CountDownLatch copyRequestArrived = new CountDownLatch(1); TestRAMDirectory remote = new TestRAMDirectory(){ @Override public void copy(Directory to, String src, String dest, IOContext context) throws IOException { copyRequestArrived.countDown(); try { copyProceed.await(); } catch (InterruptedException e) { } super.copy(to, src, dest, context); } }; Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , "t1"); //1. Trigger a read which should go to remote readAndAssert(wrapped, "t1", t1); copyRequestArrived.await(); assertEquals(1, c1.getCopyInProgressCount()); assertEquals(1, remote.openedFiles.size()); //2. Trigger another read and this should also be //served from remote readAndAssert(wrapped, "t1", t1); assertEquals(1, c1.getCopyInProgressCount()); assertEquals(IOUtils.humanReadableByteCount(t1.length), c1.getCopyInProgressSize()); assertEquals(1, c1.getCopyInProgressDetails().length); System.out.println(Arrays.toString(c1.getCopyInProgressDetails())); assertEquals(2, remote.openedFiles.size()); //3. Perform copy copyProceed.countDown(); Futures.allAsList(submittedTasks).get(); remote.reset(); //4. Now read again after copy is done readAndAssert(wrapped, "t1", t1); // Now read should be served from local and not from remote assertEquals(0, remote.openedFiles.size()); assertEquals(0, c1.getCopyInProgressCount()); executor.shutdown(); } /** * Test for the case where local directory is opened already contains * the index files and in such a case file should not be read from remote */ @Test public void reuseLocalDir() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); TestRAMDirectory remote = new TestRAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote, "t1"); //1. Read for the first time should be served from remote readAndAssert(wrapped, "t1", t1); assertEquals(1, remote.openedFiles.size()); //2. Reuse the testDir and read again Directory wrapped2 = c1.wrapForRead("/foo", defn, remote); remote.reset(); //3. Now read should be served from local readAndAssert(wrapped2, "t1", t1); assertEquals(0, remote.openedFiles.size()); //Now check if local file gets corrupted then read from remote Directory wrapped3 = c1.wrapForRead("/foo", defn, remote); remote.reset(); //4. Corrupt the local copy writeFile(baseDir, "t1"); //Now read would be done from remote readAndAssert(wrapped3, "t1", t1); assertEquals(1, remote.openedFiles.size()); } @Test public void deleteCorruptedFile() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); RAMIndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(){ @Override public IndexInput openInput(String name, IOContext context) throws IOException { throw new IllegalStateException("boom"); } }; String fileName = "failed.txt"; Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , fileName); try { readAndAssert(wrapped, fileName, t1); fail("Read of file should have failed"); } catch (IllegalStateException ignore){ } assertFalse(c1.baseDir.fileExists(fileName)); } @Test public void deletesOnClose() throws Exception{ //Use a close safe dir. In actual case the FSDir would //be opened on same file system hence it can retain memory //but RAMDirectory does not retain memory hence we simulate //that by not closing the RAMDir and reuse it Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory r1 = new RAMDirectory(); byte[] t1 = writeFile(r1, "t1"); byte[] t2 = writeFile(r1 , "t2"); Directory w1 = c1.wrapForRead("/foo", defn, r1); readAndAssert(w1, "t1", t1); readAndAssert(w1, "t2", t2); // t1 and t2 should now be present in local (base dir which back local) assertTrue(baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); Directory r2 = new RAMDirectory(); copy(r1, r2); r2.deleteFile("t1"); Directory w2 = c1.wrapForRead("/foo", defn, r2); //Close would trigger removal of file which are not present in remote w2.close(); assertFalse("t1 should have been deleted", baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); } @Test public void failureInDelete() throws Exception{ final Set<String> testFiles = new HashSet<String>(); Directory baseDir = new CloseSafeDir() { @Override public void deleteFile(String name) throws IOException { if (testFiles.contains(name)){ throw new IOException("Not allowed to delete " + name); } super.deleteFile(name); } }; IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory r1 = new RAMDirectory(); byte[] t1 = writeFile(r1, "t1"); byte[] t2 = writeFile(r1 , "t2"); Directory w1 = c1.wrapForRead("/foo", defn, r1); readAndAssert(w1, "t1", t1); readAndAssert(w1, "t2", t2); // t1 and t2 should now be present in local (base dir which back local) assertTrue(baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); Directory r2 = new CloseSafeDir(); copy(r1, r2); r2.deleteFile("t1"); Directory w2 = c1.wrapForRead("/foo", defn, r2); //Close would trigger removal of file which are not present in remote testFiles.add("t1"); w2.close(); assertEquals(1, c1.getFailedToDeleteFiles().size()); IndexCopier.LocalIndexFile testFile = c1.getFailedToDeleteFiles().values().iterator().next(); assertEquals(1, testFile.getDeleteAttemptCount()); assertEquals(IOUtils.humanReadableByteCount(t1.length), c1.getGarbageSize()); assertEquals(1, c1.getGarbageDetails().length); Directory w3 = c1.wrapForRead("/foo", defn, r2); w3.close(); assertEquals(2, testFile.getDeleteAttemptCount()); //Now let the file to be deleted testFiles.clear(); Directory w4 = c1.wrapForRead("/foo", defn, r2); w4.close(); //No pending deletes left assertEquals(0, c1.getFailedToDeleteFiles().size()); } @Test public void deletedOnlyFilesForOlderVersion() throws Exception{ Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); //1. Open a local and read t1 from remote Directory remote1 = new RAMDirectory(); byte[] t1 = writeFile(remote1, "t1"); Directory local1 = copier.wrapForRead("/foo", defn, remote1); readAndAssert(local1, "t1", t1); //While local1 is open , open another local2 and read t2 Directory remote2 = new RAMDirectory(); byte[] t2 = writeFile(remote2, "t2"); Directory local2 = copier.wrapForRead("/foo", defn, remote2); readAndAssert(local2, "t2", t2); //Close local1 local1.close(); //t2 should still be readable readAndAssert(local2, "t2", t2); } @Test public void wrapForWriteWithoutIndexPath() throws Exception{ Directory remote = new CloseSafeDir(); IndexCopier copier = new IndexCopier(sameThreadExecutor(), getWorkDir()); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); Directory dir = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(dir, "t1"); dir.close(); readAndAssert(remote, "t1", t1); //Work dir must be empty post close assertArrayEquals(FileUtils.EMPTY_FILE_ARRAY, copier.getIndexWorkDir().listFiles()); } @Test public void wrapForWriteWithIndexPath() throws Exception{ Directory remote = new CloseSafeDir(); IndexCopier copier = new IndexCopier(sameThreadExecutor(), getWorkDir()); builder.setProperty(IndexConstants.INDEX_PATH, "foo"); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); Directory dir = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(dir, "t1"); dir.close(); readAndAssert(remote, "t1", t1); //Work dir must be empty post close File indexDir = copier.getIndexDir(defn, "foo"); List<File> files = new ArrayList<File>(FileUtils.listFiles(indexDir, null, true)); Set<String> fileNames = Sets.newHashSet(); for (File f : files){ fileNames.add(f.getName()); } assertThat(fileNames, contains("t1")); } @Test public void copyOnWriteBasics() throws Exception{ Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(); byte[] t1 = writeFile(remote, "t1"); //State of remote directory should set before wrapping as later //additions would not be picked up given COW assume remote directory //to be read only Directory local = copier.wrapForWrite(defn, remote, false); assertEquals(newHashSet("t1"), newHashSet(local.listAll())); assertEquals(t1.length, local.fileLength("t1")); byte[] t2 = writeFile(local, "t2"); assertEquals(newHashSet("t1", "t2"), newHashSet(local.listAll())); assertEquals(t2.length, local.fileLength("t2")); assertTrue(local.fileExists("t1")); assertTrue(local.fileExists("t2")); assertTrue("t2 should be copied to remote", remote.fileExists("t2")); readAndAssert(local, "t1", t1); readAndAssert(local, "t2", t2); local.deleteFile("t1"); assertEquals(newHashSet("t2"), newHashSet(local.listAll())); local.deleteFile("t2"); assertEquals(newHashSet(), newHashSet(local.listAll())); try { local.fileLength("nonExistentFile"); fail(); } catch (FileNotFoundException ignore) { } try { local.openInput("nonExistentFile", IOContext.DEFAULT); fail(); } catch (FileNotFoundException ignore) { } local.close(); assertFalse(baseDir.fileExists("t2")); } /** * Checks for the case where if the file exist local before writer starts * then those files do not get deleted even if deleted by writer via * indexing process from 'baseDir' as they might be in use by existing open * indexes */ @Test public void cowExistingLocalFileNotDeleted() throws Exception{ Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new CloseSafeDir(); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote, "t2"); Directory local = copier.wrapForWrite(defn, remote, false); assertEquals(newHashSet("t1", "t2"), newHashSet(local.listAll())); byte[] t3 = writeFile(local, "t3"); //Now pull in the file t1 via CopyOnRead in baseDir Directory localForRead = copier.wrapForRead("/foo", defn, remote); readAndAssert(localForRead, "t1", t1); //File which was copied from remote should not be deleted from baseDir //upon delete from local assertTrue(baseDir.fileExists("t1")); local.deleteFile("t1"); assertFalse("t1 should be deleted from remote", remote.fileExists("t1")); assertFalse("t1 should be deleted from 'local' view also", local.fileExists("t1")); assertTrue("t1 should not be deleted from baseDir", baseDir.fileExists("t1")); //File which was created only via local SHOULD get removed from //baseDir only upon close assertTrue(baseDir.fileExists("t3")); local.deleteFile("t3"); assertFalse("t1 should be deleted from remote", local.fileExists("t3")); assertTrue("t1 should NOT be deleted from remote", baseDir.fileExists("t3")); local.close(); assertFalse("t3 should also be deleted from local", baseDir.fileExists("t3")); } @Test public void cowReadDoneFromLocalIfFileExist() throws Exception{ final Set<String> readLocal = newHashSet(); Directory baseDir = new CloseSafeDir(){ @Override public IndexInput openInput(String name, IOContext context) throws IOException { readLocal.add(name); return super.openInput(name, context); } }; IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); final Set<String> readRemotes = newHashSet(); Directory remote = new RAMDirectory() { @Override public IndexInput openInput(String name, IOContext context) throws IOException { readRemotes.add(name); return super.openInput(name, context); } }; byte[] t1 = writeFile(remote, "t1"); Directory local = copier.wrapForWrite(defn, remote, false); //Read should be served from remote readRemotes.clear();readLocal.clear(); readAndAssert(local, "t1", t1); assertEquals(newHashSet("t1"), readRemotes); assertEquals(newHashSet(), readLocal); //Now pull in the file t1 via CopyOnRead in baseDir Directory localForRead = copier.wrapForRead("/foo", defn, remote); readAndAssert(localForRead, "t1", t1); //Read should be served from local readRemotes.clear();readLocal.clear(); readAndAssert(local, "t1", t1); assertEquals(newHashSet(), readRemotes); assertEquals(newHashSet("t1"), readLocal); local.close(); } @Test public void cowCopyDoneOnClose() throws Exception{ final CollectingExecutor executor = new CollectingExecutor(); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executor, getWorkDir()); Directory remote = new CloseSafeDir(); final Directory local = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(local, "t1"); assertTrue(local.fileExists("t1")); assertFalse("t1 should NOT be copied to remote", remote.fileExists("t1")); //Execute all job executor.executeAll(); assertTrue("t1 should now be copied to remote", remote.fileExists("t1")); byte[] t2 = writeFile(local, "t2"); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); final ExecutorService executorService = Executors.newFixedThreadPool(4); final CountDownLatch copyLatch = new CountDownLatch(1); Future<?> copyTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { copyLatch.await(); //the executor to a proper one as it might happen that //STOP task is added post CountingExecutor has executed. Then there //would be none to process the STOP. Having a proper executor would //handle that case executor.setForwardingExecutor(executorService); executor.executeAll(); return null; } }); final CountDownLatch closeLatch = new CountDownLatch(1); Future<?> closeTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { closeLatch.await(); local.close(); return null; } }); closeLatch.countDown(); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); //Let copy to proceed copyLatch.countDown(); //Now wait for close to finish closeTasks.get(); assertTrue("t2 should now be copied to remote", remote.fileExists("t2")); executorService.shutdown(); } @Test public void cowCopyDoneOnCloseExceptionHandling() throws Exception{ final CollectingExecutor executor = new CollectingExecutor(); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executor, getWorkDir()); Directory remote = new CloseSafeDir(); final Directory local = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(local, "t1"); assertTrue(local.fileExists("t1")); assertFalse("t1 should NOT be copied to remote", remote.fileExists("t1")); //Execute all job executor.executeAll(); assertTrue("t1 should now be copied to remote", remote.fileExists("t1")); byte[] t2 = writeFile(local, "t2"); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); ExecutorService executorService = Executors.newFixedThreadPool(2); final CountDownLatch copyLatch = new CountDownLatch(1); Future<?> copyTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { copyLatch.await(); executor.executeAll(); executor.enableImmediateExecution(); return null; } }); final CountDownLatch closeLatch = new CountDownLatch(1); Future<?> closeTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { closeLatch.await(); local.close(); return null; } }); closeLatch.countDown(); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); //Let copy to proceed copyLatch.countDown(); //Now wait for close to finish closeTasks.get(); assertTrue("t2 should now be copied to remote", remote.fileExists("t2")); executorService.shutdown(); } @Test public void cowFailureInCopy() throws Exception{ ExecutorService executorService = Executors.newFixedThreadPool(2); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executorService, getWorkDir()); final Set<String> toFail = Sets.newHashSet(); Directory remote = new CloseSafeDir() { @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { if (toFail.contains(name)){ throw new RuntimeException("Failing copy for "+name); } return super.createOutput(name, context); } }; final Directory local = copier.wrapForWrite(defn, remote, false); toFail.add("t2"); byte[] t1 = writeFile(local, "t1"); byte[] t2 = writeFile(local, "t2"); try { local.close(); fail(); } catch (IOException ignore){ } executorService.shutdown(); } @Test public void cowPoolClosedWithTaskInQueue() throws Exception{ ExecutorService executorService = Executors.newFixedThreadPool(2); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executorService, getWorkDir()); final Set<String> toPause = Sets.newHashSet(); final CountDownLatch pauseCopyLatch = new CountDownLatch(1); Directory remote = new CloseSafeDir() { @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { if (toPause.contains(name)){ try { pauseCopyLatch.await(); } catch (InterruptedException ignore) { } } return super.createOutput(name, context); } }; final Directory local = copier.wrapForWrite(defn, remote, false); toPause.add("t2"); byte[] t1 = writeFile(local, "t1"); byte[] t2 = writeFile(local, "t2"); byte[] t3 = writeFile(local, "t3"); byte[] t4 = writeFile(local, "t4"); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread closer = new Thread(new Runnable() { @Override public void run() { try { local.close(); } catch (Throwable e) { e.printStackTrace(); error.set(e); } } }); closer.start(); copier.close(); executorService.shutdown(); executorService.awaitTermination(100, TimeUnit.MILLISECONDS); pauseCopyLatch.countDown(); closer.join(); assertNotNull("Close should have thrown an exception", error.get()); } /** * Test the interaction between COR and COW using same underlying directory */ @Test public void cowConcurrentAccess() throws Exception{ CollectingExecutor executor = new CollectingExecutor(); ExecutorService executorService = Executors.newFixedThreadPool(2); executor.setForwardingExecutor(executorService); Directory baseDir = new CloseSafeDir(); String indexPath = "/foo"; builder.setProperty(IndexConstants.INDEX_PATH, indexPath); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executor, getWorkDir(), true); Directory remote = new CloseSafeDir(); byte[] f1 = writeFile(remote, "f1"); Directory cor1 = copier.wrapForRead(indexPath, defn, remote); readAndAssert(cor1, "f1", f1); cor1.close(); final CountDownLatch pauseCopyLatch = new CountDownLatch(1); Directory remote2 = new FilterDirectory(remote) { @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { try { pauseCopyLatch.await(); } catch (InterruptedException ignore) { } return super.createOutput(name, context); } }; //Start copying a file to remote via COW Directory cow1 = copier.wrapForWrite(defn, remote2, false); byte[] f2 = writeFile(cow1, "f2"); //Before copy is done to remote lets delete f1 from remote and //open a COR and close it such that it triggers delete of f1 remote.deleteFile("f1"); Directory cor2 = copier.wrapForRead(indexPath, defn, remote); //Ensure that deletion task submitted to executor get processed immediately executor.enableImmediateExecution(); cor2.close(); executor.enableDelayedExecution(); assertFalse(baseDir.fileExists("f1")); assertFalse("f2 should not have been copied to remote so far", remote.fileExists("f2")); assertTrue("f2 should exist", baseDir.fileExists("f2")); pauseCopyLatch.countDown(); cow1.close(); assertTrue("f2 should exist", remote.fileExists("f2")); executorService.shutdown(); } private static void doReindex(NodeBuilder builder) { builder.child(IndexDefinition.STATUS_NODE).remove(); LuceneIndexEditorContext.configureUniqueId(builder); } private byte[] writeFile(Directory dir, String name) throws IOException { byte[] data = randomBytes(rnd.nextInt(maxFileSize) + 1); IndexOutput o = dir.createOutput(name, IOContext.DEFAULT); o.writeBytes(data, data.length); o.close(); return data; } private byte[] randomBytes(int size) { byte[] data = new byte[size]; rnd.nextBytes(data); return data; } private File getWorkDir(){ return temporaryFolder.getRoot(); } private static void readAndAssert(Directory wrapped, String fileName, byte[] expectedData) throws IOException { IndexInput i = wrapped.openInput(fileName, IOContext.DEFAULT); byte[] result = new byte[(int)wrapped.fileLength(fileName)]; i.readBytes(result, 0, result.length); assertTrue(Arrays.equals(expectedData, result)); i.close(); } private static void copy(Directory source, Directory dest) throws IOException { for (String file : source.listAll()) { source.copy(dest, file, file, IOContext.DEFAULT); } } private class RAMIndexCopier extends IndexCopier { final Directory baseDir; public RAMIndexCopier(Directory baseDir, Executor executor, File indexRootDir, boolean prefetchEnabled) throws IOException { super(executor, indexRootDir, prefetchEnabled); this.baseDir = baseDir; } public RAMIndexCopier(Directory baseDir, Executor executor, File indexRootDir) throws IOException { this(baseDir, executor, indexRootDir, false); } @Override protected Directory createLocalDirForIndexReader(String indexPath, IndexDefinition definition) throws IOException { return baseDir; } @Override protected Directory createLocalDirForIndexWriter(IndexDefinition definition) throws IOException { return baseDir; } } private static class TestRAMDirectory extends RAMDirectory { final List<String> openedFiles = newArrayList(); @Override public IndexInput openInput(String name, IOContext context) throws IOException { openedFiles.add(name); return super.openInput(name, context); } public void reset(){ openedFiles.clear(); } } private static class CloseSafeDir extends RAMDirectory { @Override public void close() { } } private static class CollectingExecutor implements Executor { final BlockingQueue<Runnable> commands = new LinkedBlockingQueue<Runnable>(); private volatile boolean immediateExecution = false; private volatile Executor forwardingExecutor; @Override public void execute(Runnable command) { if (immediateExecution){ command.run(); return; } if (forwardingExecutor != null){ forwardingExecutor.execute(command); return; } commands.add(command); } void executeAll(){ Runnable c; while ((c = commands.poll()) != null){ c.run(); } } void enableImmediateExecution(){ immediateExecution = true; } void enableDelayedExecution(){ immediateExecution = false; } void setForwardingExecutor(Executor forwardingExecutor){ this.forwardingExecutor = forwardingExecutor; } } }
oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexCopierTest.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.jackrabbit.oak.plugins.index.lucene; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.management.openmbean.TabularData; import com.google.common.base.StandardSystemProperty; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ForwardingListeningExecutorService; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.oak.commons.IOUtils; import org.apache.jackrabbit.oak.plugins.index.IndexConstants; import org.apache.jackrabbit.oak.spi.state.NodeBuilder; import org.apache.jackrabbit.oak.spi.state.NodeState; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FilterDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; import static org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent.INITIAL_CONTENT; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; public class IndexCopierTest { private Random rnd = new Random(); private int maxFileSize = 7896; private NodeState root = INITIAL_CONTENT; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target")); private NodeBuilder builder = root.builder(); private String indexPath = "/oak:index/test"; @Before public void setUp(){ builder.setProperty(IndexConstants.INDEX_PATH, indexPath); LuceneIndexEditorContext.configureUniqueId(builder); } @Test public void basicTest() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , "t1"); byte[] t2 = writeFile(remote , "t2"); assertEquals(2, wrapped.listAll().length); assertTrue(wrapped.fileExists("t1")); assertTrue(wrapped.fileExists("t2")); assertEquals(t1.length, wrapped.fileLength("t1")); assertEquals(t2.length, wrapped.fileLength("t2")); readAndAssert(wrapped, "t1", t1); //t1 should now be added to testDir assertTrue(baseDir.fileExists("t1")); } @Test public void basicTestWithPrefetch() throws Exception{ final List<String> syncedFiles = Lists.newArrayList(); Directory baseDir = new RAMDirectory(){ @Override public void sync(Collection<String> names) throws IOException { syncedFiles.addAll(names); super.sync(names); } }; IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir(), true); Directory remote = new RAMDirectory(); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote , "t2"); Directory wrapped = c1.wrapForRead("/foo", defn, remote); assertEquals(2, wrapped.listAll().length); assertThat(syncedFiles, containsInAnyOrder("t1", "t2")); assertTrue(wrapped.fileExists("t1")); assertTrue(wrapped.fileExists("t2")); assertTrue(baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); assertEquals(t1.length, wrapped.fileLength("t1")); assertEquals(t2.length, wrapped.fileLength("t2")); readAndAssert(wrapped, "t1", t1); } @Test public void nonExistentFile() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); CollectingExecutor executor = new CollectingExecutor(); IndexCopier c1 = new RAMIndexCopier(baseDir, executor, getWorkDir(), true); Directory remote = new RAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); try { wrapped.openInput("foo.txt", IOContext.DEFAULT); fail(); } catch(FileNotFoundException ignore){ } assertEquals(0, executor.commands.size()); } @Test public void basicTestWithFS() throws Exception{ IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new IndexCopier(sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote , "t2"); assertEquals(2, wrapped.listAll().length); assertTrue(wrapped.fileExists("t1")); assertTrue(wrapped.fileExists("t2")); assertEquals(t1.length, wrapped.fileLength("t1")); assertEquals(t2.length, wrapped.fileLength("t2")); readAndAssert(wrapped, "t1", t1); //t1 should now be added to testDir File indexDir = c1.getIndexDir(defn, "/foo"); assertTrue(new File(indexDir, "t1").exists()); TabularData td = c1.getIndexPathMapping(); assertEquals(1, td.size()); } @Test public void deleteOldPostReindex() throws Exception{ assumeNotWindows(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new IndexCopier(sameThreadExecutor(), getWorkDir()); Directory remote = new CloseSafeDir(); Directory w1 = c1.wrapForRead(indexPath, defn, remote); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote , "t2"); readAndAssert(w1, "t1", t1); readAndAssert(w1, "t2", t2); //t1 should now be added to testDir File indexDir = c1.getIndexDir(defn, indexPath); assertTrue(new File(indexDir, "t1").exists()); doReindex(builder); defn = new IndexDefinition(root, builder.getNodeState()); //Close old version w1.close(); //Get a new one with updated reindexCount Directory w2 = c1.wrapForRead(indexPath, defn, remote); readAndAssert(w2, "t1", t1); w2.close(); assertFalse("Old index directory should have been removed", indexDir.exists()); //Assert that new index file do exist and not get removed File indexDir2 = c1.getIndexDir(defn, indexPath); assertTrue(new File(indexDir2, "t1").exists()); //Check if parent directory is also removed i.e. //index count should be 1 now assertEquals(1, c1.getIndexRootDirectory().getLocalIndexes(indexPath).size()); } @Test public void concurrentRead() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); CollectingExecutor executor = new CollectingExecutor(); IndexCopier c1 = new RAMIndexCopier(baseDir, executor, getWorkDir()); TestRAMDirectory remote = new TestRAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , "t1"); //1. Trigger a read which should go to remote readAndAssert(wrapped, "t1", t1); assertEquals(1, c1.getScheduledForCopyCount()); assertEquals(1, remote.openedFiles.size()); assertEquals(1, executor.commands.size()); //2. Trigger another read and this should also be //served from remote readAndAssert(wrapped, "t1", t1); assertEquals(1, c1.getScheduledForCopyCount()); assertEquals(2, remote.openedFiles.size()); //Second read should not add a new copy task assertEquals(1, executor.commands.size()); //3. Perform copy executor.executeAll(); remote.reset(); //4. Now read again after copy is done readAndAssert(wrapped, "t1", t1); // Now read should be served from local and not from remote assertEquals(0, remote.openedFiles.size()); assertEquals(0, c1.getScheduledForCopyCount()); } @Test public void copyInProgressStats() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); final List<ListenableFuture<?>> submittedTasks = Lists.newArrayList(); ExecutorService executor = new ForwardingListeningExecutorService() { @Override protected ListeningExecutorService delegate() { return MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); } @Override public void execute(Runnable command) { submittedTasks.add(super.submit(command)); } }; IndexCopier c1 = new RAMIndexCopier(baseDir, executor, getWorkDir()); final CountDownLatch copyProceed = new CountDownLatch(1); final CountDownLatch copyRequestArrived = new CountDownLatch(1); TestRAMDirectory remote = new TestRAMDirectory(){ @Override public void copy(Directory to, String src, String dest, IOContext context) throws IOException { copyRequestArrived.countDown(); try { copyProceed.await(); } catch (InterruptedException e) { } super.copy(to, src, dest, context); } }; Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , "t1"); //1. Trigger a read which should go to remote readAndAssert(wrapped, "t1", t1); copyRequestArrived.await(); assertEquals(1, c1.getCopyInProgressCount()); assertEquals(1, remote.openedFiles.size()); //2. Trigger another read and this should also be //served from remote readAndAssert(wrapped, "t1", t1); assertEquals(1, c1.getCopyInProgressCount()); assertEquals(IOUtils.humanReadableByteCount(t1.length), c1.getCopyInProgressSize()); assertEquals(1, c1.getCopyInProgressDetails().length); System.out.println(Arrays.toString(c1.getCopyInProgressDetails())); assertEquals(2, remote.openedFiles.size()); //3. Perform copy copyProceed.countDown(); Futures.allAsList(submittedTasks).get(); remote.reset(); //4. Now read again after copy is done readAndAssert(wrapped, "t1", t1); // Now read should be served from local and not from remote assertEquals(0, remote.openedFiles.size()); assertEquals(0, c1.getCopyInProgressCount()); executor.shutdown(); } /** * Test for the case where local directory is opened already contains * the index files and in such a case file should not be read from remote */ @Test public void reuseLocalDir() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); TestRAMDirectory remote = new TestRAMDirectory(); Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote, "t1"); //1. Read for the first time should be served from remote readAndAssert(wrapped, "t1", t1); assertEquals(1, remote.openedFiles.size()); //2. Reuse the testDir and read again Directory wrapped2 = c1.wrapForRead("/foo", defn, remote); remote.reset(); //3. Now read should be served from local readAndAssert(wrapped2, "t1", t1); assertEquals(0, remote.openedFiles.size()); //Now check if local file gets corrupted then read from remote Directory wrapped3 = c1.wrapForRead("/foo", defn, remote); remote.reset(); //4. Corrupt the local copy writeFile(baseDir, "t1"); //Now read would be done from remote readAndAssert(wrapped3, "t1", t1); assertEquals(1, remote.openedFiles.size()); } @Test public void deleteCorruptedFile() throws Exception{ Directory baseDir = new RAMDirectory(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); RAMIndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(){ @Override public IndexInput openInput(String name, IOContext context) throws IOException { throw new IllegalStateException("boom"); } }; String fileName = "failed.txt"; Directory wrapped = c1.wrapForRead("/foo", defn, remote); byte[] t1 = writeFile(remote , fileName); try { readAndAssert(wrapped, fileName, t1); fail("Read of file should have failed"); } catch (IllegalStateException ignore){ } assertFalse(c1.baseDir.fileExists(fileName)); } @Test public void deletesOnClose() throws Exception{ //Use a close safe dir. In actual case the FSDir would //be opened on same file system hence it can retain memory //but RAMDirectory does not retain memory hence we simulate //that by not closing the RAMDir and reuse it Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory r1 = new RAMDirectory(); byte[] t1 = writeFile(r1, "t1"); byte[] t2 = writeFile(r1 , "t2"); Directory w1 = c1.wrapForRead("/foo", defn, r1); readAndAssert(w1, "t1", t1); readAndAssert(w1, "t2", t2); // t1 and t2 should now be present in local (base dir which back local) assertTrue(baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); Directory r2 = new RAMDirectory(); copy(r1, r2); r2.deleteFile("t1"); Directory w2 = c1.wrapForRead("/foo", defn, r2); //Close would trigger removal of file which are not present in remote w2.close(); assertFalse("t1 should have been deleted", baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); } @Test public void failureInDelete() throws Exception{ final Set<String> testFiles = new HashSet<String>(); Directory baseDir = new CloseSafeDir() { @Override public void deleteFile(String name) throws IOException { if (testFiles.contains(name)){ throw new IOException("Not allowed to delete " + name); } super.deleteFile(name); } }; IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier c1 = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory r1 = new RAMDirectory(); byte[] t1 = writeFile(r1, "t1"); byte[] t2 = writeFile(r1 , "t2"); Directory w1 = c1.wrapForRead("/foo", defn, r1); readAndAssert(w1, "t1", t1); readAndAssert(w1, "t2", t2); // t1 and t2 should now be present in local (base dir which back local) assertTrue(baseDir.fileExists("t1")); assertTrue(baseDir.fileExists("t2")); Directory r2 = new CloseSafeDir(); copy(r1, r2); r2.deleteFile("t1"); Directory w2 = c1.wrapForRead("/foo", defn, r2); //Close would trigger removal of file which are not present in remote testFiles.add("t1"); w2.close(); assertEquals(1, c1.getFailedToDeleteFiles().size()); IndexCopier.LocalIndexFile testFile = c1.getFailedToDeleteFiles().values().iterator().next(); assertEquals(1, testFile.getDeleteAttemptCount()); assertEquals(IOUtils.humanReadableByteCount(t1.length), c1.getGarbageSize()); assertEquals(1, c1.getGarbageDetails().length); Directory w3 = c1.wrapForRead("/foo", defn, r2); w3.close(); assertEquals(2, testFile.getDeleteAttemptCount()); //Now let the file to be deleted testFiles.clear(); Directory w4 = c1.wrapForRead("/foo", defn, r2); w4.close(); //No pending deletes left assertEquals(0, c1.getFailedToDeleteFiles().size()); } @Test public void deletedOnlyFilesForOlderVersion() throws Exception{ Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); //1. Open a local and read t1 from remote Directory remote1 = new RAMDirectory(); byte[] t1 = writeFile(remote1, "t1"); Directory local1 = copier.wrapForRead("/foo", defn, remote1); readAndAssert(local1, "t1", t1); //While local1 is open , open another local2 and read t2 Directory remote2 = new RAMDirectory(); byte[] t2 = writeFile(remote2, "t2"); Directory local2 = copier.wrapForRead("/foo", defn, remote2); readAndAssert(local2, "t2", t2); //Close local1 local1.close(); //t2 should still be readable readAndAssert(local2, "t2", t2); } @Test public void wrapForWriteWithoutIndexPath() throws Exception{ assumeNotWindows(); Directory remote = new CloseSafeDir(); IndexCopier copier = new IndexCopier(sameThreadExecutor(), getWorkDir()); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); Directory dir = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(dir, "t1"); dir.close(); readAndAssert(remote, "t1", t1); //Work dir must be empty post close assertArrayEquals(FileUtils.EMPTY_FILE_ARRAY, copier.getIndexWorkDir().listFiles()); } @Test public void wrapForWriteWithIndexPath() throws Exception{ assumeNotWindows(); Directory remote = new CloseSafeDir(); IndexCopier copier = new IndexCopier(sameThreadExecutor(), getWorkDir()); builder.setProperty(IndexConstants.INDEX_PATH, "foo"); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); Directory dir = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(dir, "t1"); dir.close(); readAndAssert(remote, "t1", t1); //Work dir must be empty post close File indexDir = copier.getIndexDir(defn, "foo"); List<File> files = new ArrayList<File>(FileUtils.listFiles(indexDir, null, true)); Set<String> fileNames = Sets.newHashSet(); for (File f : files){ fileNames.add(f.getName()); } assertThat(fileNames, contains("t1")); } @Test public void copyOnWriteBasics() throws Exception{ Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new RAMDirectory(); byte[] t1 = writeFile(remote, "t1"); //State of remote directory should set before wrapping as later //additions would not be picked up given COW assume remote directory //to be read only Directory local = copier.wrapForWrite(defn, remote, false); assertEquals(newHashSet("t1"), newHashSet(local.listAll())); assertEquals(t1.length, local.fileLength("t1")); byte[] t2 = writeFile(local, "t2"); assertEquals(newHashSet("t1", "t2"), newHashSet(local.listAll())); assertEquals(t2.length, local.fileLength("t2")); assertTrue(local.fileExists("t1")); assertTrue(local.fileExists("t2")); assertTrue("t2 should be copied to remote", remote.fileExists("t2")); readAndAssert(local, "t1", t1); readAndAssert(local, "t2", t2); local.deleteFile("t1"); assertEquals(newHashSet("t2"), newHashSet(local.listAll())); local.deleteFile("t2"); assertEquals(newHashSet(), newHashSet(local.listAll())); try { local.fileLength("nonExistentFile"); fail(); } catch (FileNotFoundException ignore) { } try { local.openInput("nonExistentFile", IOContext.DEFAULT); fail(); } catch (FileNotFoundException ignore) { } local.close(); assertFalse(baseDir.fileExists("t2")); } /** * Checks for the case where if the file exist local before writer starts * then those files do not get deleted even if deleted by writer via * indexing process from 'baseDir' as they might be in use by existing open * indexes */ @Test public void cowExistingLocalFileNotDeleted() throws Exception{ Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); Directory remote = new CloseSafeDir(); byte[] t1 = writeFile(remote, "t1"); byte[] t2 = writeFile(remote, "t2"); Directory local = copier.wrapForWrite(defn, remote, false); assertEquals(newHashSet("t1", "t2"), newHashSet(local.listAll())); byte[] t3 = writeFile(local, "t3"); //Now pull in the file t1 via CopyOnRead in baseDir Directory localForRead = copier.wrapForRead("/foo", defn, remote); readAndAssert(localForRead, "t1", t1); //File which was copied from remote should not be deleted from baseDir //upon delete from local assertTrue(baseDir.fileExists("t1")); local.deleteFile("t1"); assertFalse("t1 should be deleted from remote", remote.fileExists("t1")); assertFalse("t1 should be deleted from 'local' view also", local.fileExists("t1")); assertTrue("t1 should not be deleted from baseDir", baseDir.fileExists("t1")); //File which was created only via local SHOULD get removed from //baseDir only upon close assertTrue(baseDir.fileExists("t3")); local.deleteFile("t3"); assertFalse("t1 should be deleted from remote", local.fileExists("t3")); assertTrue("t1 should NOT be deleted from remote", baseDir.fileExists("t3")); local.close(); assertFalse("t3 should also be deleted from local", baseDir.fileExists("t3")); } @Test public void cowReadDoneFromLocalIfFileExist() throws Exception{ final Set<String> readLocal = newHashSet(); Directory baseDir = new CloseSafeDir(){ @Override public IndexInput openInput(String name, IOContext context) throws IOException { readLocal.add(name); return super.openInput(name, context); } }; IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, sameThreadExecutor(), getWorkDir()); final Set<String> readRemotes = newHashSet(); Directory remote = new RAMDirectory() { @Override public IndexInput openInput(String name, IOContext context) throws IOException { readRemotes.add(name); return super.openInput(name, context); } }; byte[] t1 = writeFile(remote, "t1"); Directory local = copier.wrapForWrite(defn, remote, false); //Read should be served from remote readRemotes.clear();readLocal.clear(); readAndAssert(local, "t1", t1); assertEquals(newHashSet("t1"), readRemotes); assertEquals(newHashSet(), readLocal); //Now pull in the file t1 via CopyOnRead in baseDir Directory localForRead = copier.wrapForRead("/foo", defn, remote); readAndAssert(localForRead, "t1", t1); //Read should be served from local readRemotes.clear();readLocal.clear(); readAndAssert(local, "t1", t1); assertEquals(newHashSet(), readRemotes); assertEquals(newHashSet("t1"), readLocal); local.close(); } @Test public void cowCopyDoneOnClose() throws Exception{ final CollectingExecutor executor = new CollectingExecutor(); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executor, getWorkDir()); Directory remote = new CloseSafeDir(); final Directory local = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(local, "t1"); assertTrue(local.fileExists("t1")); assertFalse("t1 should NOT be copied to remote", remote.fileExists("t1")); //Execute all job executor.executeAll(); assertTrue("t1 should now be copied to remote", remote.fileExists("t1")); byte[] t2 = writeFile(local, "t2"); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); final ExecutorService executorService = Executors.newFixedThreadPool(4); final CountDownLatch copyLatch = new CountDownLatch(1); Future<?> copyTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { copyLatch.await(); //the executor to a proper one as it might happen that //STOP task is added post CountingExecutor has executed. Then there //would be none to process the STOP. Having a proper executor would //handle that case executor.setForwardingExecutor(executorService); executor.executeAll(); return null; } }); final CountDownLatch closeLatch = new CountDownLatch(1); Future<?> closeTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { closeLatch.await(); local.close(); return null; } }); closeLatch.countDown(); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); //Let copy to proceed copyLatch.countDown(); //Now wait for close to finish closeTasks.get(); assertTrue("t2 should now be copied to remote", remote.fileExists("t2")); executorService.shutdown(); } @Test public void cowCopyDoneOnCloseExceptionHandling() throws Exception{ final CollectingExecutor executor = new CollectingExecutor(); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executor, getWorkDir()); Directory remote = new CloseSafeDir(); final Directory local = copier.wrapForWrite(defn, remote, false); byte[] t1 = writeFile(local, "t1"); assertTrue(local.fileExists("t1")); assertFalse("t1 should NOT be copied to remote", remote.fileExists("t1")); //Execute all job executor.executeAll(); assertTrue("t1 should now be copied to remote", remote.fileExists("t1")); byte[] t2 = writeFile(local, "t2"); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); ExecutorService executorService = Executors.newFixedThreadPool(2); final CountDownLatch copyLatch = new CountDownLatch(1); Future<?> copyTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { copyLatch.await(); executor.executeAll(); executor.enableImmediateExecution(); return null; } }); final CountDownLatch closeLatch = new CountDownLatch(1); Future<?> closeTasks = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { closeLatch.await(); local.close(); return null; } }); closeLatch.countDown(); assertFalse("t2 should NOT be copied to remote", remote.fileExists("t2")); //Let copy to proceed copyLatch.countDown(); //Now wait for close to finish closeTasks.get(); assertTrue("t2 should now be copied to remote", remote.fileExists("t2")); executorService.shutdown(); } @Test public void cowFailureInCopy() throws Exception{ ExecutorService executorService = Executors.newFixedThreadPool(2); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executorService, getWorkDir()); final Set<String> toFail = Sets.newHashSet(); Directory remote = new CloseSafeDir() { @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { if (toFail.contains(name)){ throw new RuntimeException("Failing copy for "+name); } return super.createOutput(name, context); } }; final Directory local = copier.wrapForWrite(defn, remote, false); toFail.add("t2"); byte[] t1 = writeFile(local, "t1"); byte[] t2 = writeFile(local, "t2"); try { local.close(); fail(); } catch (IOException ignore){ } executorService.shutdown(); } @Test public void cowPoolClosedWithTaskInQueue() throws Exception{ ExecutorService executorService = Executors.newFixedThreadPool(2); Directory baseDir = new CloseSafeDir(); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executorService, getWorkDir()); final Set<String> toPause = Sets.newHashSet(); final CountDownLatch pauseCopyLatch = new CountDownLatch(1); Directory remote = new CloseSafeDir() { @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { if (toPause.contains(name)){ try { pauseCopyLatch.await(); } catch (InterruptedException ignore) { } } return super.createOutput(name, context); } }; final Directory local = copier.wrapForWrite(defn, remote, false); toPause.add("t2"); byte[] t1 = writeFile(local, "t1"); byte[] t2 = writeFile(local, "t2"); byte[] t3 = writeFile(local, "t3"); byte[] t4 = writeFile(local, "t4"); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread closer = new Thread(new Runnable() { @Override public void run() { try { local.close(); } catch (Throwable e) { e.printStackTrace(); error.set(e); } } }); closer.start(); copier.close(); executorService.shutdown(); executorService.awaitTermination(100, TimeUnit.MILLISECONDS); pauseCopyLatch.countDown(); closer.join(); assertNotNull("Close should have thrown an exception", error.get()); } /** * Test the interaction between COR and COW using same underlying directory */ @Test public void cowConcurrentAccess() throws Exception{ CollectingExecutor executor = new CollectingExecutor(); ExecutorService executorService = Executors.newFixedThreadPool(2); executor.setForwardingExecutor(executorService); Directory baseDir = new CloseSafeDir(); String indexPath = "/foo"; builder.setProperty(IndexConstants.INDEX_PATH, indexPath); IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); IndexCopier copier = new RAMIndexCopier(baseDir, executor, getWorkDir(), true); Directory remote = new CloseSafeDir(); byte[] f1 = writeFile(remote, "f1"); Directory cor1 = copier.wrapForRead(indexPath, defn, remote); readAndAssert(cor1, "f1", f1); cor1.close(); final CountDownLatch pauseCopyLatch = new CountDownLatch(1); Directory remote2 = new FilterDirectory(remote) { @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { try { pauseCopyLatch.await(); } catch (InterruptedException ignore) { } return super.createOutput(name, context); } }; //Start copying a file to remote via COW Directory cow1 = copier.wrapForWrite(defn, remote2, false); byte[] f2 = writeFile(cow1, "f2"); //Before copy is done to remote lets delete f1 from remote and //open a COR and close it such that it triggers delete of f1 remote.deleteFile("f1"); Directory cor2 = copier.wrapForRead(indexPath, defn, remote); //Ensure that deletion task submitted to executor get processed immediately executor.enableImmediateExecution(); cor2.close(); executor.enableDelayedExecution(); assertFalse(baseDir.fileExists("f1")); assertFalse("f2 should not have been copied to remote so far", remote.fileExists("f2")); assertTrue("f2 should exist", baseDir.fileExists("f2")); pauseCopyLatch.countDown(); cow1.close(); assertTrue("f2 should exist", remote.fileExists("f2")); executorService.shutdown(); } private static void doReindex(NodeBuilder builder) { builder.child(IndexDefinition.STATUS_NODE).remove(); LuceneIndexEditorContext.configureUniqueId(builder); } private byte[] writeFile(Directory dir, String name) throws IOException { byte[] data = randomBytes(rnd.nextInt(maxFileSize) + 1); IndexOutput o = dir.createOutput(name, IOContext.DEFAULT); o.writeBytes(data, data.length); o.close(); return data; } private byte[] randomBytes(int size) { byte[] data = new byte[size]; rnd.nextBytes(data); return data; } private File getWorkDir(){ return temporaryFolder.getRoot(); } private static void readAndAssert(Directory wrapped, String fileName, byte[] expectedData) throws IOException { IndexInput i = wrapped.openInput(fileName, IOContext.DEFAULT); byte[] result = new byte[(int)wrapped.fileLength(fileName)]; i.readBytes(result, 0, result.length); assertTrue(Arrays.equals(expectedData, result)); i.close(); } private static void copy(Directory source, Directory dest) throws IOException { for (String file : source.listAll()) { source.copy(dest, file, file, IOContext.DEFAULT); } } private class RAMIndexCopier extends IndexCopier { final Directory baseDir; public RAMIndexCopier(Directory baseDir, Executor executor, File indexRootDir, boolean prefetchEnabled) throws IOException { super(executor, indexRootDir, prefetchEnabled); this.baseDir = baseDir; } public RAMIndexCopier(Directory baseDir, Executor executor, File indexRootDir) throws IOException { this(baseDir, executor, indexRootDir, false); } @Override protected Directory createLocalDirForIndexReader(String indexPath, IndexDefinition definition) throws IOException { return baseDir; } @Override protected Directory createLocalDirForIndexWriter(IndexDefinition definition) throws IOException { return baseDir; } } private static class TestRAMDirectory extends RAMDirectory { final List<String> openedFiles = newArrayList(); @Override public IndexInput openInput(String name, IOContext context) throws IOException { openedFiles.add(name); return super.openInput(name, context); } public void reset(){ openedFiles.clear(); } } private static class CloseSafeDir extends RAMDirectory { @Override public void close() { } } private static class CollectingExecutor implements Executor { final BlockingQueue<Runnable> commands = new LinkedBlockingQueue<Runnable>(); private volatile boolean immediateExecution = false; private volatile Executor forwardingExecutor; @Override public void execute(Runnable command) { if (immediateExecution){ command.run(); return; } if (forwardingExecutor != null){ forwardingExecutor.execute(command); return; } commands.add(command); } void executeAll(){ Runnable c; while ((c = commands.poll()) != null){ c.run(); } } void enableImmediateExecution(){ immediateExecution = true; } void enableDelayedExecution(){ immediateExecution = false; } void setForwardingExecutor(Executor forwardingExecutor){ this.forwardingExecutor = forwardingExecutor; } } private static void assumeNotWindows() { assumeTrue(!StandardSystemProperty.OS_NAME.value().toLowerCase().contains("windows")); } }
OAK-3629 - Index corruption seen with CopyOnRead when index definition is recreated Checked with Vikas that now test pass on windows also. So enabling those test for windows also git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1751420 13f79535-47bb-0310-9956-ffa450edef68
oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexCopierTest.java
OAK-3629 - Index corruption seen with CopyOnRead when index definition is recreated
<ide><path>ak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexCopierTest.java <ide> <ide> @Test <ide> public void deleteOldPostReindex() throws Exception{ <del> assumeNotWindows(); <ide> IndexDefinition defn = new IndexDefinition(root, builder.getNodeState()); <ide> IndexCopier c1 = new IndexCopier(sameThreadExecutor(), getWorkDir()); <ide> <ide> <ide> @Test <ide> public void wrapForWriteWithoutIndexPath() throws Exception{ <del> assumeNotWindows(); <ide> Directory remote = new CloseSafeDir(); <ide> <ide> IndexCopier copier = new IndexCopier(sameThreadExecutor(), getWorkDir()); <ide> <ide> @Test <ide> public void wrapForWriteWithIndexPath() throws Exception{ <del> assumeNotWindows(); <ide> Directory remote = new CloseSafeDir(); <ide> <ide> IndexCopier copier = new IndexCopier(sameThreadExecutor(), getWorkDir()); <ide> } <ide> } <ide> <del> private static void assumeNotWindows() { <del> assumeTrue(!StandardSystemProperty.OS_NAME.value().toLowerCase().contains("windows")); <del> } <ide> }
Java
isc
b67290af82f89c3091668c2667e8152012db7405
0
ylfonline/ormlite-jdbc,dankito/ormlite-jpa-jdbc,j256/ormlite-jdbc,isbm/ormlite-jdbc,t9nf/ormlite-jdbc
package com.j256.ormlite.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import org.junit.Test; import com.j256.ormlite.BaseJdbcTest; import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseFieldConfig; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.misc.BaseDaoEnabled; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.j256.ormlite.stmt.UpdateBuilder; import com.j256.ormlite.stmt.Where; import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTableConfig; import com.j256.ormlite.table.TableUtils; public class JdbcBaseDaoImplTest extends BaseJdbcTest { private static final boolean CLOSE_IS_NOOP = false; private static final boolean UPDATE_ROWS_RETURNS_ONE = false; protected boolean isTableExistsWorks() { return true; } /* ======================================================================================== */ private final static String DEFAULT_VALUE_STRING = "1314199"; private final static int DEFAULT_VALUE = Integer.parseInt(DEFAULT_VALUE_STRING); private final static int ALL_TYPES_STRING_WIDTH = 4; protected final static String FOO_TABLE_NAME = "footable"; private final static String ENUM_TABLE_NAME = "enumtable"; private final static String NULL_BOOLEAN_TABLE_NAME = "nullbooltable"; private final static String NULL_INT_TABLE_NAME = "nullinttable"; private final static String DEFAULT_BOOLEAN_VALUE = "true"; private final static String DEFAULT_STRING_VALUE = "foo"; // this can't have non-zero milliseconds private final static String DEFAULT_DATE_VALUE = "2010-07-16 01:31:17.000000"; private final static String DEFAULT_DATE_LONG_VALUE = "1282768620000"; private final static String DEFAULT_DATE_STRING_FORMAT = "MM/dd/yyyy HH-mm-ss-SSSSSS"; private final static String DEFAULT_DATE_STRING_VALUE = "07/16/2010 01-31-17-000000"; private final static String DEFAULT_BYTE_VALUE = "1"; private final static String DEFAULT_SHORT_VALUE = "2"; private final static String DEFAULT_INT_VALUE = "3"; private final static String DEFAULT_LONG_VALUE = "4"; private final static String DEFAULT_FLOAT_VALUE = "5"; private final static String DEFAULT_DOUBLE_VALUE = "6"; private final static String DEFAULT_ENUM_VALUE = "FIRST"; private final static String DEFAULT_ENUM_NUMBER_VALUE = "1"; @Test public void testCreateDaoStatic() throws Exception { if (connectionSource == null) { return; } createTable(Foo.class, true); Dao<Foo, Integer> fooDao = DaoManager.createDao(connectionSource, Foo.class); String stuff = "stuff"; Foo foo = new Foo(); foo.stuff = stuff; assertEquals(1, fooDao.create(foo)); // now we query for foo from the database to make sure it was persisted right Foo foo2 = fooDao.queryForId(foo.id); assertNotNull(foo2); assertEquals(foo.id, foo2.id); assertEquals(stuff, foo2.stuff); } @Test public void testCreateUpdateDelete() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String s1 = "stuff"; Foo foo1 = new Foo(); foo1.stuff = s1; assertEquals(0, foo1.id); // persist foo to db through the dao and sends the id on foo because it was auto-generated by the db assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); assertEquals(s1, foo1.stuff); // now we query for foo from the database to make sure it was persisted right Foo foo2 = fooDao.queryForId(foo1.id); assertNotNull(foo2); assertEquals(foo1.id, foo2.id); assertEquals(s1, foo2.stuff); String s2 = "stuff2"; foo2.stuff = s2; // now we update 1 row in a the database after changing foo assertEquals(1, fooDao.update(foo2)); // now we get it from the db again to make sure it was updated correctly Foo foo3 = fooDao.queryForId(foo1.id); assertEquals(s2, foo3.stuff); assertEquals(1, fooDao.delete(foo2)); assertNull(fooDao.queryForId(foo1.id)); } @Test public void testDoubleCreate() throws Exception { Dao<DoubleCreate, Object> doubleDao = createDao(DoubleCreate.class, true); int id = 313413123; DoubleCreate foo = new DoubleCreate(); foo.id = id; assertEquals(1, doubleDao.create(foo)); try { doubleDao.create(foo); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testIterateRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> acctList = fooDao.queryForAll(); int initialSize = acctList.size(); Foo foo1 = new Foo(); foo1.stuff = "s1"; Foo foo2 = new Foo(); foo2.stuff = "s2"; Foo foo3 = new Foo(); foo3.stuff = "s3"; fooDao.create(foo1); fooDao.create(foo2); fooDao.create(foo3); assertTrue(foo1.id != foo2.id); assertTrue(foo1.id != foo3.id); assertTrue(foo2.id != foo3.id); assertEquals(foo1, fooDao.queryForId(foo1.id)); assertEquals(foo2, fooDao.queryForId(foo2.id)); assertEquals(foo3, fooDao.queryForId(foo3.id)); acctList = fooDao.queryForAll(); assertEquals(initialSize + 3, acctList.size()); assertEquals(foo1, acctList.get(acctList.size() - 3)); assertEquals(foo2, acctList.get(acctList.size() - 2)); assertEquals(foo3, acctList.get(acctList.size() - 1)); int acctC = 0; Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { Foo foo = iterator.next(); if (acctC == acctList.size() - 3) { assertEquals(foo1, foo); } else if (acctC == acctList.size() - 2) { iterator.remove(); assertEquals(foo2, foo); } else if (acctC == acctList.size() - 1) { assertEquals(foo3, foo); } acctC++; } assertEquals(initialSize + 3, acctC); } @Test public void testGeneratedField() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; assertEquals(0, foo1.id); assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); } @Test public void testGeneratedIdNotNullField() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; assertEquals(0, foo1.id); assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); } @Test public void testObjectToString() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff = "foo123231"; Foo foo1 = new Foo(); foo1.stuff = stuff; String objStr = fooDao.objectToString(foo1); assertTrue(objStr.contains(Integer.toString(foo1.id))); assertTrue(objStr.contains(stuff)); } @Test public void testCreateNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.create((Foo) null)); } @Test public void testUpdateNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.update((Foo) null)); } @Test public void testUpdateIdNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.updateId(null, null)); } @Test public void testDeleteNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.delete((Foo) null)); } @Test public void testCloseInIterator() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); Iterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { iterator.next(); closeConnectionSource(); } if (!CLOSE_IS_NOOP) { fail("expected exception"); } } catch (IllegalStateException e) { // expected } } @Test public void testCloseIteratorFirst() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); closeConnectionSource(); try { fooDao.iterator(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } @Test public void testCloseIteratorBeforeNext() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { closeConnectionSource(); iterator.next(); } if (!CLOSE_IS_NOOP) { fail("expected exception"); } } catch (IllegalStateException e) { // expected } finally { iterator.close(); } } @Test public void testCloseIteratorBeforeRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { iterator.next(); closeConnectionSource(); iterator.remove(); } fail("expected exception"); } catch (Exception e) { // expected } } @Test public void testNoNextBeforeRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { iterator.remove(); fail("expected exception"); } catch (IllegalStateException e) { // expected } finally { iterator.close(); } } @Test public void testIteratePageSize() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); int numItems = 1000; fooDao.callBatchTasks(new InsertCallable(numItems, fooDao)); // now delete them with the iterator to test page-size Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } @Test public void testIteratorPreparedQuery() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); // do an insert of bunch of items final int numItems = 100; fooDao.callBatchTasks(new InsertCallable(numItems, fooDao)); int lastX = 10; PreparedQuery<Foo> preparedQuery = fooDao.queryBuilder().where().ge(Foo.VAL_FIELD_NAME, numItems - lastX).prepare(); // now delete them with the iterator to test page-size Iterator<Foo> iterator = fooDao.iterator(preparedQuery); int itemC = 0; while (iterator.hasNext()) { Foo foo = iterator.next(); System.out.println("Foo = " + foo.val); itemC++; } assertEquals(lastX, itemC); } private static class InsertCallable implements Callable<Void> { private int numItems; private Dao<Foo, Integer> fooDao; public InsertCallable(int numItems, Dao<Foo, Integer> fooDao) { this.numItems = numItems; this.fooDao = fooDao; } public Void call() throws Exception { for (int i = 0; i < numItems; i++) { Foo foo = new Foo(); foo.val = i; assertEquals(1, fooDao.create(foo)); } return null; } } @Test public void testDeleteObjects() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> fooList = new ArrayList<Foo>(); for (int i = 0; i < 100; i++) { Foo foo = new Foo(); foo.stuff = Integer.toString(i); assertEquals(1, fooDao.create(foo)); fooList.add(foo); } int deleted = fooDao.delete(fooList); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteObjectsNone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> fooList = new ArrayList<Foo>(); assertEquals(fooList.size(), fooDao.delete(fooList)); assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteIds() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); final List<Integer> fooIdList = new ArrayList<Integer>(); fooDao.callBatchTasks(new Callable<Void>() { public Void call() throws Exception { for (int i = 0; i < 100; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); fooIdList.add(foo.id); } return null; } }); int deleted = fooDao.deleteIds(fooIdList); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooIdList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteIdsNone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Integer> fooIdList = new ArrayList<Integer>(); assertEquals(fooIdList.size(), fooDao.deleteIds(fooIdList)); assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeletePreparedStmtIn() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Integer> fooIdList = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); fooIdList.add(foo.id); } DeleteBuilder<Foo, Integer> stmtBuilder = fooDao.deleteBuilder(); stmtBuilder.where().in(Foo.ID_FIELD_NAME, fooIdList); int deleted = fooDao.delete(stmtBuilder.prepare()); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooIdList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteAllPreparedStmt() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); int fooN = 100; for (int i = 0; i < fooN; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); } DeleteBuilder<Foo, Integer> stmtBuilder = fooDao.deleteBuilder(); int deleted = fooDao.delete(stmtBuilder.prepare()); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooN, deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testHasNextAfterDone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { } assertFalse(iterator.hasNext()); } @Test public void testNextWithoutHasNext() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); try { iterator.next(); fail("expected exception"); } catch (Exception e) { // expected } } @Test public void testRemoveAfterDone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); assertFalse(iterator.hasNext()); try { iterator.remove(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } @Test public void testIteratorNoResults() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); assertFalse(iterator.hasNext()); assertNull(iterator.next()); } @Test public void testCreateNoId() throws Exception { Dao<NoId, Object> whereDao = createDao(NoId.class, true); NoId noId = new NoId(); assertEquals(0, whereDao.queryForAll().size()); // this should work even though there is no id whereDao.create(noId); assertEquals(1, whereDao.queryForAll().size()); } @Test public void testJustIdCreateQueryDelete() throws Exception { Dao<JustId, Object> justIdDao = createDao(JustId.class, true); String id = "just-id"; JustId justId = new JustId(); justId.id = id; assertEquals(1, justIdDao.create(justId)); JustId justId2 = justIdDao.queryForId(id); assertNotNull(justId2); assertEquals(id, justId2.id); assertEquals(1, justIdDao.delete(justId)); assertNull(justIdDao.queryForId(id)); // update should fail during construction } @Test public void testJustIdUpdateId() throws Exception { Dao<JustId, Object> justIdDao = createDao(JustId.class, true); String id = "just-id-update-1"; JustId justId = new JustId(); justId.id = id; assertEquals(1, justIdDao.create(justId)); JustId justId2 = justIdDao.queryForId(id); assertNotNull(justId2); assertEquals(id, justId2.id); String id2 = "just-id-update-2"; // change the id assertEquals(1, justIdDao.updateId(justId2, id2)); assertNull(justIdDao.queryForId(id)); JustId justId3 = justIdDao.queryForId(id2); assertNotNull(justId3); assertEquals(id2, justId3.id); assertEquals(1, justIdDao.delete(justId3)); assertNull(justIdDao.queryForId(id)); assertNull(justIdDao.queryForId(id2)); } @Test public void testJustIdRefresh() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff1 = "just-id-refresh-1"; Foo foo1 = new Foo(); foo1.stuff = stuff1; assertEquals(1, fooDao.create(foo1)); int id = foo1.id; Foo foo2 = fooDao.queryForId(id); assertNotNull(foo2); assertEquals(id, foo2.id); assertEquals(stuff1, foo2.stuff); String stuff2 = "just-id-refresh-2"; foo2.stuff = stuff2; // change the id in the db assertEquals(1, fooDao.update(foo2)); Foo foo3 = fooDao.queryForId(id); assertNotNull(foo3); assertEquals(id, foo3.id); assertEquals(stuff2, foo3.stuff); assertEquals(stuff1, foo1.stuff); assertEquals(1, fooDao.refresh(foo1)); assertEquals(stuff2, foo1.stuff); } @Test public void testSpringConstruction() throws Exception { if (connectionSource == null) { return; } createTable(Foo.class, true); BaseDaoImpl<Foo, Integer> fooDao = new BaseDaoImpl<Foo, Integer>(Foo.class) { }; try { fooDao.create(new Foo()); fail("expected exception"); } catch (IllegalStateException e) { // expected } fooDao.setConnectionSource(connectionSource); fooDao.initialize(); Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); assertEquals(1, fooDao.delete(foo)); } @Test public void testForeignCreation() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); ForeignWrapper wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(wrapper.id, wrapper2.id); assertEquals(wrapper.foreign.id, wrapper2.foreign.id); assertTrue(wrapperDao.objectsEqual(wrapper, wrapper2)); // this won't be true because wrapper2.foreign is a shell assertFalse(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertNull(wrapper2.foreign.stringField); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); // now it should be true assertTrue(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertEquals(stuff1, wrapper2.foreign.stringField); // create a new foreign foreign = new AllTypes(); String stuff2 = "stuff2"; foreign.stringField = stuff2; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); // change the foreign object wrapper.foreign = foreign; // update it assertEquals(1, wrapperDao.update(wrapper)); wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(wrapper.id, wrapper2.id); assertEquals(wrapper.foreign.id, wrapper2.foreign.id); assertTrue(wrapperDao.objectsEqual(wrapper, wrapper2)); // this won't be true because wrapper2.foreign is a shell assertFalse(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertNull(wrapper2.foreign.stringField); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); // now it should be true assertTrue(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertEquals(stuff2, wrapper2.foreign.stringField); } @Test public void testForeignRefreshNoChange() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); ForeignWrapper wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); AllTypes foreign2 = wrapper2.foreign; assertEquals(stuff1, foreign2.stringField); assertEquals(1, wrapperDao.refresh(wrapper2)); assertSame(foreign2, wrapper2.foreign); assertEquals(stuff1, wrapper2.foreign.stringField); // now, in the background, we change the foreign ForeignWrapper wrapper3 = wrapperDao.queryForId(wrapper.id); AllTypes foreign3 = new AllTypes(); String stuff3 = "stuff3"; foreign3.stringField = stuff3; assertEquals(1, foreignDao.create(foreign3)); wrapper3.foreign = foreign3; assertEquals(1, wrapperDao.update(wrapper3)); assertEquals(1, wrapperDao.refresh(wrapper2)); // now all of a sudden wrapper2 should not have the same foreign field assertNotSame(foreign2, wrapper2.foreign); assertNull(wrapper2.foreign.stringField); } @Test public void testMultipleForeignWrapper() throws Exception { Dao<MultipleForeignWrapper, Integer> multipleWrapperDao = createDao(MultipleForeignWrapper.class, true); Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); MultipleForeignWrapper multiWrapper = new MultipleForeignWrapper(); multiWrapper.foreign = foreign; multiWrapper.foreignWrapper = wrapper; // this sets the wrapper id assertEquals(1, multipleWrapperDao.create(multiWrapper)); MultipleForeignWrapper multiWrapper2 = multipleWrapperDao.queryForId(multiWrapper.id); assertEquals(foreign.id, multiWrapper2.foreign.id); assertNull(multiWrapper2.foreign.stringField); assertEquals(wrapper.id, multiWrapper2.foreignWrapper.id); assertNull(multiWrapper2.foreignWrapper.foreign); assertEquals(1, foreignDao.refresh(multiWrapper2.foreign)); assertEquals(stuff1, multiWrapper2.foreign.stringField); assertNull(multiWrapper2.foreignWrapper.foreign); assertEquals(1, wrapperDao.refresh(multiWrapper2.foreignWrapper)); assertEquals(foreign.id, multiWrapper2.foreignWrapper.foreign.id); assertNull(multiWrapper2.foreignWrapper.foreign.stringField); assertEquals(1, foreignDao.refresh(multiWrapper2.foreignWrapper.foreign)); assertEquals(stuff1, multiWrapper2.foreignWrapper.foreign.stringField); } @Test public void testRefreshNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); // this should be a noop assertEquals(0, fooDao.refresh(null)); } @Test public void testGetSet() throws Exception { Dao<GetSet, Integer> getSetDao = createDao(GetSet.class, true); GetSet getSet = new GetSet(); String stuff = "ewfewfewfew343u42f"; getSet.setStuff(stuff); assertEquals(1, getSetDao.create(getSet)); GetSet getSet2 = getSetDao.queryForId(getSet.id); assertEquals(stuff, getSet2.stuff); } @Test public void testQueryForFirst() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff = "ewf4334234u42f"; QueryBuilder<Foo, Integer> qb = fooDao.queryBuilder(); qb.where().eq(Foo.STUFF_FIELD_NAME, stuff); assertNull(fooDao.queryForFirst(qb.prepare())); Foo foo1 = new Foo(); foo1.stuff = stuff; assertEquals(1, fooDao.create(foo1)); // should still get foo1 Foo foo2 = fooDao.queryForFirst(qb.prepare()); assertEquals(foo1.id, foo2.id); assertEquals(stuff, foo2.stuff); // create another with same stuff Foo foo3 = new Foo(); String stuff2 = "ewf43342wefwffwefwe34u42f"; foo3.stuff = stuff2; assertEquals(1, fooDao.create(foo3)); foo2 = fooDao.queryForFirst(qb.prepare()); assertEquals(foo1.id, foo2.id); assertEquals(stuff, foo2.stuff); } @Test public void testFieldConfig() throws Exception { List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>(); fieldConfigs.add(new DatabaseFieldConfig("id", "id2", DataType.UNKNOWN, null, 0, false, false, true, null, false, null, false, null, false, null, false, null, null, false, 0, 0)); fieldConfigs.add(new DatabaseFieldConfig("stuff", "stuffy", DataType.UNKNOWN, null, 0, false, false, false, null, false, null, false, null, false, null, false, null, null, false, 0, 0)); DatabaseTableConfig<NoAnno> tableConfig = new DatabaseTableConfig<NoAnno>(NoAnno.class, "noanno", fieldConfigs); Dao<NoAnno, Integer> noAnnotaionDao = createDao(tableConfig, true); NoAnno noa = new NoAnno(); String stuff = "qpoqwpjoqwp12"; noa.stuff = stuff; assertEquals(1, noAnnotaionDao.create(noa)); NoAnno noa2 = noAnnotaionDao.queryForId(noa.id); assertEquals(noa.id, noa2.id); assertEquals(stuff, noa2.stuff); } @Test public void testFieldConfigForeign() throws Exception { List<DatabaseFieldConfig> noAnnotationsFieldConfigs = new ArrayList<DatabaseFieldConfig>(); DatabaseFieldConfig field1 = new DatabaseFieldConfig("id"); field1.setColumnName("idthingie"); field1.setGeneratedId(true); noAnnotationsFieldConfigs.add(field1); DatabaseFieldConfig field2 = new DatabaseFieldConfig("stuff"); field2.setColumnName("stuffy"); noAnnotationsFieldConfigs.add(field2); DatabaseTableConfig<NoAnno> noAnnotationsTableConfig = new DatabaseTableConfig<NoAnno>(NoAnno.class, noAnnotationsFieldConfigs); Dao<NoAnno, Integer> noAnnotationDao = createDao(noAnnotationsTableConfig, true); NoAnno noa = new NoAnno(); String stuff = "qpoqwpjoqwp12"; noa.stuff = stuff; assertEquals(1, noAnnotationDao.create(noa)); assertNotNull(noAnnotationDao.queryForId(noa.id)); List<DatabaseFieldConfig> noAnnotationsForiegnFieldConfigs = new ArrayList<DatabaseFieldConfig>(); DatabaseFieldConfig field3 = new DatabaseFieldConfig("id"); field3.setColumnName("anotherid"); field3.setGeneratedId(true); noAnnotationsForiegnFieldConfigs.add(field3); DatabaseFieldConfig field4 = new DatabaseFieldConfig("foreign"); field4.setColumnName("foreignThingie"); field4.setForeign(true); field4.setForeignTableConfig(noAnnotationsTableConfig); noAnnotationsForiegnFieldConfigs.add(field4); DatabaseTableConfig<NoAnnoFor> noAnnotationsForiegnTableConfig = new DatabaseTableConfig<NoAnnoFor>(NoAnnoFor.class, noAnnotationsForiegnFieldConfigs); Dao<NoAnnoFor, Integer> noAnnotaionForeignDao = createDao(noAnnotationsForiegnTableConfig, true); NoAnnoFor noaf = new NoAnnoFor(); noaf.foreign = noa; assertEquals(1, noAnnotaionForeignDao.create(noaf)); NoAnnoFor noaf2 = noAnnotaionForeignDao.queryForId(noaf.id); assertNotNull(noaf2); assertEquals(noaf.id, noaf2.id); assertEquals(noa.id, noaf2.foreign.id); assertNull(noaf2.foreign.stuff); assertEquals(1, noAnnotationDao.refresh(noaf2.foreign)); assertEquals(stuff, noaf2.foreign.stuff); } @Test public void testGeneratedIdNotNull() throws Exception { // we saw an error with the not null before the generated id stuff under hsqldb Dao<GeneratedIdNotNull, Integer> dao = createDao(GeneratedIdNotNull.class, true); assertEquals(1, dao.create(new GeneratedIdNotNull())); } @Test public void testBasicStuff() throws Exception { Dao<Basic, String> fooDao = createDao(Basic.class, true); String string = "s1"; Basic foo1 = new Basic(); foo1.id = string; assertEquals(1, fooDao.create(foo1)); Basic foo2 = fooDao.queryForId(string); assertTrue(fooDao.objectsEqual(foo1, foo2)); List<Basic> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertTrue(fooDao.objectsEqual(foo1, fooList.get(0))); int i = 0; for (Basic foo3 : fooDao) { assertTrue(fooDao.objectsEqual(foo1, foo3)); i++; } assertEquals(1, i); assertEquals(1, fooDao.delete(foo2)); assertNull(fooDao.queryForId(string)); fooList = fooDao.queryForAll(); assertEquals(0, fooList.size()); i = 0; for (Basic foo3 : fooDao) { assertTrue(fooDao.objectsEqual(foo1, foo3)); i++; } assertEquals(0, i); } @Test public void testMultiplePrimaryKey() throws Exception { Dao<Basic, String> fooDao = createDao(Basic.class, true); Basic foo1 = new Basic(); foo1.id = "dup"; assertEquals(1, fooDao.create(foo1)); try { fooDao.create(foo1); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testDefaultValue() throws Exception { Dao<DefaultValue, Object> defValDao = createDao(DefaultValue.class, true); DefaultValue defVal1 = new DefaultValue(); assertEquals(1, defValDao.create(defVal1)); List<DefaultValue> defValList = defValDao.queryForAll(); assertEquals(1, defValList.size()); DefaultValue defVal2 = defValList.get(0); assertEquals(DEFAULT_VALUE, (int) defVal2.intField); } @Test public void testNotNull() throws Exception { Dao<NotNull, Object> defValDao = createDao(NotNull.class, true); NotNull notNull = new NotNull(); try { defValDao.create(notNull); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testNotNullOkay() throws Exception { Dao<NotNull, Object> defValDao = createDao(NotNull.class, true); NotNull notNull = new NotNull(); notNull.notNull = "not null"; assertEquals(1, defValDao.create(notNull)); } @Test public void testGeneratedId() throws Exception { Dao<GeneratedId, Object> genIdDao = createDao(GeneratedId.class, true); GeneratedId genId = new GeneratedId(); assertEquals(0, genId.id); assertEquals(1, genIdDao.create(genId)); long id = genId.id; assertEquals(1, id); GeneratedId genId2 = genIdDao.queryForId(id); assertNotNull(genId2); assertEquals(id, genId2.id); genId = new GeneratedId(); assertEquals(0, genId.id); assertEquals(1, genIdDao.create(genId)); id = genId.id; assertEquals(2, id); genId2 = genIdDao.queryForId(id); assertNotNull(genId2); assertEquals(id, genId2.id); } @Test public void testAllTypes() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); String stringVal = "some string"; boolean boolVal = true; // we have to round this because the db may not be storing millis long millis = (System.currentTimeMillis() / 1000) * 1000; Date dateVal = new Date(millis); Date dateLongVal = new Date(millis); Date dateStringVal = new Date(millis); char charVal = 'w'; byte byteVal = 117; short shortVal = 15217; int intVal = 1023213; long longVal = 1231231231231L; float floatVal = 123.13F; double doubleVal = 1413312.1231233; OurEnum enumVal = OurEnum.FIRST; allTypes.stringField = stringVal; allTypes.booleanField = boolVal; allTypes.dateField = dateVal; allTypes.dateLongField = dateLongVal; allTypes.dateStringField = dateStringVal; allTypes.charField = charVal; allTypes.byteField = byteVal; allTypes.shortField = shortVal; allTypes.intField = intVal; allTypes.longField = longVal; allTypes.floatField = floatVal; allTypes.doubleField = doubleVal; allTypes.enumField = enumVal; allTypes.enumStringField = enumVal; allTypes.enumIntegerField = enumVal; SerialData obj = new SerialData(); String key = "key"; String value = "value"; obj.addEntry(key, value); allTypes.serialField = obj; assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); assertEquals(value, allTypesList.get(0).serialField.map.get(key)); assertEquals(1, allDao.refresh(allTypes)); // queries on all fields QueryBuilder<AllTypes, Integer> qb = allDao.queryBuilder(); checkQueryResult(allDao, qb, allTypes, AllTypes.STRING_FIELD_NAME, stringVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.BOOLEAN_FIELD_NAME, boolVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_FIELD_NAME, dateVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_LONG_FIELD_NAME, dateLongVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_STRING_FIELD_NAME, dateStringVal, true); if (!databaseType.getDatabaseName().equals("Derby")) { checkQueryResult(allDao, qb, allTypes, AllTypes.CHAR_FIELD_NAME, charVal, true); } checkQueryResult(allDao, qb, allTypes, AllTypes.BYTE_FIELD_NAME, byteVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.SHORT_FIELD_NAME, shortVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.INT_FIELD_NAME, intVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.LONG_FIELD_NAME, longVal, true); // float tested below checkQueryResult(allDao, qb, allTypes, AllTypes.DOUBLE_FIELD_NAME, doubleVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_FIELD_NAME, enumVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_STRING_FIELD_NAME, enumVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_INTEGER_FIELD_NAME, enumVal, true); } /** * This is special because comparing floats may not work as expected. */ @Test public void testAllTypesFloat() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); float floatVal = 123.13F; float floatLowVal = floatVal * 0.9F; float floatHighVal = floatVal * 1.1F; allTypes.floatField = floatVal; assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); assertEquals(1, allDao.refresh(allTypes)); // queries on all fields QueryBuilder<AllTypes, Integer> qb = allDao.queryBuilder(); // float comparisons are not exactly right so we switch to a low -> high query instead if (!checkQueryResult(allDao, qb, allTypes, AllTypes.FLOAT_FIELD_NAME, floatVal, false)) { qb.where().gt(AllTypes.FLOAT_FIELD_NAME, floatLowVal).and().lt(AllTypes.FLOAT_FIELD_NAME, floatHighVal); List<AllTypes> results = allDao.query(qb.prepare()); assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } } @Test public void testAllTypesDefault() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); } @Test public void testNumberTypes() throws Exception { Dao<NumberTypes, Integer> numberDao = createDao(NumberTypes.class, true); NumberTypes numberMins = new NumberTypes(); numberMins.byteField = Byte.MIN_VALUE; numberMins.shortField = Short.MIN_VALUE; numberMins.intField = Integer.MIN_VALUE; numberMins.longField = Long.MIN_VALUE; numberMins.floatField = -1.0e+37F; numberMins.doubleField = -1.0e+307; assertEquals(1, numberDao.create(numberMins)); NumberTypes numberMins2 = new NumberTypes(); numberMins2.byteField = Byte.MIN_VALUE; numberMins2.shortField = Short.MIN_VALUE; numberMins2.intField = Integer.MIN_VALUE; numberMins2.longField = Long.MIN_VALUE; numberMins2.floatField = 1.0e-37F; // derby couldn't take 1.0e-307 for some reason numberMins2.doubleField = 1.0e-306; assertEquals(1, numberDao.create(numberMins2)); NumberTypes numberMaxs = new NumberTypes(); numberMaxs.byteField = Byte.MAX_VALUE; numberMaxs.shortField = Short.MAX_VALUE; numberMaxs.intField = Integer.MAX_VALUE; numberMaxs.longField = Long.MAX_VALUE; numberMaxs.floatField = 1.0e+37F; numberMaxs.doubleField = 1.0e+307; assertEquals(1, numberDao.create(numberMaxs)); assertEquals(1, numberDao.refresh(numberMaxs)); List<NumberTypes> allTypesList = numberDao.queryForAll(); assertEquals(3, allTypesList.size()); assertTrue(numberDao.objectsEqual(numberMins, allTypesList.get(0))); assertTrue(numberDao.objectsEqual(numberMins2, allTypesList.get(1))); assertTrue(numberDao.objectsEqual(numberMaxs, allTypesList.get(2))); } @Test public void testStringWidthTooLong() throws Exception { if (connectionSource == null) { return; } if (!connectionSource.getDatabaseType().isVarcharFieldWidthSupported()) { return; } Dao<StringWidth, Object> stringWidthDao = createDao(StringWidth.class, true); StringWidth stringWidth = new StringWidth(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ALL_TYPES_STRING_WIDTH + 1; i++) { sb.append("c"); } String string = sb.toString(); assertTrue(string.length() > ALL_TYPES_STRING_WIDTH); stringWidth.stringField = string; try { stringWidthDao.create(stringWidth); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testStringWidthOkay() throws Exception { Dao<StringWidth, Object> stringWidthDao = createDao(StringWidth.class, true); StringWidth stringWidth = new StringWidth(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ALL_TYPES_STRING_WIDTH; i++) { sb.append("c"); } String string = sb.toString(); assertTrue(string.length() == ALL_TYPES_STRING_WIDTH); stringWidth.stringField = string; assertEquals(1, stringWidthDao.create(stringWidth)); List<StringWidth> stringWidthList = stringWidthDao.queryForAll(); assertEquals(1, stringWidthList.size()); assertTrue(stringWidthDao.objectsEqual(stringWidth, stringWidthList.get(0))); } @Test public void testCreateReserverdTable() throws Exception { Dao<Create, String> whereDao = createDao(Create.class, true); String id = "from-string"; Create where = new Create(); where.id = id; assertEquals(1, whereDao.create(where)); Create where2 = whereDao.queryForId(id); assertEquals(id, where2.id); assertEquals(1, whereDao.delete(where2)); assertNull(whereDao.queryForId(id)); } @Test public void testCreateReserverdFields() throws Exception { Dao<ReservedField, Object> reservedDao = createDao(ReservedField.class, true); String from = "from-string"; ReservedField res = new ReservedField(); res.from = from; assertEquals(1, reservedDao.create(res)); int id = res.select; ReservedField res2 = reservedDao.queryForId(id); assertNotNull(res2); assertEquals(id, res2.select); String group = "group-string"; for (ReservedField reserved : reservedDao) { assertEquals(from, reserved.from); reserved.group = group; reservedDao.update(reserved); } Iterator<ReservedField> reservedIterator = reservedDao.iterator(); while (reservedIterator.hasNext()) { ReservedField reserved = reservedIterator.next(); assertEquals(from, reserved.from); assertEquals(group, reserved.group); reservedIterator.remove(); } assertEquals(0, reservedDao.queryForAll().size()); } @Test public void testEscapeCharInField() throws Exception { if (connectionSource == null) { return; } StringBuilder sb = new StringBuilder(); String word = "foo"; connectionSource.getDatabaseType().appendEscapedWord(sb, word); String escaped = sb.toString(); int index = escaped.indexOf(word); String escapeString = escaped.substring(0, index); Dao<Basic, String> fooDao = createDao(Basic.class, true); Basic foo1 = new Basic(); String id = word + escapeString + word; foo1.id = id; assertEquals(1, fooDao.create(foo1)); Basic foo2 = fooDao.queryForId(id); assertNotNull(foo2); assertEquals(id, foo2.id); } @Test public void testGeneratedIdCapital() throws Exception { createDao(GeneratedColumnCapital.class, true); } @Test public void testObject() throws Exception { Dao<ObjectHolder, Integer> objDao = createDao(ObjectHolder.class, true); ObjectHolder foo1 = new ObjectHolder(); foo1.obj = new SerialData(); String key = "key2"; String value = "val2"; foo1.obj.addEntry(key, value); String strObj = "fjpwefefwpjoefwjpojopfew"; foo1.strObj = strObj; assertEquals(1, objDao.create(foo1)); ObjectHolder foo2 = objDao.queryForId(foo1.id); assertTrue(objDao.objectsEqual(foo1, foo2)); } @Test public void testNotSerializable() throws Exception { try { createDao(NotSerializable.class, true); fail("expected exception"); } catch (IllegalArgumentException e) { // expected } } @Test public void testStringEnum() throws Exception { Dao<LocalEnumString, Object> fooDao = createDao(LocalEnumString.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumString foo = new LocalEnumString(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); List<LocalEnumString> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(ourEnum, fooList.get(0).ourEnum); } @Test public void testUnknownStringEnum() throws Exception { Dao<LocalEnumString, Object> fooDao = createDao(LocalEnumString.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumString foo = new LocalEnumString(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumString2, Object> foo2Dao = createDao(LocalEnumString2.class, false); try { foo2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testIntEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); List<LocalEnumInt> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(ourEnum, fooList.get(0).ourEnum); } @Test public void testUnknownIntEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumInt2, Object> foo2Dao = createDao(LocalEnumInt2.class, false); try { foo2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testUnknownIntUnknownValEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumInt3, Object> foo2Dao = createDao(LocalEnumInt3.class, false); List<LocalEnumInt3> fooList = foo2Dao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(OurEnum2.FIRST, fooList.get(0).ourEnum); } @Test public void testNullHandling() throws Exception { Dao<AllObjectTypes, Object> allDao = createDao(AllObjectTypes.class, true); AllObjectTypes all = new AllObjectTypes(); assertEquals(1, allDao.create(all)); List<AllObjectTypes> allList = allDao.queryForAll(); assertEquals(1, allList.size()); assertTrue(allDao.objectsEqual(all, allList.get(0))); } @Test public void testObjectNotNullHandling() throws Exception { Dao<AllObjectTypes, Object> allDao = createDao(AllObjectTypes.class, true); AllObjectTypes all = new AllObjectTypes(); all.stringField = "foo"; all.booleanField = false; Date dateValue = new Date(1279649192000L); all.dateField = dateValue; all.byteField = 0; all.shortField = 0; all.intField = 0; all.longField = 0L; all.floatField = 0F; all.doubleField = 0D; all.objectField = new SerialData(); all.ourEnum = OurEnum.FIRST; assertEquals(1, allDao.create(all)); assertEquals(1, allDao.refresh(all)); List<AllObjectTypes> allList = allDao.queryForAll(); assertEquals(1, allList.size()); assertTrue(allDao.objectsEqual(all, allList.get(0))); } @Test public void testDefaultValueHandling() throws Exception { Dao<AllTypesDefault, Object> allDao = createDao(AllTypesDefault.class, true); AllTypesDefault all = new AllTypesDefault(); assertEquals(1, allDao.create(all)); assertEquals(1, allDao.refresh(all)); List<AllTypesDefault> allList = allDao.queryForAll(); assertEquals(1, allList.size()); all.stringField = DEFAULT_STRING_VALUE; DateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); all.dateField = defaultDateFormat.parse(DEFAULT_DATE_VALUE); all.dateLongField = new Date(Long.parseLong(DEFAULT_DATE_LONG_VALUE)); DateFormat defaultDateStringFormat = new SimpleDateFormat(DEFAULT_DATE_STRING_FORMAT); all.dateStringField = defaultDateStringFormat.parse(DEFAULT_DATE_STRING_VALUE); all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.byteField = Byte.parseByte(DEFAULT_BYTE_VALUE); all.byteObj = Byte.parseByte(DEFAULT_BYTE_VALUE); all.shortField = Short.parseShort(DEFAULT_SHORT_VALUE); all.shortObj = Short.parseShort(DEFAULT_SHORT_VALUE); all.intField = Integer.parseInt(DEFAULT_INT_VALUE); all.intObj = Integer.parseInt(DEFAULT_INT_VALUE); all.longField = Long.parseLong(DEFAULT_LONG_VALUE); all.longObj = Long.parseLong(DEFAULT_LONG_VALUE); all.floatField = Float.parseFloat(DEFAULT_FLOAT_VALUE); all.floatObj = Float.parseFloat(DEFAULT_FLOAT_VALUE); all.doubleField = Double.parseDouble(DEFAULT_DOUBLE_VALUE); all.doubleObj = Double.parseDouble(DEFAULT_DOUBLE_VALUE); all.ourEnum = OurEnum.valueOf(DEFAULT_ENUM_VALUE); assertFalse(allDao.objectsEqual(all, allList.get(0))); } @Test public void testBooleanDefaultValueHandling() throws Exception { Dao<BooleanDefault, Object> allDao = createDao(BooleanDefault.class, true); BooleanDefault all = new BooleanDefault(); assertEquals(1, allDao.create(all)); List<BooleanDefault> allList = allDao.queryForAll(); assertEquals(1, allList.size()); all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); assertFalse(allDao.objectsEqual(all, allList.get(0))); } @Test public void testNullUnPersistToBooleanPrimitive() throws Exception { Dao<NullBoolean1, Object> null1Dao = createDao(NullBoolean1.class, true); NullBoolean1 nullThing = new NullBoolean1(); assertEquals(1, null1Dao.create(nullThing)); Dao<NullBoolean2, Object> null2Dao = createDao(NullBoolean2.class, false); try { null2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testNullUnPersistToIntPrimitive() throws Exception { Dao<NullInt1, Object> null1Dao = createDao(NullInt1.class, true); NullInt1 nullThing = new NullInt1(); assertEquals(1, null1Dao.create(nullThing)); Dao<NullInt2, Object> null2Dao = createDao(NullInt2.class, false); try { null2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testQueryRawStrings() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; foo.stuff = stuff; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<String[]> results = fooDao.queryRaw(queryString); assertEquals(0, results.getResults().size()); assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); boolean gotId = false; boolean gotStuff = false; boolean gotVal = false; // all this crap is here because of android column order for (int colC = 0; colC < 3; colC++) { if (colNames[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { gotId = true; } else if (colNames[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { gotStuff = true; } else if (colNames[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { gotVal = true; } } assertTrue(gotId); assertTrue(gotStuff); assertTrue(gotVal); List<String[]> resultList = results.getResults(); assertEquals(1, resultList.size()); String[] result = resultList.get(0); assertEquals(colN, result.length); for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (results.getColumnNames()[colC] == "id") { assertEquals(Integer.toString(foo.id), result[colC]); } if (results.getColumnNames()[colC] == "stuff") { assertEquals(stuff, result[1]); } } } @Test public void testQueryRawStringsIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; int val = 12321411; foo.stuff = stuff; foo.val = val; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<String[]> results = fooDao.queryRaw(queryString); CloseableIterator<String[]> iterator = results.closeableIterator(); try { assertFalse(iterator.hasNext()); } finally { iterator.close(); } assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); String[] result = iterator.next(); assertEquals(colN, result.length); boolean foundId = false; boolean foundStuff = false; boolean foundVal = false; for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { assertEquals(Integer.toString(foo.id), result[colC]); foundId = true; } if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { assertEquals(stuff, result[colC]); foundStuff = true; } if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { assertEquals(Integer.toString(val), result[colC]); foundVal = true; } } assertTrue(foundId); assertTrue(foundStuff); assertTrue(foundVal); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } @Test public void testQueryRawMappedIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); final Foo foo = new Foo(); String stuff = "eprjpejrre"; foo.stuff = stuff; String queryString = buildFooQueryAllString(fooDao); Mapper mapper = new Mapper(); GenericRawResults<Foo> rawResults = fooDao.queryRaw(queryString, mapper); assertEquals(0, rawResults.getResults().size()); assertEquals(1, fooDao.create(foo)); rawResults = fooDao.queryRaw(queryString, mapper); Iterator<Foo> iterator = rawResults.iterator(); assertTrue(iterator.hasNext()); Foo foo2 = iterator.next(); assertEquals(foo.id, foo2.id); assertEquals(foo.stuff, foo2.stuff); assertEquals(foo.val, foo2.val); assertFalse(iterator.hasNext()); } @Test public void testQueryRawObjectsIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; int val = 213123; foo.stuff = stuff; foo.val = val; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<Object[]> results = fooDao.queryRaw(queryString, new DataType[] { DataType.INTEGER, DataType.STRING, DataType.INTEGER }); CloseableIterator<Object[]> iterator = results.closeableIterator(); try { assertFalse(iterator.hasNext()); } finally { iterator.close(); } assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString, new DataType[] { DataType.INTEGER, DataType.STRING, DataType.INTEGER }); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); Object[] result = iterator.next(); assertEquals(colN, result.length); String[] columnNames = results.getColumnNames(); boolean foundId = false; boolean foundStuff = false; boolean foundVal = false; for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (columnNames[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { assertEquals(foo.id, result[colC]); foundId = true; } if (columnNames[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { assertEquals(stuff, result[colC]); foundStuff = true; } if (columnNames[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { assertEquals(val, result[colC]); foundVal = true; } } assertTrue(foundId); assertTrue(foundStuff); assertTrue(foundVal); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } @Test public void testNotNullDefault() throws Exception { Dao<NotNullDefault, Object> dao = createDao(NotNullDefault.class, true); NotNullDefault notNullDefault = new NotNullDefault(); assertEquals(1, dao.create(notNullDefault)); } @Test public void testStringDefault() throws Exception { Dao<StringDefalt, Object> dao = createDao(StringDefalt.class, true); StringDefalt foo = new StringDefalt(); assertEquals(1, dao.create(foo)); } @Test public void testDateUpdate() throws Exception { Dao<LocalDate, Object> dao = createDao(LocalDate.class, true); LocalDate localDate = new LocalDate(); // note: this does not have milliseconds Date date = new Date(2131232000); localDate.date = date; assertEquals(1, dao.create(localDate)); List<LocalDate> allDates = dao.queryForAll(); assertEquals(1, allDates.size()); assertEquals(date, allDates.get(0).date); // now we update it assertEquals(1, dao.update(localDate)); allDates = dao.queryForAll(); assertEquals(1, allDates.size()); assertEquals(date, allDates.get(0).date); // now we set it to null localDate.date = null; // now we update it assertEquals(1, dao.update(localDate)); allDates = dao.queryForAll(); assertEquals(1, allDates.size()); // we should get null back and not some auto generated field assertNull(allDates.get(0).date); } @Test public void testDateRefresh() throws Exception { Dao<LocalDate, Object> dao = createDao(LocalDate.class, true); LocalDate localDate = new LocalDate(); // note: this does not have milliseconds Date date = new Date(2131232000); localDate.date = date; assertEquals(1, dao.create(localDate)); assertEquals(1, dao.refresh(localDate)); } @Test public void testSpringBadWiring() throws Exception { BaseDaoImpl<String, String> daoSupport = new BaseDaoImpl<String, String>(String.class) { }; try { daoSupport.initialize(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } @Test public void testUnique() throws Exception { Dao<Unique, Long> dao = createDao(Unique.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; Unique unique = new Unique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new Unique(); unique.stuff = stuff; assertEquals(1, dao.create(unique)); unique = new Unique(); unique.uniqueStuff = uniqueStuff; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testDoubleUnique() throws Exception { Dao<DoubleUnique, Long> dao = createDao(DoubleUnique.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; DoubleUnique unique = new DoubleUnique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new DoubleUnique(); unique.stuff = stuff; try { // either 1st field can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } unique = new DoubleUnique(); unique.uniqueStuff = uniqueStuff; try { // nor 2nd field can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } unique = new DoubleUnique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; try { // nor both fields can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testDoubleUniqueCombo() throws Exception { Dao<DoubleUniqueCombo, Long> dao = createDao(DoubleUniqueCombo.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; DoubleUniqueCombo unique = new DoubleUniqueCombo(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new DoubleUniqueCombo(); unique.stuff = stuff; assertEquals(1, dao.create(unique)); unique = new DoubleUniqueCombo(); unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); unique = new DoubleUniqueCombo(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testUniqueAndUniqueCombo() throws Exception { Dao<UniqueAndUniqueCombo, Long> dao = createDao(UniqueAndUniqueCombo.class, true); String unique1 = "unique but not combo"; String combo1 = "combo unique"; String combo2 = "another combo unique"; UniqueAndUniqueCombo unique = new UniqueAndUniqueCombo(); unique.unique1 = unique1; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new UniqueAndUniqueCombo(); unique.unique1 = unique1; try { dao.create(unique); fail("this should throw"); } catch (Exception e) { // expected } unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = combo2; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = unique1; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = unique1; unique.combo2 = combo2; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = combo2; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testForeignQuery() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; Date date = new Date(); foreign.dateField = date; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); QueryBuilder<ForeignWrapper, Integer> qb = wrapperDao.queryBuilder(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, foreign.id); List<ForeignWrapper> results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * now look it up not by foreign.id but by foreign which should extract the id automagically */ qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, foreign); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * Now let's try the same thing but with a SelectArg */ SelectArg selectArg = new SelectArg(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, selectArg); selectArg.setValue(foreign.id); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * Now let's try the same thing but with a SelectArg with foreign value, not foreign.id */ selectArg = new SelectArg(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, selectArg); selectArg.setValue(foreign); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); } @Test public void testPrepareStatementUpdateValueString() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "dqedqdq"; foo.stuff = stuff; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.STUFF_FIELD_NAME, stuff); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String newStuff = "fepojefpjo"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, newStuff); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.query(stmtb.prepare()); assertEquals(0, results.size()); } @Test public void testInSubQuery() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Basic, String> basicDao = createDao(Basic.class, true); Basic basic1 = new Basic(); String string1 = "ewpofjewgprgrg"; basic1.id = string1; assertEquals(1, basicDao.create(basic1)); Basic basic2 = new Basic(); String string2 = "e2432423432wpofjewgprgrg"; basic2.id = string2; assertEquals(1, basicDao.create(basic2)); Foo foo1 = new Foo(); foo1.stuff = basic1.id; Foo foo2 = new Foo(); foo2.stuff = basic2.id; Foo foo3 = new Foo(); String string3 = "neither of the others"; foo3.stuff = string3; int num1 = 7; for (int i = 0; i < num1; i++) { assertEquals(1, fooDao.create(foo1)); } int num2 = 17; for (int i = 0; i < num2; i++) { assertEquals(1, fooDao.create(foo2)); } int num3 = 29; long maxId = 0; for (int i = 0; i < num3; i++) { assertEquals(1, fooDao.create(foo3)); if (foo3.id > maxId) { maxId = foo3.id; } } QueryBuilder<Basic, String> bqb = basicDao.queryBuilder(); bqb.selectColumns(Basic.ID_FIELD); // string1 bqb.where().eq(Basic.ID_FIELD, string1); List<Foo> results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1, results.size()); // string2 bqb.where().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num2, results.size()); // ! string2 with not().in(...) bqb.where().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().not().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num3, results.size()); // string3 which there should be none bqb.where().eq(Basic.ID_FIELD, string3); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(0, results.size()); // string1 OR string2 bqb.where().eq(Basic.ID_FIELD, string1).or().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num2, results.size()); // all strings IN bqb.where().in(Basic.ID_FIELD, string1, string2, string3); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num2, results.size()); // string1 AND string2 which there should be none bqb.where().eq(Basic.ID_FIELD, string1).and().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(0, results.size()); } @Test public void testInSubQuerySelectArgs() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Basic, String> basicDao = createDao(Basic.class, true); Basic basic1 = new Basic(); String string1 = "ewpofjewgprgrg"; basic1.id = string1; assertEquals(1, basicDao.create(basic1)); Basic basic2 = new Basic(); String string2 = "e2432423432wpofjewgprgrg"; basic2.id = string2; assertEquals(1, basicDao.create(basic2)); Foo foo1 = new Foo(); foo1.stuff = basic1.id; Foo foo2 = new Foo(); foo2.stuff = basic2.id; int num1 = 7; for (int i = 0; i < num1; i++) { assertEquals(1, fooDao.create(foo1)); } int num2 = 17; long maxId = 0; for (int i = 0; i < num2; i++) { assertEquals(1, fooDao.create(foo2)); if (foo2.id > maxId) { maxId = foo2.id; } } // using seletArgs SelectArg arg1 = new SelectArg(); SelectArg arg2 = new SelectArg(); QueryBuilder<Basic, String> bqb = basicDao.queryBuilder(); bqb.selectColumns(Basic.ID_FIELD); bqb.where().eq(Basic.ID_FIELD, arg1); PreparedQuery<Foo> preparedQuery = fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).and().lt(Foo.ID_FIELD_NAME, arg2).prepare(); arg1.setValue(string1); // this should get none arg2.setValue(0); List<Foo> results = fooDao.query(preparedQuery); assertEquals(0, results.size()); } @Test public void testPrepareStatementUpdateValueNumber() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); foo.val = 123213; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.ID_FIELD_NAME, foo.id); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); updateb.updateColumnValue(Foo.VAL_FIELD_NAME, foo.val + 1); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); assertEquals(foo.val + 1, results.get(0).val); } @Test public void testPrepareStatementUpdateValueExpression() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); foo.val = 123213; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.ID_FIELD_NAME, foo.id); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String stuff = "deopdjq"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, stuff); StringBuilder sb = new StringBuilder(); updateb.escapeColumnName(sb, Foo.VAL_FIELD_NAME); sb.append("+ 1"); updateb.updateColumnExpression(Foo.VAL_FIELD_NAME, sb.toString()); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.queryForAll(); assertEquals(1, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(foo.val + 1, results.get(0).val); } @Test public void testPrepareStatementUpdateValueWhere() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 78582351; assertEquals(1, fooDao.create(foo1)); Foo foo2 = new Foo(); String stuff = "eopqjdepodje"; foo2.stuff = stuff; foo2.val = 123344131; assertEquals(1, fooDao.create(foo2)); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String newStuff = "deopdjq"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, newStuff); StringBuilder sb = new StringBuilder(); updateb.escapeColumnName(sb, Foo.VAL_FIELD_NAME); sb.append("+ 1"); updateb.updateColumnExpression(Foo.VAL_FIELD_NAME, sb.toString()); updateb.where().eq(Foo.ID_FIELD_NAME, foo2.id); assertEquals(1, fooDao.update(updateb.prepare())); List<Foo> results = fooDao.queryForAll(); assertEquals(2, results.size()); Foo foo = results.get(0); assertEquals(foo1.id, foo.id); assertEquals(foo1.val, foo.val); assertNull(foo.stuff); foo = results.get(1); assertEquals(foo2.id, foo.id); assertEquals(foo2.val + 1, foo.val); assertEquals(newStuff, foo.stuff); } @Test public void testStringAsId() throws Exception { checkTypeAsId(StringId.class, "foo", "bar"); } @Test public void testLongStringAsId() throws Exception { try { createDao(LongStringId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testBooleanAsId() throws Exception { try { createDao(BooleanId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testBooleanObjAsId() throws Exception { try { createDao(BooleanObjId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testDateAsId() throws Exception { // no milliseconds checkTypeAsId(DateId.class, new Date(1232312313000L), new Date(1232312783000L)); } @Test public void testDateLongAsId() throws Exception { // no milliseconds checkTypeAsId(DateLongId.class, new Date(1232312313000L), new Date(1232312783000L)); } @Test public void testDateStringAsId() throws Exception { // no milliseconds checkTypeAsId(DateStringId.class, new Date(1232312313000L), new Date(1232312783000L)); } @Test public void testByteAsId() throws Exception { checkTypeAsId(ByteId.class, (byte) 1, (byte) 2); } @Test public void testByteObjAsId() throws Exception { checkTypeAsId(ByteObjId.class, (byte) 1, (byte) 2); } @Test public void testShortAsId() throws Exception { checkTypeAsId(ShortId.class, (short) 1, (short) 2); } @Test public void testShortObjAsId() throws Exception { checkTypeAsId(ShortObjId.class, (short) 1, (short) 2); } @Test public void testIntAsId() throws Exception { checkTypeAsId(IntId.class, (int) 1, (int) 2); } @Test public void testIntObjAsId() throws Exception { checkTypeAsId(IntObjId.class, (int) 1, (int) 2); } @Test public void testLongAsId() throws Exception { checkTypeAsId(LongId.class, (long) 1, (long) 2); } @Test public void testLongObjAsId() throws Exception { checkTypeAsId(LongObjId.class, (long) 1, (long) 2); } @Test public void testFloatAsId() throws Exception { checkTypeAsId(FloatId.class, (float) 1, (float) 2); } @Test public void testFloatObjAsId() throws Exception { checkTypeAsId(FloatObjId.class, (float) 1, (float) 2); } @Test public void testDoubleAsId() throws Exception { checkTypeAsId(DoubleId.class, (double) 1, (double) 2); } @Test public void testDoubleObjAsId() throws Exception { checkTypeAsId(DoubleObjId.class, (double) 1, (double) 2); } @Test public void testEnumAsId() throws Exception { checkTypeAsId(EnumId.class, OurEnum.SECOND, OurEnum.FIRST); } @Test public void testEnumStringAsId() throws Exception { checkTypeAsId(EnumStringId.class, OurEnum.SECOND, OurEnum.FIRST); } @Test public void testEnumIntegerAsId() throws Exception { checkTypeAsId(EnumIntegerId.class, OurEnum.SECOND, OurEnum.FIRST); } @Test public void testSerializableAsId() throws Exception { try { createDao(SerializableId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testRecursiveForeign() throws Exception { Dao<Recursive, Integer> recursiveDao = createDao(Recursive.class, true); Recursive recursive1 = new Recursive(); Recursive recursive2 = new Recursive(); recursive2.foreign = recursive1; assertEquals(recursiveDao.create(recursive1), 1); assertEquals(recursiveDao.create(recursive2), 1); Recursive recursive3 = recursiveDao.queryForId(recursive2.id); assertNotNull(recursive3); assertEquals(recursive1.id, recursive3.foreign.id); } @Test public void testSerializableWhere() throws Exception { Dao<AllTypes, Object> allDao = createDao(AllTypes.class, true); try { // can't query for a serial field allDao.queryBuilder().where().eq(AllTypes.SERIAL_FIELD_NAME, new SelectArg()); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testSerializedBytes() throws Exception { Dao<SerializedBytes, Integer> dao = createDao(SerializedBytes.class, true); SerializedBytes serial = new SerializedBytes(); serial.bytes = new byte[] { 1, 25, 3, 124, 10 }; assertEquals(1, dao.create(serial)); SerializedBytes raw2 = dao.queryForId(serial.id); assertNotNull(raw2); assertEquals(serial.id, raw2.id); assertTrue(Arrays.equals(serial.bytes, raw2.bytes)); } @Test public void testByteArray() throws Exception { Dao<ByteArray, Integer> dao = createDao(ByteArray.class, true); ByteArray foo = new ByteArray(); foo.bytes = new byte[] { 17, 25, 3, 124, 0, 127, 10 }; assertEquals(1, dao.create(foo)); ByteArray raw2 = dao.queryForId(foo.id); assertNotNull(raw2); assertEquals(foo.id, raw2.id); assertTrue(Arrays.equals(foo.bytes, raw2.bytes)); } @Test public void testSuperClassAnnotations() throws Exception { Dao<Sub, Integer> dao = createDao(Sub.class, true); Sub sub1 = new Sub(); String stuff = "doepqjdpqdq"; sub1.stuff = stuff; assertEquals(1, dao.create(sub1)); Sub sub2 = dao.queryForId(sub1.id); assertNotNull(sub2); assertEquals(sub1.id, sub2.id); assertEquals(sub1.stuff, sub2.stuff); } @Test public void testFieldIndex() throws Exception { Dao<Index, Integer> dao = createDao(Index.class, true); Index index1 = new Index(); String stuff = "doepqjdpqdq"; index1.stuff = stuff; assertEquals(1, dao.create(index1)); Index index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); // this should work assertEquals(1, dao.create(index1)); PreparedQuery<Index> query = dao.queryBuilder().where().eq("stuff", index1.stuff).prepare(); List<Index> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(stuff, results.get(1).stuff); } @Test public void testFieldIndexColumnName() throws Exception { Dao<IndexColumnName, Integer> dao = createDao(IndexColumnName.class, true); IndexColumnName index1 = new IndexColumnName(); String stuff = "doepqjdpqdq"; index1.stuff = stuff; assertEquals(1, dao.create(index1)); IndexColumnName index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); // this should work assertEquals(1, dao.create(index1)); PreparedQuery<IndexColumnName> query = dao.queryBuilder().where().eq(IndexColumnName.STUFF_COLUMN_NAME, index1.stuff).prepare(); List<IndexColumnName> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(stuff, results.get(1).stuff); } @Test public void testFieldUniqueIndex() throws Exception { Dao<UniqueIndex, Integer> dao = createDao(UniqueIndex.class, true); UniqueIndex index1 = new UniqueIndex(); String stuff1 = "doepqjdpqdq"; index1.stuff = stuff1; assertEquals(1, dao.create(index1)); UniqueIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff1, index2.stuff); try { dao.create(index1); fail("This should have thrown"); } catch (SQLException e) { // expected } String stuff2 = "fewofwgwgwee"; index1.stuff = stuff2; assertEquals(1, dao.create(index1)); PreparedQuery<UniqueIndex> query = dao.queryBuilder().where().eq("stuff", stuff1).prepare(); List<UniqueIndex> results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff1, results.get(0).stuff); query = dao.queryBuilder().where().eq("stuff", stuff2).prepare(); results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff2, results.get(0).stuff); } @Test public void testComboFieldIndex() throws Exception { Dao<ComboIndex, Integer> dao = createDao(ComboIndex.class, true); ComboIndex index1 = new ComboIndex(); String stuff = "doepqjdpqdq"; long junk1 = 131234124213213L; index1.stuff = stuff; index1.junk = junk1; assertEquals(1, dao.create(index1)); ComboIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); assertEquals(junk1, index2.junk); assertEquals(1, dao.create(index1)); PreparedQuery<ComboIndex> query = dao.queryBuilder().where().eq("stuff", index1.stuff).prepare(); List<ComboIndex> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(junk1, results.get(0).junk); assertEquals(stuff, results.get(1).stuff); assertEquals(junk1, results.get(1).junk); } @Test public void testComboUniqueFieldIndex() throws Exception { Dao<ComboUniqueIndex, Integer> dao = createDao(ComboUniqueIndex.class, true); ComboUniqueIndex index1 = new ComboUniqueIndex(); String stuff1 = "doepqjdpqdq"; long junk = 131234124213213L; index1.stuff = stuff1; index1.junk = junk; assertEquals(1, dao.create(index1)); ComboUniqueIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(index1.stuff, index2.stuff); assertEquals(index1.junk, index2.junk); try { dao.create(index1); fail("This should have thrown"); } catch (SQLException e) { // expected } String stuff2 = "fpeowjfewpf"; index1.stuff = stuff2; // same junk assertEquals(1, dao.create(index1)); PreparedQuery<ComboUniqueIndex> query = dao.queryBuilder().where().eq("stuff", stuff1).prepare(); List<ComboUniqueIndex> results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff1, results.get(0).stuff); assertEquals(junk, results.get(0).junk); query = dao.queryBuilder().where().eq("stuff", stuff2).prepare(); results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff2, results.get(0).stuff); assertEquals(junk, results.get(0).junk); } @Test public void testLongVarChar() throws Exception { Dao<LongVarChar, Integer> dao = createDao(LongVarChar.class, true); LongVarChar lvc = new LongVarChar(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10240; i++) { sb.append("."); } String stuff = sb.toString(); lvc.stuff = stuff; assertEquals(1, dao.create(lvc)); LongVarChar lvc2 = dao.queryForId(lvc.id); assertNotNull(lvc2); assertEquals(stuff, lvc2.stuff); } @Test public void testTableExists() throws Exception { if (!isTableExistsWorks()) { return; } Dao<Foo, Integer> dao = createDao(Foo.class, false); assertFalse(dao.isTableExists()); TableUtils.createTable(connectionSource, Foo.class); assertTrue(dao.isTableExists()); TableUtils.dropTable(connectionSource, Foo.class, false); assertFalse(dao.isTableExists()); } @Test public void testRaw() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo = new Foo(); int val = 131265312; foo.val = val; assertEquals(1, dao.create(foo)); StringBuilder sb = new StringBuilder(); databaseType.appendEscapedEntityName(sb, Foo.VAL_FIELD_NAME); String fieldName = sb.toString(); QueryBuilder<Foo, Integer> qb = dao.queryBuilder(); qb.where().eq(Foo.ID_FIELD_NAME, foo.id).and().raw(fieldName + " = " + val); assertEquals(1, dao.query(qb.prepare()).size()); qb.where().eq(Foo.ID_FIELD_NAME, foo.id).and().raw(fieldName + " != " + val); assertEquals(0, dao.query(qb.prepare()).size()); } @Test public void testUuidInsertQuery() throws Exception { Dao<UuidGeneratedId, UUID> dao = createDao(UuidGeneratedId.class, true); UuidGeneratedId uuid1 = new UuidGeneratedId(); String stuff1 = "fopewfjefjwgw"; uuid1.stuff = stuff1; assertNull(uuid1.id); assertEquals(1, dao.create(uuid1)); assertNotNull(uuid1.id); UuidGeneratedId uuid2 = new UuidGeneratedId(); String stuff2 = "fopefewjfepowfjefjwgw"; uuid2.stuff = stuff2; assertNull(uuid2.id); assertEquals(1, dao.create(uuid2)); assertNotNull(uuid2.id); assertFalse(uuid1.id.equals(uuid2.id)); List<UuidGeneratedId> uuids = dao.queryForAll(); assertEquals(2, uuids.size()); UuidGeneratedId uuid3 = dao.queryForId(uuid1.id); assertEquals(stuff1, uuid3.stuff); uuid3 = dao.queryForId(uuid2.id); assertEquals(stuff2, uuid3.stuff); } @Test public void testBaseDaoEnabled() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(dao); assertEquals(1, one.create()); } @Test public void testBaseDaoEnabledForeign() throws Exception { Dao<One, Integer> oneDao = createDao(One.class, true); Dao<ForeignDaoEnabled, Integer> foreignDao = createDao(ForeignDaoEnabled.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(oneDao); assertEquals(1, one.create()); ForeignDaoEnabled foreign = new ForeignDaoEnabled(); foreign.one = one; foreign.setDao(foreignDao); assertEquals(1, foreign.create()); ForeignDaoEnabled foreign2 = foreignDao.queryForId(foreign.id); assertNotNull(foreign2); assertEquals(one.id, foreign2.one.id); assertNull(foreign2.one.stuff); assertEquals(1, foreign2.one.refresh()); assertEquals(stuff, foreign2.one.stuff); } @Test public void testBasicEagerCollection() throws Exception { Dao<EagerAccount, Integer> accountDao = createDao(EagerAccount.class, true); Dao<EagerOrder, Integer> orderDao = createDao(EagerOrder.class, true); EagerAccount account = new EagerAccount(); String name = "fwepfjewfew"; account.name = name; assertEquals(1, accountDao.create(account)); EagerOrder order1 = new EagerOrder(); int val1 = 13123441; order1.val = val1; order1.account = account; assertEquals(1, orderDao.create(order1)); EagerOrder order2 = new EagerOrder(); int val2 = 113787097; order2.val = val2; order2.account = account; assertEquals(1, orderDao.create(order2)); EagerAccount account2 = accountDao.queryForId(account.id); assertEquals(name, account2.name); assertNotNull(account2.orders); int orderC = 0; for (EagerOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; } } assertEquals(2, orderC); // insert it via the collection EagerOrder order3 = new EagerOrder(); int val3 = 76557654; order3.val = val3; order3.account = account; account2.orders.add(order3); // the size should change immediately assertEquals(3, account2.orders.size()); // now insert it behind the collections back EagerOrder order4 = new EagerOrder(); int val4 = 1123587097; order4.val = val4; order4.account = account; assertEquals(1, orderDao.create(order4)); // account2's collection should not have changed assertEquals(3, account2.orders.size()); // now we refresh the collection assertEquals(1, accountDao.refresh(account2)); assertEquals(name, account2.name); assertNotNull(account2.orders); orderC = 0; for (EagerOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; case 4 : assertEquals(val4, order.val); break; } } assertEquals(4, orderC); } @Test public void testBasicLazyCollection() throws Exception { Dao<LazyAccount, Integer> accountDao = createDao(LazyAccount.class, true); Dao<LazyOrder, Integer> orderDao = createDao(LazyOrder.class, true); LazyAccount account = new LazyAccount(); String name = "fwepfjewfew"; account.name = name; assertEquals(1, accountDao.create(account)); LazyOrder order1 = new LazyOrder(); int val1 = 13123441; order1.val = val1; order1.account = account; assertEquals(1, orderDao.create(order1)); LazyOrder order2 = new LazyOrder(); int val2 = 113787097; order2.val = val2; order2.account = account; assertEquals(1, orderDao.create(order2)); LazyAccount account2 = accountDao.queryForId(account.id); assertEquals(name, account2.name); assertNotNull(account2.orders); int orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; } } assertEquals(2, orderC); // insert it via the collection LazyOrder order3 = new LazyOrder(); int val3 = 76557654; order3.val = val3; order3.account = account; account2.orders.add(order3); orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; } } assertEquals(3, orderC); // now insert it behind the collections back LazyOrder order4 = new LazyOrder(); int val4 = 1123587097; order4.val = val4; order4.account = account; assertEquals(1, orderDao.create(order4)); // without refreshing we should see the new order orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; case 4 : assertEquals(val4, order.val); break; } } assertEquals(4, orderC); } @SuppressWarnings("unchecked") @Test public void testUseOfAndMany() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id)); List<Foo> results = where.query(); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); // this should match none where.clear(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id), where.eq(Foo.ID_FIELD_NAME, notId)); results = where.query(); assertEquals(0, results.size()); } @Test @SuppressWarnings("unchecked") public void testUseOfAndInt() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id)); List<Foo> results = where.query(); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); // this should match none where.clear(); where.eq(Foo.VAL_FIELD_NAME, val); where.eq(Foo.ID_FIELD_NAME, id); where.eq(Foo.ID_FIELD_NAME, notId); where.and(3); results = where.query(); assertEquals(0, results.size()); } @SuppressWarnings("unchecked") @Test public void testUseOfOrMany() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.or(where.eq(Foo.ID_FIELD_NAME, id), where.eq(Foo.ID_FIELD_NAME, notId), where.eq(Foo.VAL_FIELD_NAME, val + 1), where.eq(Foo.VAL_FIELD_NAME, val + 1)); List<Foo> results = where.query(); assertEquals(2, results.size()); assertEquals(id, results.get(0).id); assertEquals(notId, results.get(1).id); } @Test public void testUseOfOrInt() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.eq(Foo.ID_FIELD_NAME, id); where.eq(Foo.ID_FIELD_NAME, notId); where.eq(Foo.VAL_FIELD_NAME, val + 1); where.eq(Foo.VAL_FIELD_NAME, val + 1); where.or(4); List<Foo> results = where.query(); assertEquals(2, results.size()); assertEquals(id, results.get(0).id); assertEquals(notId, results.get(1).id); } @Test public void testQueryForMatching() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Foo match = new Foo(); match.val = val; List<Foo> results = dao.queryForMatching(match); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); match = new Foo(); match.id = notId; match.val = val; results = dao.queryForMatching(match); assertEquals(0, results.size()); } @Test public void testQueryForFieldValues() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put(Foo.VAL_FIELD_NAME, val); List<Foo> results = dao.queryForFieldValues(fieldValues); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); fieldValues.put(Foo.ID_FIELD_NAME, notId); fieldValues.put(Foo.VAL_FIELD_NAME, val); results = dao.queryForFieldValues(fieldValues); assertEquals(0, results.size()); } @Test public void testInsertAutoGeneratedId() throws Exception { Dao<Foo, Integer> dao1 = createDao(Foo.class, true); Dao<NotQuiteFoo, Integer> dao2 = createDao(NotQuiteFoo.class, false); Foo foo = new Foo(); assertEquals(1, dao1.create(foo)); NotQuiteFoo notQuiteFoo = new NotQuiteFoo(); notQuiteFoo.id = foo.id + 1; assertEquals(1, dao2.create(notQuiteFoo)); List<Foo> results = dao1.queryForAll(); assertEquals(2, results.size()); assertEquals(foo.id, results.get(0).id); assertEquals(notQuiteFoo.id, results.get(1).id); } @Test public void testCreateWithAllowGeneratedIdInsert() throws Exception { if (databaseType == null || !databaseType.isAllowGeneratedIdInsertSupported()) { return; } Dao<AllowGeneratedIdInsert, Integer> dao = createDao(AllowGeneratedIdInsert.class, true); AllowGeneratedIdInsert foo = new AllowGeneratedIdInsert(); assertEquals(1, dao.create(foo)); AllowGeneratedIdInsert result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.id, result.id); AllowGeneratedIdInsert foo2 = new AllowGeneratedIdInsert(); assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.id, result.id); assertFalse(foo2.id == foo.id); AllowGeneratedIdInsert foo3 = new AllowGeneratedIdInsert(); foo3.id = 10002; assertEquals(1, dao.create(foo3)); result = dao.queryForId(foo3.id); assertNotNull(result); assertEquals(foo3.id, result.id); assertFalse(foo3.id == foo.id); assertFalse(foo3.id == foo2.id); } @Test public void testCreateWithAllowGeneratedIdInsertObject() throws Exception { if (databaseType == null || !databaseType.isAllowGeneratedIdInsertSupported()) { return; } Dao<AllowGeneratedIdInsertObject, Integer> dao = createDao(AllowGeneratedIdInsertObject.class, true); AllowGeneratedIdInsertObject foo = new AllowGeneratedIdInsertObject(); assertEquals(1, dao.create(foo)); AllowGeneratedIdInsertObject result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.id, result.id); AllowGeneratedIdInsertObject foo2 = new AllowGeneratedIdInsertObject(); assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.id, result.id); assertFalse(foo2.id == foo.id); AllowGeneratedIdInsertObject foo3 = new AllowGeneratedIdInsertObject(); foo3.id = 10002; assertEquals(1, dao.create(foo3)); result = dao.queryForId(foo3.id); assertNotNull(result); assertEquals(foo3.id, result.id); assertFalse(foo3.id == foo.id); assertFalse(foo3.id == foo2.id); } @Test public void testCreateOrUpdate() throws Exception { Dao<NotQuiteFoo, Integer> dao = createDao(NotQuiteFoo.class, true); NotQuiteFoo foo1 = new NotQuiteFoo(); foo1.stuff = "wow"; CreateOrUpdateStatus status = dao.createOrUpdate(foo1); assertTrue(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); String stuff2 = "4134132"; foo1.stuff = stuff2; status = dao.createOrUpdate(foo1); assertFalse(status.isCreated()); assertTrue(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); NotQuiteFoo result = dao.queryForId(foo1.id); assertEquals(stuff2, result.stuff); } @Test public void testCreateOrUpdateNull() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); CreateOrUpdateStatus status = dao.createOrUpdate(null); assertFalse(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(0, status.getNumLinesChanged()); } @Test public void testCreateOrUpdateNullId() throws Exception { Dao<CreateOrUpdateObjectId, Integer> dao = createDao(CreateOrUpdateObjectId.class, true); CreateOrUpdateObjectId foo = new CreateOrUpdateObjectId(); String stuff = "21313"; foo.stuff = stuff; CreateOrUpdateStatus status = dao.createOrUpdate(foo); assertTrue(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); CreateOrUpdateObjectId result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(stuff, result.stuff); String stuff2 = "pwojgfwe"; foo.stuff = stuff2; dao.createOrUpdate(foo); result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(stuff2, result.stuff); } @Test public void testUpdateNoChange() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); foo.id = 13567567; foo.val = 1232131; assertEquals(1, dao.create(foo)); assertEquals(1, dao.update(foo)); assertEquals(1, dao.update(foo)); } @Test public void testNullForeign() throws Exception { Dao<Order, Integer> orderDao = createDao(Order.class, true); int numOrders = 10; for (int orderC = 0; orderC < numOrders; orderC++) { Order order = new Order(); order.val = orderC; assertEquals(1, orderDao.create(order)); } List<Order> results = orderDao.queryBuilder().where().isNull(Order.ONE_FIELD_NAME).query(); assertNotNull(results); assertEquals(numOrders, results.size()); } @Test public void testSelfGeneratedIdPrimary() throws Exception { Dao<SelfGeneratedIdUuidPrimary, UUID> dao = createDao(SelfGeneratedIdUuidPrimary.class, true); SelfGeneratedIdUuidPrimary foo = new SelfGeneratedIdUuidPrimary(); foo.stuff = "ewpfojwefjo"; assertEquals(1, dao.create(foo)); SelfGeneratedIdUuidPrimary result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.stuff, result.stuff); } @Test public void testCreateIfNotExists() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); String stuff = "stuff"; foo1.stuff = stuff; Foo fooResult = dao.createIfNotExists(foo1); assertSame(foo1, fooResult); // now if we do it again, we should get the database copy of foo fooResult = dao.createIfNotExists(foo1); assertNotSame(foo1, fooResult); assertEquals(foo1.id, fooResult.id); assertEquals(foo1.stuff, fooResult.stuff); } @Test public void testCreateIfNotExistsNull() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); assertNull(dao.createIfNotExists(null)); } @Test public void testCountOf() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); foo.id = 1; assertEquals(1, dao.create(foo)); assertEquals(1, dao.countOf()); foo.id = 2; assertEquals(1, dao.create(foo)); assertEquals(2, dao.countOf()); } @Test public void testCountOfPrepared() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id1 = 1; foo.id = id1; assertEquals(1, dao.create(foo)); foo.id = 2; assertEquals(1, dao.create(foo)); assertEquals(2, dao.countOf()); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.setCountOf(true).where().eq(Foo.ID_FIELD_NAME, id1); assertEquals(1, dao.countOf(qb.prepare())); } @Test public void testCountOfPreparedNoCountOf() throws Exception { if (connectionSource == null) { throw new IllegalArgumentException("Simulation"); } Dao<Foo, String> dao = createDao(Foo.class, true); QueryBuilder<Foo, String> qb = dao.queryBuilder(); try { dao.countOf(qb.prepare()); fail("Should have thrown"); } catch (IllegalArgumentException e) { // expected } } @Test public void testSelectRaw() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); assertEquals(1, dao.create(foo)); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.selectRaw("COUNT(*)"); GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString()); List<String[]> list = results.getResults(); assertEquals(1, list.size()); String[] array = list.get(0); assertEquals(1, array.length); assertEquals("1", array[0]); } @Test public void testSelectRawNotQuery() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); assertEquals(1, dao.create(foo)); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.selectRaw("COUNTOF(*)"); try { qb.query(); } catch (SQLException e) { // expected } } @Test public void testForeignAutoCreate() throws Exception { Dao<ForeignAutoCreate, Long> foreignAutoCreateDao = createDao(ForeignAutoCreate.class, true); Dao<ForeignAutoCreateForeign, Long> foreignAutoCreateForeignDao = createDao(ForeignAutoCreateForeign.class, true); List<ForeignAutoCreateForeign> results = foreignAutoCreateForeignDao.queryForAll(); assertEquals(0, results.size()); ForeignAutoCreateForeign foreign = new ForeignAutoCreateForeign(); String stuff = "fopewjfpwejfpwjfw"; foreign.stuff = stuff; ForeignAutoCreate foo1 = new ForeignAutoCreate(); foo1.foreign = foreign; assertEquals(1, foreignAutoCreateDao.create(foo1)); // we should not get something from the other dao results = foreignAutoCreateForeignDao.queryForAll(); assertEquals(1, results.size()); assertEquals(foreign.id, results.get(0).id); // if we get foo back, we should see the foreign-id List<ForeignAutoCreate> foreignAutoCreateResults = foreignAutoCreateDao.queryForAll(); assertEquals(1, foreignAutoCreateResults.size()); assertEquals(foo1.id, foreignAutoCreateResults.get(0).id); assertNotNull(foreignAutoCreateResults.get(0).foreign); assertEquals(foo1.foreign.id, foreignAutoCreateResults.get(0).foreign.id); // now we create it when the foreign field already has an id set ForeignAutoCreate foo2 = new ForeignAutoCreate(); foo2.foreign = foreign; assertEquals(1, foreignAutoCreateDao.create(foo1)); results = foreignAutoCreateForeignDao.queryForAll(); // no additional results should be found assertEquals(1, results.size()); assertEquals(foreign.id, results.get(0).id); } /* ==================================================================================== */ private <T extends TestableType<ID>, ID> void checkTypeAsId(Class<T> clazz, ID id1, ID id2) throws Exception { Constructor<T> constructor = clazz.getDeclaredConstructor(); Dao<T, ID> dao = createDao(clazz, true); String s1 = "stuff"; T data1 = constructor.newInstance(); data1.setId(id1); data1.setStuff(s1); // create it assertEquals(1, dao.create(data1)); // refresh it assertEquals(1, dao.refresh(data1)); // now we query for foo from the database to make sure it was persisted right T data2 = dao.queryForId(id1); assertNotNull(data2); assertEquals(id1, data2.getId()); assertEquals(s1, data2.getStuff()); // now we update 1 row in a the database after changing stuff String s2 = "stuff2"; data2.setStuff(s2); assertEquals(1, dao.update(data2)); // now we get it from the db again to make sure it was updated correctly T data3 = dao.queryForId(id1); assertEquals(s2, data3.getStuff()); // change its id assertEquals(1, dao.updateId(data2, id2)); // the old id should not exist assertNull(dao.queryForId(id1)); T data4 = dao.queryForId(id2); assertNotNull(data4); assertEquals(s2, data4.getStuff()); // delete it assertEquals(1, dao.delete(data2)); // should not find it assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); // create data1 and data2 data1.setId(id1); assertEquals(1, dao.create(data1)); data2 = constructor.newInstance(); data2.setId(id2); assertEquals(1, dao.create(data2)); data3 = dao.queryForId(id1); assertNotNull(data3); assertEquals(id1, data3.getId()); data4 = dao.queryForId(id2); assertNotNull(data4); assertEquals(id2, data4.getId()); // delete a collection of ids List<ID> idList = new ArrayList<ID>(); idList.add(id1); idList.add(id2); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, dao.deleteIds(idList)); } else { assertEquals(2, dao.deleteIds(idList)); } assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); // delete a collection of objects assertEquals(1, dao.create(data1)); assertEquals(1, dao.create(data2)); List<T> dataList = new ArrayList<T>(); dataList.add(data1); dataList.add(data2); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, dao.delete(dataList)); } else { assertEquals(2, dao.delete(dataList)); } assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); } /** * Returns the object if the query failed or null otherwise. */ private boolean checkQueryResult(Dao<AllTypes, Integer> allDao, QueryBuilder<AllTypes, Integer> qb, AllTypes allTypes, String fieldName, Object value, boolean required) throws SQLException { qb.where().eq(fieldName, value); List<AllTypes> results = allDao.query(qb.prepare()); if (required) { assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } else if (results.size() == 1) { assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } else { return false; } SelectArg selectArg = new SelectArg(); qb.where().eq(fieldName, selectArg); selectArg.setValue(value); results = allDao.query(qb.prepare()); assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); return true; } private String buildFooQueryAllString(Dao<Foo, Object> fooDao) throws SQLException { String queryString = fooDao.queryBuilder() .selectColumns(Foo.ID_FIELD_NAME, Foo.STUFF_FIELD_NAME, Foo.VAL_FIELD_NAME) .prepareStatementString(); return queryString; } private interface TestableType<ID> { String getStuff(); void setStuff(String stuff); ID getId(); void setId(ID id); } private static class Mapper implements RawRowMapper<Foo> { public Foo mapRow(String[] columnNames, String[] resultColumns) { Foo foo = new Foo(); for (int i = 0; i < columnNames.length; i++) { if (columnNames[i].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { foo.id = Integer.parseInt(resultColumns[i]); } else if (columnNames[i].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { foo.stuff = resultColumns[i]; } else if (columnNames[i].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { foo.val = Integer.parseInt(resultColumns[i]); } } return foo; } } /* ==================================================================================== */ @DatabaseTable(tableName = FOO_TABLE_NAME) protected static class Foo { public final static String ID_FIELD_NAME = "id"; public final static String STUFF_FIELD_NAME = "stuff"; public final static String VAL_FIELD_NAME = "val"; @DatabaseField(generatedId = true, columnName = ID_FIELD_NAME) public int id; @DatabaseField(columnName = STUFF_FIELD_NAME) public String stuff; @DatabaseField(columnName = VAL_FIELD_NAME) public int val; public Foo() { } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return id == ((Foo) other).id; } @Override public int hashCode() { return id; } @Override public String toString() { return "Foo.id=" + id; } } @DatabaseTable(tableName = FOO_TABLE_NAME) protected static class NotQuiteFoo { @DatabaseField(id = true, columnName = Foo.ID_FIELD_NAME) public int id; @DatabaseField(columnName = Foo.STUFF_FIELD_NAME) public String stuff; @DatabaseField(columnName = Foo.VAL_FIELD_NAME) public int val; public NotQuiteFoo() { } } protected static class DoubleCreate { @DatabaseField(id = true) int id; } protected static class NoId { @DatabaseField public String notId; } private static class JustId { @DatabaseField(id = true) public String id; } private static class ForeignWrapper { private final static String FOREIGN_FIELD_NAME = "foreign"; @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true, columnName = FOREIGN_FIELD_NAME) AllTypes foreign; } private static class MultipleForeignWrapper { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true) AllTypes foreign; @DatabaseField(foreign = true) ForeignWrapper foreignWrapper; } protected static class GetSet { @DatabaseField(generatedId = true, useGetSet = true) private int id; @DatabaseField(useGetSet = true) private String stuff; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } protected static class NoAnno { public int id; public String stuff; public NoAnno() { } } protected static class NoAnnoFor { public int id; public NoAnno foreign; public NoAnnoFor() { } } protected static class GeneratedIdNotNull { @DatabaseField(generatedId = true, canBeNull = false) public int id; @DatabaseField public String stuff; public GeneratedIdNotNull() { } } protected static class Basic { public final static String ID_FIELD = "id"; @DatabaseField(id = true, columnName = ID_FIELD) String id; } private static class DefaultValue { @DatabaseField(defaultValue = DEFAULT_VALUE_STRING) Integer intField; DefaultValue() { } } protected static class NotNull { @DatabaseField(canBeNull = false) String notNull; NotNull() { } } protected static class GeneratedId { @DatabaseField(generatedId = true) int id; @DatabaseField String other; public GeneratedId() { } } protected static class AllTypes { public static final String STRING_FIELD_NAME = "stringField"; public static final String BOOLEAN_FIELD_NAME = "booleanField"; public static final String DATE_FIELD_NAME = "dateField"; public static final String DATE_LONG_FIELD_NAME = "dateLongField"; public static final String DATE_STRING_FIELD_NAME = "dateStringField"; public static final String SERIAL_FIELD_NAME = "serialField"; public static final String CHAR_FIELD_NAME = "charField"; public static final String BYTE_FIELD_NAME = "byteField"; public static final String SHORT_FIELD_NAME = "shortField"; public static final String INT_FIELD_NAME = "intField"; public static final String LONG_FIELD_NAME = "longField"; public static final String FLOAT_FIELD_NAME = "floatField"; public static final String DOUBLE_FIELD_NAME = "doubleField"; public static final String ENUM_FIELD_NAME = "enumField"; public static final String ENUM_STRING_FIELD_NAME = "enumStringField"; public static final String ENUM_INTEGER_FIELD_NAME = "enumIntegerField"; @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = STRING_FIELD_NAME) String stringField; @DatabaseField(columnName = BOOLEAN_FIELD_NAME) boolean booleanField; @DatabaseField(columnName = DATE_FIELD_NAME) Date dateField; @DatabaseField(columnName = DATE_LONG_FIELD_NAME, dataType = DataType.DATE_LONG) Date dateLongField; @DatabaseField(columnName = DATE_STRING_FIELD_NAME, dataType = DataType.DATE_STRING, format = DEFAULT_DATE_STRING_FORMAT) Date dateStringField; @DatabaseField(columnName = CHAR_FIELD_NAME) char charField; @DatabaseField(columnName = BYTE_FIELD_NAME) byte byteField; @DatabaseField(columnName = SHORT_FIELD_NAME) short shortField; @DatabaseField(columnName = INT_FIELD_NAME) int intField; @DatabaseField(columnName = LONG_FIELD_NAME) long longField; @DatabaseField(columnName = FLOAT_FIELD_NAME) float floatField; @DatabaseField(columnName = DOUBLE_FIELD_NAME) double doubleField; @DatabaseField(columnName = SERIAL_FIELD_NAME, dataType = DataType.SERIALIZABLE) SerialData serialField; @DatabaseField(columnName = ENUM_FIELD_NAME) OurEnum enumField; @DatabaseField(columnName = ENUM_STRING_FIELD_NAME, dataType = DataType.ENUM_STRING) OurEnum enumStringField; @DatabaseField(columnName = ENUM_INTEGER_FIELD_NAME, dataType = DataType.ENUM_INTEGER) OurEnum enumIntegerField; AllTypes() { } } protected static class AllTypesDefault { @DatabaseField(generatedId = true) int id; @DatabaseField(defaultValue = DEFAULT_STRING_VALUE) String stringField; @DatabaseField(defaultValue = DEFAULT_DATE_VALUE) Date dateField; @DatabaseField(dataType = DataType.DATE_LONG, defaultValue = DEFAULT_DATE_LONG_VALUE) Date dateLongField; @DatabaseField(dataType = DataType.DATE_STRING, defaultValue = DEFAULT_DATE_STRING_VALUE, format = DEFAULT_DATE_STRING_FORMAT) Date dateStringField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) boolean booleanField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) Boolean booleanObj; @DatabaseField(defaultValue = DEFAULT_BYTE_VALUE) byte byteField; @DatabaseField(defaultValue = DEFAULT_BYTE_VALUE) Byte byteObj; @DatabaseField(defaultValue = DEFAULT_SHORT_VALUE) short shortField; @DatabaseField(defaultValue = DEFAULT_SHORT_VALUE) Short shortObj; @DatabaseField(defaultValue = DEFAULT_INT_VALUE) int intField; @DatabaseField(defaultValue = DEFAULT_INT_VALUE) Integer intObj; @DatabaseField(defaultValue = DEFAULT_LONG_VALUE) long longField; @DatabaseField(defaultValue = DEFAULT_LONG_VALUE) Long longObj; @DatabaseField(defaultValue = DEFAULT_FLOAT_VALUE) float floatField; @DatabaseField(defaultValue = DEFAULT_FLOAT_VALUE) Float floatObj; @DatabaseField(defaultValue = DEFAULT_DOUBLE_VALUE) double doubleField; @DatabaseField(defaultValue = DEFAULT_DOUBLE_VALUE) Double doubleObj; @DatabaseField(dataType = DataType.SERIALIZABLE) SerialData objectField; @DatabaseField(defaultValue = DEFAULT_ENUM_VALUE) OurEnum ourEnum; @DatabaseField(defaultValue = DEFAULT_ENUM_NUMBER_VALUE, dataType = DataType.ENUM_INTEGER) OurEnum ourEnumNumber; AllTypesDefault() { } } protected static class BooleanDefault { @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) boolean booleanField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) Boolean booleanObj; BooleanDefault() { } } protected static class AllObjectTypes { @DatabaseField(generatedId = true) int id; @DatabaseField String stringField; @DatabaseField Boolean booleanField; @DatabaseField Date dateField; @DatabaseField Byte byteField; @DatabaseField Short shortField; @DatabaseField Integer intField; @DatabaseField Long longField; @DatabaseField Float floatField; @DatabaseField Double doubleField; @DatabaseField(dataType = DataType.SERIALIZABLE) SerialData objectField; @DatabaseField OurEnum ourEnum; AllObjectTypes() { } } protected static class NumberTypes { @DatabaseField(generatedId = true) public int id; @DatabaseField public byte byteField; @DatabaseField public short shortField; @DatabaseField public int intField; @DatabaseField public long longField; @DatabaseField public float floatField; @DatabaseField public double doubleField; public NumberTypes() { } } protected static class StringWidth { @DatabaseField(width = ALL_TYPES_STRING_WIDTH) String stringField; StringWidth() { } } // for testing reserved table names as fields private static class Create { @DatabaseField(id = true) public String id; } // for testing reserved words as field names protected static class ReservedField { @DatabaseField(id = true) public int select; @DatabaseField public String from; @DatabaseField public String table; @DatabaseField public String where; @DatabaseField public String group; @DatabaseField public String order; @DatabaseField public String values; public ReservedField() { } } // test the field name that has a capital letter in it protected static class GeneratedColumnCapital { @DatabaseField(generatedId = true, columnName = "idCap") int id; @DatabaseField String other; public GeneratedColumnCapital() { } } protected static class ObjectHolder { @DatabaseField(generatedId = true) public int id; @DatabaseField(dataType = DataType.SERIALIZABLE) public SerialData obj; @DatabaseField(dataType = DataType.SERIALIZABLE) public String strObj; public ObjectHolder() { } } protected static class NotSerializable { @DatabaseField(generatedId = true) public int id; @DatabaseField(dataType = DataType.SERIALIZABLE) public ObjectHolder obj; public NotSerializable() { } } protected static class SerialData implements Serializable { private static final long serialVersionUID = -3883857119616908868L; public Map<String, String> map; public SerialData() { } public void addEntry(String key, String value) { if (map == null) { map = new HashMap<String, String>(); } map.put(key, value); } @Override public int hashCode() { return map.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } SerialData other = (SerialData) obj; if (map == null) { return other.map == null; } else { return map.equals(other.map); } } } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumString { @DatabaseField OurEnum ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumString2 { @DatabaseField OurEnum2 ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt { @DatabaseField(dataType = DataType.ENUM_INTEGER) OurEnum ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt2 { @DatabaseField(dataType = DataType.ENUM_INTEGER) OurEnum2 ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt3 { @DatabaseField(dataType = DataType.ENUM_INTEGER, unknownEnumName = "FIRST") OurEnum2 ourEnum; } private enum OurEnum { FIRST, SECOND, ; } private enum OurEnum2 { FIRST, ; } @DatabaseTable(tableName = NULL_BOOLEAN_TABLE_NAME) protected static class NullBoolean1 { @DatabaseField Boolean val; } @DatabaseTable(tableName = NULL_BOOLEAN_TABLE_NAME) protected static class NullBoolean2 { @DatabaseField(throwIfNull = true) boolean val; } @DatabaseTable(tableName = NULL_INT_TABLE_NAME) protected static class NullInt1 { @DatabaseField Integer val; } @DatabaseTable(tableName = NULL_INT_TABLE_NAME) protected static class NullInt2 { @DatabaseField(throwIfNull = true) int val; } @DatabaseTable protected static class NotNullDefault { @DatabaseField(canBeNull = false, defaultValue = "3") String stuff; } @DatabaseTable protected static class Unique { @DatabaseField(generatedId = true) int id; @DatabaseField String stuff; @DatabaseField(unique = true) String uniqueStuff; } @DatabaseTable protected static class DoubleUnique { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String stuff; @DatabaseField(unique = true) String uniqueStuff; } @DatabaseTable protected static class DoubleUniqueCombo { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueCombo = true) String stuff; @DatabaseField(uniqueCombo = true) String uniqueStuff; } @DatabaseTable protected static class UniqueAndUniqueCombo { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String unique1; @DatabaseField(uniqueCombo = true) String combo1; @DatabaseField(uniqueCombo = true) String combo2; } @DatabaseTable protected static class StringDefalt { @DatabaseField(defaultValue = "3") String stuff; } @DatabaseTable protected static class LocalDate { @DatabaseField(generatedId = true) int id; @DatabaseField Date date; } @DatabaseTable protected static class StringId implements TestableType<String> { @DatabaseField(id = true) String id; @DatabaseField String stuff; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongStringId implements TestableType<String> { @DatabaseField(id = true, dataType = DataType.LONG_STRING) String id; @DatabaseField String stuff; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class BooleanId implements TestableType<Boolean> { @DatabaseField(id = true) boolean id; @DatabaseField String stuff; public Boolean getId() { return id; } public void setId(Boolean bool) { this.id = bool; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class BooleanObjId implements TestableType<Boolean> { @DatabaseField(id = true) Boolean id; @DatabaseField String stuff; public Boolean getId() { return id; } public void setId(Boolean bool) { this.id = bool; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateId implements TestableType<Date> { @DatabaseField(id = true) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateLongId implements TestableType<Date> { @DatabaseField(id = true, dataType = DataType.DATE_LONG) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateStringId implements TestableType<Date> { @DatabaseField(id = true, dataType = DataType.DATE_STRING) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ByteId implements TestableType<Byte> { @DatabaseField(id = true) byte id; @DatabaseField String stuff; public Byte getId() { return id; } public void setId(Byte id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ByteObjId implements TestableType<Byte> { @DatabaseField(id = true) Byte id; @DatabaseField String stuff; public Byte getId() { return id; } public void setId(Byte id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ShortId implements TestableType<Short> { @DatabaseField(id = true) short id; @DatabaseField String stuff; public Short getId() { return id; } public void setId(Short id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ShortObjId implements TestableType<Short> { @DatabaseField(id = true) Short id; @DatabaseField String stuff; public Short getId() { return id; } public void setId(Short id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class IntId implements TestableType<Integer> { @DatabaseField(id = true) int id; @DatabaseField String stuff; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class IntObjId implements TestableType<Integer> { @DatabaseField(id = true) Integer id; @DatabaseField String stuff; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongId implements TestableType<Long> { @DatabaseField(id = true) long id; @DatabaseField String stuff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongObjId implements TestableType<Long> { @DatabaseField(id = true) Long id; @DatabaseField String stuff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class FloatId implements TestableType<Float> { @DatabaseField(id = true) float id; @DatabaseField String stuff; public Float getId() { return id; } public void setId(Float id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class FloatObjId implements TestableType<Float> { @DatabaseField(id = true) Float id; @DatabaseField String stuff; public Float getId() { return id; } public void setId(Float id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DoubleId implements TestableType<Double> { @DatabaseField(id = true) double id; @DatabaseField String stuff; public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DoubleObjId implements TestableType<Double> { @DatabaseField(id = true) Double id; @DatabaseField String stuff; public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumId implements TestableType<OurEnum> { @DatabaseField(id = true) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumStringId implements TestableType<OurEnum> { @DatabaseField(id = true, dataType = DataType.ENUM_STRING) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumIntegerId implements TestableType<OurEnum> { @DatabaseField(id = true, dataType = DataType.ENUM_INTEGER) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class SerializableId implements TestableType<SerialData> { @DatabaseField(id = true, dataType = DataType.SERIALIZABLE) SerialData serial; @DatabaseField String stuff; public SerialData getId() { return serial; } public void setId(SerialData id) { this.serial = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class Recursive { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true) Recursive foreign; public Recursive() { } } @DatabaseTable protected static class SerializedBytes { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.SERIALIZABLE) byte[] bytes; public SerializedBytes() { } } @DatabaseTable protected static class ByteArray { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.BYTE_ARRAY) byte[] bytes; public ByteArray() { } } @DatabaseTable protected static class Index { @DatabaseField(generatedId = true) int id; @DatabaseField(index = true) String stuff; public Index() { } } @DatabaseTable protected static class IndexColumnName { public static final String STUFF_COLUMN_NAME = "notStuff"; @DatabaseField(generatedId = true) int id; @DatabaseField(index = true, columnName = STUFF_COLUMN_NAME) String stuff; public IndexColumnName() { } } @DatabaseTable protected static class UniqueIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueIndex = true) String stuff; public UniqueIndex() { } } @DatabaseTable protected static class ComboIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(indexName = "stuffjunk") String stuff; @DatabaseField(indexName = "stuffjunk") long junk; public ComboIndex() { } } @DatabaseTable protected static class ComboUniqueIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueIndexName = "stuffjunk") String stuff; @DatabaseField(uniqueIndexName = "stuffjunk") long junk; public ComboUniqueIndex() { } } @DatabaseTable protected static class LongVarChar { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.LONG_STRING) String stuff; public LongVarChar() { } } protected static class Base { @DatabaseField(id = true) int id; public Base() { // for ormlite } } protected static class Sub extends Base { @DatabaseField String stuff; public Sub() { // for ormlite } } protected static class UuidGeneratedId { @DatabaseField(generatedId = true) public UUID id; @DatabaseField public String stuff; public UuidGeneratedId() { } } protected static class One extends BaseDaoEnabled<One, Integer> { @DatabaseField(generatedId = true) public int id; @DatabaseField public String stuff; public One() { } } protected static class ForeignDaoEnabled extends BaseDaoEnabled<ForeignDaoEnabled, Integer> { @DatabaseField(generatedId = true) public int id; @DatabaseField(foreign = true) public One one; public ForeignDaoEnabled() { } } protected static class EagerAccount { @DatabaseField(generatedId = true) int id; @DatabaseField String name; @ForeignCollectionField(eager = true) Collection<EagerOrder> orders; protected EagerAccount() { } } protected static class EagerOrder { @DatabaseField(generatedId = true) int id; @DatabaseField int val; @DatabaseField(foreign = true) EagerAccount account; protected EagerOrder() { } } protected static class LazyAccount { @DatabaseField(generatedId = true) int id; @DatabaseField String name; @ForeignCollectionField Collection<LazyOrder> orders; protected LazyAccount() { } } protected static class LazyOrder { @DatabaseField(generatedId = true) int id; @DatabaseField int val; @DatabaseField(foreign = true) LazyAccount account; protected LazyOrder() { } } protected static class AllowGeneratedIdInsert { @DatabaseField(generatedId = true, allowGeneratedIdInsert = true) int id; @DatabaseField String stuff; } protected static class SelfGeneratedIdUuidPrimary { @DatabaseField(generatedId = true) UUID id; @DatabaseField String stuff; } protected static class AllowGeneratedIdInsertObject { @DatabaseField(generatedId = true, allowGeneratedIdInsert = true) Integer id; @DatabaseField String stuff; } protected static class CreateOrUpdateObjectId { @DatabaseField(generatedId = true) public Integer id; @DatabaseField public String stuff; public CreateOrUpdateObjectId() { } } protected static class Order { public static final String ONE_FIELD_NAME = "one_id"; @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) int val; @DatabaseField(foreign = true, columnName = ONE_FIELD_NAME) One one; protected Order() { } } protected static class ForeignAutoCreate { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true, foreignAutoCreate = true) public ForeignAutoCreateForeign foreign; } protected static class ForeignAutoCreateForeign { @DatabaseField(generatedId = true) int id; @DatabaseField String stuff; } }
src/test/java/com/j256/ormlite/dao/JdbcBaseDaoImplTest.java
package com.j256.ormlite.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import org.junit.Test; import com.j256.ormlite.BaseJdbcTest; import com.j256.ormlite.dao.Dao.CreateOrUpdateStatus; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseFieldConfig; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.misc.BaseDaoEnabled; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.PreparedQuery; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.j256.ormlite.stmt.UpdateBuilder; import com.j256.ormlite.stmt.Where; import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTableConfig; import com.j256.ormlite.table.TableUtils; public class JdbcBaseDaoImplTest extends BaseJdbcTest { private static final boolean CLOSE_IS_NOOP = false; private static final boolean UPDATE_ROWS_RETURNS_ONE = false; protected boolean isTableExistsWorks() { return true; } /* ======================================================================================== */ private final static String DEFAULT_VALUE_STRING = "1314199"; private final static int DEFAULT_VALUE = Integer.parseInt(DEFAULT_VALUE_STRING); private final static int ALL_TYPES_STRING_WIDTH = 4; protected final static String FOO_TABLE_NAME = "footable"; private final static String ENUM_TABLE_NAME = "enumtable"; private final static String NULL_BOOLEAN_TABLE_NAME = "nullbooltable"; private final static String NULL_INT_TABLE_NAME = "nullinttable"; private final static String DEFAULT_BOOLEAN_VALUE = "true"; private final static String DEFAULT_STRING_VALUE = "foo"; // this can't have non-zero milliseconds private final static String DEFAULT_DATE_VALUE = "2010-07-16 01:31:17.000000"; private final static String DEFAULT_DATE_LONG_VALUE = "1282768620000"; private final static String DEFAULT_DATE_STRING_FORMAT = "MM/dd/yyyy HH-mm-ss-SSSSSS"; private final static String DEFAULT_DATE_STRING_VALUE = "07/16/2010 01-31-17-000000"; private final static String DEFAULT_BYTE_VALUE = "1"; private final static String DEFAULT_SHORT_VALUE = "2"; private final static String DEFAULT_INT_VALUE = "3"; private final static String DEFAULT_LONG_VALUE = "4"; private final static String DEFAULT_FLOAT_VALUE = "5"; private final static String DEFAULT_DOUBLE_VALUE = "6"; private final static String DEFAULT_ENUM_VALUE = "FIRST"; private final static String DEFAULT_ENUM_NUMBER_VALUE = "1"; @Test public void testCreateDaoStatic() throws Exception { if (connectionSource == null) { return; } createTable(Foo.class, true); Dao<Foo, Integer> fooDao = DaoManager.createDao(connectionSource, Foo.class); String stuff = "stuff"; Foo foo = new Foo(); foo.stuff = stuff; assertEquals(1, fooDao.create(foo)); // now we query for foo from the database to make sure it was persisted right Foo foo2 = fooDao.queryForId(foo.id); assertNotNull(foo2); assertEquals(foo.id, foo2.id); assertEquals(stuff, foo2.stuff); } @Test public void testCreateUpdateDelete() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String s1 = "stuff"; Foo foo1 = new Foo(); foo1.stuff = s1; assertEquals(0, foo1.id); // persist foo to db through the dao and sends the id on foo because it was auto-generated by the db assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); assertEquals(s1, foo1.stuff); // now we query for foo from the database to make sure it was persisted right Foo foo2 = fooDao.queryForId(foo1.id); assertNotNull(foo2); assertEquals(foo1.id, foo2.id); assertEquals(s1, foo2.stuff); String s2 = "stuff2"; foo2.stuff = s2; // now we update 1 row in a the database after changing foo assertEquals(1, fooDao.update(foo2)); // now we get it from the db again to make sure it was updated correctly Foo foo3 = fooDao.queryForId(foo1.id); assertEquals(s2, foo3.stuff); assertEquals(1, fooDao.delete(foo2)); assertNull(fooDao.queryForId(foo1.id)); } @Test public void testDoubleCreate() throws Exception { Dao<DoubleCreate, Object> doubleDao = createDao(DoubleCreate.class, true); int id = 313413123; DoubleCreate foo = new DoubleCreate(); foo.id = id; assertEquals(1, doubleDao.create(foo)); try { doubleDao.create(foo); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testIterateRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> acctList = fooDao.queryForAll(); int initialSize = acctList.size(); Foo foo1 = new Foo(); foo1.stuff = "s1"; Foo foo2 = new Foo(); foo2.stuff = "s2"; Foo foo3 = new Foo(); foo3.stuff = "s3"; fooDao.create(foo1); fooDao.create(foo2); fooDao.create(foo3); assertTrue(foo1.id != foo2.id); assertTrue(foo1.id != foo3.id); assertTrue(foo2.id != foo3.id); assertEquals(foo1, fooDao.queryForId(foo1.id)); assertEquals(foo2, fooDao.queryForId(foo2.id)); assertEquals(foo3, fooDao.queryForId(foo3.id)); acctList = fooDao.queryForAll(); assertEquals(initialSize + 3, acctList.size()); assertEquals(foo1, acctList.get(acctList.size() - 3)); assertEquals(foo2, acctList.get(acctList.size() - 2)); assertEquals(foo3, acctList.get(acctList.size() - 1)); int acctC = 0; Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { Foo foo = iterator.next(); if (acctC == acctList.size() - 3) { assertEquals(foo1, foo); } else if (acctC == acctList.size() - 2) { iterator.remove(); assertEquals(foo2, foo); } else if (acctC == acctList.size() - 1) { assertEquals(foo3, foo); } acctC++; } assertEquals(initialSize + 3, acctC); } @Test public void testGeneratedField() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; assertEquals(0, foo1.id); assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); } @Test public void testGeneratedIdNotNullField() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; assertEquals(0, foo1.id); assertEquals(1, fooDao.create(foo1)); assertTrue(foo1.id != 0); } @Test public void testObjectToString() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff = "foo123231"; Foo foo1 = new Foo(); foo1.stuff = stuff; String objStr = fooDao.objectToString(foo1); assertTrue(objStr.contains(Integer.toString(foo1.id))); assertTrue(objStr.contains(stuff)); } @Test public void testCreateNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.create((Foo) null)); } @Test public void testUpdateNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.update((Foo) null)); } @Test public void testUpdateIdNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.updateId(null, null)); } @Test public void testDeleteNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); assertEquals(0, fooDao.delete((Foo) null)); } @Test public void testCloseInIterator() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); Iterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { iterator.next(); closeConnectionSource(); } if (!CLOSE_IS_NOOP) { fail("expected exception"); } } catch (IllegalStateException e) { // expected } } @Test public void testCloseIteratorFirst() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); closeConnectionSource(); try { fooDao.iterator(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } @Test public void testCloseIteratorBeforeNext() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { closeConnectionSource(); iterator.next(); } if (!CLOSE_IS_NOOP) { fail("expected exception"); } } catch (IllegalStateException e) { // expected } finally { iterator.close(); } } @Test public void testCloseIteratorBeforeRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { while (iterator.hasNext()) { iterator.next(); closeConnectionSource(); iterator.remove(); } fail("expected exception"); } catch (Exception e) { // expected } } @Test public void testNoNextBeforeRemove() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.stuff = "s1"; fooDao.create(foo1); CloseableIterator<Foo> iterator = fooDao.iterator(); try { iterator.remove(); fail("expected exception"); } catch (IllegalStateException e) { // expected } finally { iterator.close(); } } @Test public void testIteratePageSize() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); int numItems = 1000; fooDao.callBatchTasks(new InsertCallable(numItems, fooDao)); // now delete them with the iterator to test page-size Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } @Test public void testIteratorPreparedQuery() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); // do an insert of bunch of items final int numItems = 100; fooDao.callBatchTasks(new InsertCallable(numItems, fooDao)); int lastX = 10; PreparedQuery<Foo> preparedQuery = fooDao.queryBuilder().where().ge(Foo.VAL_FIELD_NAME, numItems - lastX).prepare(); // now delete them with the iterator to test page-size Iterator<Foo> iterator = fooDao.iterator(preparedQuery); int itemC = 0; while (iterator.hasNext()) { Foo foo = iterator.next(); System.out.println("Foo = " + foo.val); itemC++; } assertEquals(lastX, itemC); } private static class InsertCallable implements Callable<Void> { private int numItems; private Dao<Foo, Integer> fooDao; public InsertCallable(int numItems, Dao<Foo, Integer> fooDao) { this.numItems = numItems; this.fooDao = fooDao; } public Void call() throws Exception { for (int i = 0; i < numItems; i++) { Foo foo = new Foo(); foo.val = i; assertEquals(1, fooDao.create(foo)); } return null; } } @Test public void testDeleteObjects() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> fooList = new ArrayList<Foo>(); for (int i = 0; i < 100; i++) { Foo foo = new Foo(); foo.stuff = Integer.toString(i); assertEquals(1, fooDao.create(foo)); fooList.add(foo); } int deleted = fooDao.delete(fooList); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteObjectsNone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Foo> fooList = new ArrayList<Foo>(); assertEquals(fooList.size(), fooDao.delete(fooList)); assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteIds() throws Exception { final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); final List<Integer> fooIdList = new ArrayList<Integer>(); fooDao.callBatchTasks(new Callable<Void>() { public Void call() throws Exception { for (int i = 0; i < 100; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); fooIdList.add(foo.id); } return null; } }); int deleted = fooDao.deleteIds(fooIdList); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooIdList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteIdsNone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Integer> fooIdList = new ArrayList<Integer>(); assertEquals(fooIdList.size(), fooDao.deleteIds(fooIdList)); assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeletePreparedStmtIn() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); List<Integer> fooIdList = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); fooIdList.add(foo.id); } DeleteBuilder<Foo, Integer> stmtBuilder = fooDao.deleteBuilder(); stmtBuilder.where().in(Foo.ID_FIELD_NAME, fooIdList); int deleted = fooDao.delete(stmtBuilder.prepare()); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooIdList.size(), deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testDeleteAllPreparedStmt() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); int fooN = 100; for (int i = 0; i < fooN; i++) { Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); } DeleteBuilder<Foo, Integer> stmtBuilder = fooDao.deleteBuilder(); int deleted = fooDao.delete(stmtBuilder.prepare()); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, deleted); } else { assertEquals(fooN, deleted); } assertEquals(0, fooDao.queryForAll().size()); } @Test public void testHasNextAfterDone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); while (iterator.hasNext()) { } assertFalse(iterator.hasNext()); } @Test public void testNextWithoutHasNext() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); try { iterator.next(); fail("expected exception"); } catch (Exception e) { // expected } } @Test public void testRemoveAfterDone() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); assertFalse(iterator.hasNext()); try { iterator.remove(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } @Test public void testIteratorNoResults() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Iterator<Foo> iterator = fooDao.iterator(); assertFalse(iterator.hasNext()); assertNull(iterator.next()); } @Test public void testCreateNoId() throws Exception { Dao<NoId, Object> whereDao = createDao(NoId.class, true); NoId noId = new NoId(); assertEquals(0, whereDao.queryForAll().size()); // this should work even though there is no id whereDao.create(noId); assertEquals(1, whereDao.queryForAll().size()); } @Test public void testJustIdCreateQueryDelete() throws Exception { Dao<JustId, Object> justIdDao = createDao(JustId.class, true); String id = "just-id"; JustId justId = new JustId(); justId.id = id; assertEquals(1, justIdDao.create(justId)); JustId justId2 = justIdDao.queryForId(id); assertNotNull(justId2); assertEquals(id, justId2.id); assertEquals(1, justIdDao.delete(justId)); assertNull(justIdDao.queryForId(id)); // update should fail during construction } @Test public void testJustIdUpdateId() throws Exception { Dao<JustId, Object> justIdDao = createDao(JustId.class, true); String id = "just-id-update-1"; JustId justId = new JustId(); justId.id = id; assertEquals(1, justIdDao.create(justId)); JustId justId2 = justIdDao.queryForId(id); assertNotNull(justId2); assertEquals(id, justId2.id); String id2 = "just-id-update-2"; // change the id assertEquals(1, justIdDao.updateId(justId2, id2)); assertNull(justIdDao.queryForId(id)); JustId justId3 = justIdDao.queryForId(id2); assertNotNull(justId3); assertEquals(id2, justId3.id); assertEquals(1, justIdDao.delete(justId3)); assertNull(justIdDao.queryForId(id)); assertNull(justIdDao.queryForId(id2)); } @Test public void testJustIdRefresh() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff1 = "just-id-refresh-1"; Foo foo1 = new Foo(); foo1.stuff = stuff1; assertEquals(1, fooDao.create(foo1)); int id = foo1.id; Foo foo2 = fooDao.queryForId(id); assertNotNull(foo2); assertEquals(id, foo2.id); assertEquals(stuff1, foo2.stuff); String stuff2 = "just-id-refresh-2"; foo2.stuff = stuff2; // change the id in the db assertEquals(1, fooDao.update(foo2)); Foo foo3 = fooDao.queryForId(id); assertNotNull(foo3); assertEquals(id, foo3.id); assertEquals(stuff2, foo3.stuff); assertEquals(stuff1, foo1.stuff); assertEquals(1, fooDao.refresh(foo1)); assertEquals(stuff2, foo1.stuff); } @Test public void testSpringConstruction() throws Exception { if (connectionSource == null) { return; } createTable(Foo.class, true); BaseDaoImpl<Foo, Integer> fooDao = new BaseDaoImpl<Foo, Integer>(Foo.class) { }; try { fooDao.create(new Foo()); fail("expected exception"); } catch (IllegalStateException e) { // expected } fooDao.setConnectionSource(connectionSource); fooDao.initialize(); Foo foo = new Foo(); assertEquals(1, fooDao.create(foo)); assertEquals(1, fooDao.delete(foo)); } @Test public void testForeignCreation() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); ForeignWrapper wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(wrapper.id, wrapper2.id); assertEquals(wrapper.foreign.id, wrapper2.foreign.id); assertTrue(wrapperDao.objectsEqual(wrapper, wrapper2)); // this won't be true because wrapper2.foreign is a shell assertFalse(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertNull(wrapper2.foreign.stringField); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); // now it should be true assertTrue(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertEquals(stuff1, wrapper2.foreign.stringField); // create a new foreign foreign = new AllTypes(); String stuff2 = "stuff2"; foreign.stringField = stuff2; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); // change the foreign object wrapper.foreign = foreign; // update it assertEquals(1, wrapperDao.update(wrapper)); wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(wrapper.id, wrapper2.id); assertEquals(wrapper.foreign.id, wrapper2.foreign.id); assertTrue(wrapperDao.objectsEqual(wrapper, wrapper2)); // this won't be true because wrapper2.foreign is a shell assertFalse(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertNull(wrapper2.foreign.stringField); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); // now it should be true assertTrue(foreignDao.objectsEqual(foreign, wrapper2.foreign)); assertEquals(stuff2, wrapper2.foreign.stringField); } @Test public void testForeignRefreshNoChange() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); ForeignWrapper wrapper2 = wrapperDao.queryForId(wrapper.id); assertEquals(1, foreignDao.refresh(wrapper2.foreign)); AllTypes foreign2 = wrapper2.foreign; assertEquals(stuff1, foreign2.stringField); assertEquals(1, wrapperDao.refresh(wrapper2)); assertSame(foreign2, wrapper2.foreign); assertEquals(stuff1, wrapper2.foreign.stringField); // now, in the background, we change the foreign ForeignWrapper wrapper3 = wrapperDao.queryForId(wrapper.id); AllTypes foreign3 = new AllTypes(); String stuff3 = "stuff3"; foreign3.stringField = stuff3; assertEquals(1, foreignDao.create(foreign3)); wrapper3.foreign = foreign3; assertEquals(1, wrapperDao.update(wrapper3)); assertEquals(1, wrapperDao.refresh(wrapper2)); // now all of a sudden wrapper2 should not have the same foreign field assertNotSame(foreign2, wrapper2.foreign); assertNull(wrapper2.foreign.stringField); } @Test public void testMultipleForeignWrapper() throws Exception { Dao<MultipleForeignWrapper, Integer> multipleWrapperDao = createDao(MultipleForeignWrapper.class, true); Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); MultipleForeignWrapper multiWrapper = new MultipleForeignWrapper(); multiWrapper.foreign = foreign; multiWrapper.foreignWrapper = wrapper; // this sets the wrapper id assertEquals(1, multipleWrapperDao.create(multiWrapper)); MultipleForeignWrapper multiWrapper2 = multipleWrapperDao.queryForId(multiWrapper.id); assertEquals(foreign.id, multiWrapper2.foreign.id); assertNull(multiWrapper2.foreign.stringField); assertEquals(wrapper.id, multiWrapper2.foreignWrapper.id); assertNull(multiWrapper2.foreignWrapper.foreign); assertEquals(1, foreignDao.refresh(multiWrapper2.foreign)); assertEquals(stuff1, multiWrapper2.foreign.stringField); assertNull(multiWrapper2.foreignWrapper.foreign); assertEquals(1, wrapperDao.refresh(multiWrapper2.foreignWrapper)); assertEquals(foreign.id, multiWrapper2.foreignWrapper.foreign.id); assertNull(multiWrapper2.foreignWrapper.foreign.stringField); assertEquals(1, foreignDao.refresh(multiWrapper2.foreignWrapper.foreign)); assertEquals(stuff1, multiWrapper2.foreignWrapper.foreign.stringField); } @Test public void testRefreshNull() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); // this should be a noop assertEquals(0, fooDao.refresh(null)); } @Test public void testGetSet() throws Exception { Dao<GetSet, Integer> getSetDao = createDao(GetSet.class, true); GetSet getSet = new GetSet(); String stuff = "ewfewfewfew343u42f"; getSet.setStuff(stuff); assertEquals(1, getSetDao.create(getSet)); GetSet getSet2 = getSetDao.queryForId(getSet.id); assertEquals(stuff, getSet2.stuff); } @Test public void testQueryForFirst() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); String stuff = "ewf4334234u42f"; QueryBuilder<Foo, Integer> qb = fooDao.queryBuilder(); qb.where().eq(Foo.STUFF_FIELD_NAME, stuff); assertNull(fooDao.queryForFirst(qb.prepare())); Foo foo1 = new Foo(); foo1.stuff = stuff; assertEquals(1, fooDao.create(foo1)); // should still get foo1 Foo foo2 = fooDao.queryForFirst(qb.prepare()); assertEquals(foo1.id, foo2.id); assertEquals(stuff, foo2.stuff); // create another with same stuff Foo foo3 = new Foo(); String stuff2 = "ewf43342wefwffwefwe34u42f"; foo3.stuff = stuff2; assertEquals(1, fooDao.create(foo3)); foo2 = fooDao.queryForFirst(qb.prepare()); assertEquals(foo1.id, foo2.id); assertEquals(stuff, foo2.stuff); } @Test public void testFieldConfig() throws Exception { List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>(); fieldConfigs.add(new DatabaseFieldConfig("id", "id2", DataType.UNKNOWN, null, 0, false, false, true, null, false, null, false, null, false, null, false, null, null, false, 0, 0)); fieldConfigs.add(new DatabaseFieldConfig("stuff", "stuffy", DataType.UNKNOWN, null, 0, false, false, false, null, false, null, false, null, false, null, false, null, null, false, 0, 0)); DatabaseTableConfig<NoAnno> tableConfig = new DatabaseTableConfig<NoAnno>(NoAnno.class, "noanno", fieldConfigs); Dao<NoAnno, Integer> noAnnotaionDao = createDao(tableConfig, true); NoAnno noa = new NoAnno(); String stuff = "qpoqwpjoqwp12"; noa.stuff = stuff; assertEquals(1, noAnnotaionDao.create(noa)); NoAnno noa2 = noAnnotaionDao.queryForId(noa.id); assertEquals(noa.id, noa2.id); assertEquals(stuff, noa2.stuff); } @Test public void testFieldConfigForeign() throws Exception { List<DatabaseFieldConfig> noAnnotationsFieldConfigs = new ArrayList<DatabaseFieldConfig>(); DatabaseFieldConfig field1 = new DatabaseFieldConfig("id"); field1.setColumnName("idthingie"); field1.setGeneratedId(true); noAnnotationsFieldConfigs.add(field1); DatabaseFieldConfig field2 = new DatabaseFieldConfig("stuff"); field2.setColumnName("stuffy"); noAnnotationsFieldConfigs.add(field2); DatabaseTableConfig<NoAnno> noAnnotationsTableConfig = new DatabaseTableConfig<NoAnno>(NoAnno.class, noAnnotationsFieldConfigs); Dao<NoAnno, Integer> noAnnotationDao = createDao(noAnnotationsTableConfig, true); NoAnno noa = new NoAnno(); String stuff = "qpoqwpjoqwp12"; noa.stuff = stuff; assertEquals(1, noAnnotationDao.create(noa)); assertNotNull(noAnnotationDao.queryForId(noa.id)); List<DatabaseFieldConfig> noAnnotationsForiegnFieldConfigs = new ArrayList<DatabaseFieldConfig>(); DatabaseFieldConfig field3 = new DatabaseFieldConfig("id"); field3.setColumnName("anotherid"); field3.setGeneratedId(true); noAnnotationsForiegnFieldConfigs.add(field3); DatabaseFieldConfig field4 = new DatabaseFieldConfig("foreign"); field4.setColumnName("foreignThingie"); field4.setForeign(true); field4.setForeignTableConfig(noAnnotationsTableConfig); noAnnotationsForiegnFieldConfigs.add(field4); DatabaseTableConfig<NoAnnoFor> noAnnotationsForiegnTableConfig = new DatabaseTableConfig<NoAnnoFor>(NoAnnoFor.class, noAnnotationsForiegnFieldConfigs); Dao<NoAnnoFor, Integer> noAnnotaionForeignDao = createDao(noAnnotationsForiegnTableConfig, true); NoAnnoFor noaf = new NoAnnoFor(); noaf.foreign = noa; assertEquals(1, noAnnotaionForeignDao.create(noaf)); NoAnnoFor noaf2 = noAnnotaionForeignDao.queryForId(noaf.id); assertNotNull(noaf2); assertEquals(noaf.id, noaf2.id); assertEquals(noa.id, noaf2.foreign.id); assertNull(noaf2.foreign.stuff); assertEquals(1, noAnnotationDao.refresh(noaf2.foreign)); assertEquals(stuff, noaf2.foreign.stuff); } @Test public void testGeneratedIdNotNull() throws Exception { // we saw an error with the not null before the generated id stuff under hsqldb Dao<GeneratedIdNotNull, Integer> dao = createDao(GeneratedIdNotNull.class, true); assertEquals(1, dao.create(new GeneratedIdNotNull())); } @Test public void testBasicStuff() throws Exception { Dao<Basic, String> fooDao = createDao(Basic.class, true); String string = "s1"; Basic foo1 = new Basic(); foo1.id = string; assertEquals(1, fooDao.create(foo1)); Basic foo2 = fooDao.queryForId(string); assertTrue(fooDao.objectsEqual(foo1, foo2)); List<Basic> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertTrue(fooDao.objectsEqual(foo1, fooList.get(0))); int i = 0; for (Basic foo3 : fooDao) { assertTrue(fooDao.objectsEqual(foo1, foo3)); i++; } assertEquals(1, i); assertEquals(1, fooDao.delete(foo2)); assertNull(fooDao.queryForId(string)); fooList = fooDao.queryForAll(); assertEquals(0, fooList.size()); i = 0; for (Basic foo3 : fooDao) { assertTrue(fooDao.objectsEqual(foo1, foo3)); i++; } assertEquals(0, i); } @Test public void testMultiplePrimaryKey() throws Exception { Dao<Basic, String> fooDao = createDao(Basic.class, true); Basic foo1 = new Basic(); foo1.id = "dup"; assertEquals(1, fooDao.create(foo1)); try { fooDao.create(foo1); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testDefaultValue() throws Exception { Dao<DefaultValue, Object> defValDao = createDao(DefaultValue.class, true); DefaultValue defVal1 = new DefaultValue(); assertEquals(1, defValDao.create(defVal1)); List<DefaultValue> defValList = defValDao.queryForAll(); assertEquals(1, defValList.size()); DefaultValue defVal2 = defValList.get(0); assertEquals(DEFAULT_VALUE, (int) defVal2.intField); } @Test public void testNotNull() throws Exception { Dao<NotNull, Object> defValDao = createDao(NotNull.class, true); NotNull notNull = new NotNull(); try { defValDao.create(notNull); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testNotNullOkay() throws Exception { Dao<NotNull, Object> defValDao = createDao(NotNull.class, true); NotNull notNull = new NotNull(); notNull.notNull = "not null"; assertEquals(1, defValDao.create(notNull)); } @Test public void testGeneratedId() throws Exception { Dao<GeneratedId, Object> genIdDao = createDao(GeneratedId.class, true); GeneratedId genId = new GeneratedId(); assertEquals(0, genId.id); assertEquals(1, genIdDao.create(genId)); long id = genId.id; assertEquals(1, id); GeneratedId genId2 = genIdDao.queryForId(id); assertNotNull(genId2); assertEquals(id, genId2.id); genId = new GeneratedId(); assertEquals(0, genId.id); assertEquals(1, genIdDao.create(genId)); id = genId.id; assertEquals(2, id); genId2 = genIdDao.queryForId(id); assertNotNull(genId2); assertEquals(id, genId2.id); } @Test public void testAllTypes() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); String stringVal = "some string"; boolean boolVal = true; // we have to round this because the db may not be storing millis long millis = (System.currentTimeMillis() / 1000) * 1000; Date dateVal = new Date(millis); Date dateLongVal = new Date(millis); Date dateStringVal = new Date(millis); char charVal = 'w'; byte byteVal = 117; short shortVal = 15217; int intVal = 1023213; long longVal = 1231231231231L; float floatVal = 123.13F; double doubleVal = 1413312.1231233; OurEnum enumVal = OurEnum.FIRST; allTypes.stringField = stringVal; allTypes.booleanField = boolVal; allTypes.dateField = dateVal; allTypes.dateLongField = dateLongVal; allTypes.dateStringField = dateStringVal; allTypes.charField = charVal; allTypes.byteField = byteVal; allTypes.shortField = shortVal; allTypes.intField = intVal; allTypes.longField = longVal; allTypes.floatField = floatVal; allTypes.doubleField = doubleVal; allTypes.enumField = enumVal; allTypes.enumStringField = enumVal; allTypes.enumIntegerField = enumVal; SerialData obj = new SerialData(); String key = "key"; String value = "value"; obj.addEntry(key, value); allTypes.serialField = obj; assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); assertEquals(value, allTypesList.get(0).serialField.map.get(key)); assertEquals(1, allDao.refresh(allTypes)); // queries on all fields QueryBuilder<AllTypes, Integer> qb = allDao.queryBuilder(); checkQueryResult(allDao, qb, allTypes, AllTypes.STRING_FIELD_NAME, stringVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.BOOLEAN_FIELD_NAME, boolVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_FIELD_NAME, dateVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_LONG_FIELD_NAME, dateLongVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.DATE_STRING_FIELD_NAME, dateStringVal, true); if (!databaseType.getDatabaseName().equals("Derby")) { checkQueryResult(allDao, qb, allTypes, AllTypes.CHAR_FIELD_NAME, charVal, true); } checkQueryResult(allDao, qb, allTypes, AllTypes.BYTE_FIELD_NAME, byteVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.SHORT_FIELD_NAME, shortVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.INT_FIELD_NAME, intVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.LONG_FIELD_NAME, longVal, true); // float tested below checkQueryResult(allDao, qb, allTypes, AllTypes.DOUBLE_FIELD_NAME, doubleVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_FIELD_NAME, enumVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_STRING_FIELD_NAME, enumVal, true); checkQueryResult(allDao, qb, allTypes, AllTypes.ENUM_INTEGER_FIELD_NAME, enumVal, true); } /** * This is special because comparing floats may not work as expected. */ @Test public void testAllTypesFloat() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); float floatVal = 123.13F; float floatLowVal = floatVal * 0.9F; float floatHighVal = floatVal * 1.1F; allTypes.floatField = floatVal; assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); assertEquals(1, allDao.refresh(allTypes)); // queries on all fields QueryBuilder<AllTypes, Integer> qb = allDao.queryBuilder(); // float comparisons are not exactly right so we switch to a low -> high query instead if (!checkQueryResult(allDao, qb, allTypes, AllTypes.FLOAT_FIELD_NAME, floatVal, false)) { qb.where().gt(AllTypes.FLOAT_FIELD_NAME, floatLowVal).and().lt(AllTypes.FLOAT_FIELD_NAME, floatHighVal); List<AllTypes> results = allDao.query(qb.prepare()); assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } } @Test public void testAllTypesDefault() throws Exception { Dao<AllTypes, Integer> allDao = createDao(AllTypes.class, true); AllTypes allTypes = new AllTypes(); assertEquals(1, allDao.create(allTypes)); List<AllTypes> allTypesList = allDao.queryForAll(); assertEquals(1, allTypesList.size()); assertTrue(allDao.objectsEqual(allTypes, allTypesList.get(0))); } @Test public void testNumberTypes() throws Exception { Dao<NumberTypes, Integer> numberDao = createDao(NumberTypes.class, true); NumberTypes numberMins = new NumberTypes(); numberMins.byteField = Byte.MIN_VALUE; numberMins.shortField = Short.MIN_VALUE; numberMins.intField = Integer.MIN_VALUE; numberMins.longField = Long.MIN_VALUE; numberMins.floatField = -1.0e+37F; numberMins.doubleField = -1.0e+307; assertEquals(1, numberDao.create(numberMins)); NumberTypes numberMins2 = new NumberTypes(); numberMins2.byteField = Byte.MIN_VALUE; numberMins2.shortField = Short.MIN_VALUE; numberMins2.intField = Integer.MIN_VALUE; numberMins2.longField = Long.MIN_VALUE; numberMins2.floatField = 1.0e-37F; // derby couldn't take 1.0e-307 for some reason numberMins2.doubleField = 1.0e-306; assertEquals(1, numberDao.create(numberMins2)); NumberTypes numberMaxs = new NumberTypes(); numberMaxs.byteField = Byte.MAX_VALUE; numberMaxs.shortField = Short.MAX_VALUE; numberMaxs.intField = Integer.MAX_VALUE; numberMaxs.longField = Long.MAX_VALUE; numberMaxs.floatField = 1.0e+37F; numberMaxs.doubleField = 1.0e+307; assertEquals(1, numberDao.create(numberMaxs)); assertEquals(1, numberDao.refresh(numberMaxs)); List<NumberTypes> allTypesList = numberDao.queryForAll(); assertEquals(3, allTypesList.size()); assertTrue(numberDao.objectsEqual(numberMins, allTypesList.get(0))); assertTrue(numberDao.objectsEqual(numberMins2, allTypesList.get(1))); assertTrue(numberDao.objectsEqual(numberMaxs, allTypesList.get(2))); } @Test public void testStringWidthTooLong() throws Exception { if (connectionSource == null) { return; } if (!connectionSource.getDatabaseType().isVarcharFieldWidthSupported()) { return; } Dao<StringWidth, Object> stringWidthDao = createDao(StringWidth.class, true); StringWidth stringWidth = new StringWidth(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ALL_TYPES_STRING_WIDTH + 1; i++) { sb.append("c"); } String string = sb.toString(); assertTrue(string.length() > ALL_TYPES_STRING_WIDTH); stringWidth.stringField = string; try { stringWidthDao.create(stringWidth); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testStringWidthOkay() throws Exception { Dao<StringWidth, Object> stringWidthDao = createDao(StringWidth.class, true); StringWidth stringWidth = new StringWidth(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ALL_TYPES_STRING_WIDTH; i++) { sb.append("c"); } String string = sb.toString(); assertTrue(string.length() == ALL_TYPES_STRING_WIDTH); stringWidth.stringField = string; assertEquals(1, stringWidthDao.create(stringWidth)); List<StringWidth> stringWidthList = stringWidthDao.queryForAll(); assertEquals(1, stringWidthList.size()); assertTrue(stringWidthDao.objectsEqual(stringWidth, stringWidthList.get(0))); } @Test public void testCreateReserverdTable() throws Exception { Dao<Create, String> whereDao = createDao(Create.class, true); String id = "from-string"; Create where = new Create(); where.id = id; assertEquals(1, whereDao.create(where)); Create where2 = whereDao.queryForId(id); assertEquals(id, where2.id); assertEquals(1, whereDao.delete(where2)); assertNull(whereDao.queryForId(id)); } @Test public void testCreateReserverdFields() throws Exception { Dao<ReservedField, Object> reservedDao = createDao(ReservedField.class, true); String from = "from-string"; ReservedField res = new ReservedField(); res.from = from; assertEquals(1, reservedDao.create(res)); int id = res.select; ReservedField res2 = reservedDao.queryForId(id); assertNotNull(res2); assertEquals(id, res2.select); String group = "group-string"; for (ReservedField reserved : reservedDao) { assertEquals(from, reserved.from); reserved.group = group; reservedDao.update(reserved); } Iterator<ReservedField> reservedIterator = reservedDao.iterator(); while (reservedIterator.hasNext()) { ReservedField reserved = reservedIterator.next(); assertEquals(from, reserved.from); assertEquals(group, reserved.group); reservedIterator.remove(); } assertEquals(0, reservedDao.queryForAll().size()); } @Test public void testEscapeCharInField() throws Exception { if (connectionSource == null) { return; } StringBuilder sb = new StringBuilder(); String word = "foo"; connectionSource.getDatabaseType().appendEscapedWord(sb, word); String escaped = sb.toString(); int index = escaped.indexOf(word); String escapeString = escaped.substring(0, index); Dao<Basic, String> fooDao = createDao(Basic.class, true); Basic foo1 = new Basic(); String id = word + escapeString + word; foo1.id = id; assertEquals(1, fooDao.create(foo1)); Basic foo2 = fooDao.queryForId(id); assertNotNull(foo2); assertEquals(id, foo2.id); } @Test public void testGeneratedIdCapital() throws Exception { createDao(GeneratedColumnCapital.class, true); } @Test public void testObject() throws Exception { Dao<ObjectHolder, Integer> objDao = createDao(ObjectHolder.class, true); ObjectHolder foo1 = new ObjectHolder(); foo1.obj = new SerialData(); String key = "key2"; String value = "val2"; foo1.obj.addEntry(key, value); String strObj = "fjpwefefwpjoefwjpojopfew"; foo1.strObj = strObj; assertEquals(1, objDao.create(foo1)); ObjectHolder foo2 = objDao.queryForId(foo1.id); assertTrue(objDao.objectsEqual(foo1, foo2)); } @Test public void testNotSerializable() throws Exception { try { createDao(NotSerializable.class, true); fail("expected exception"); } catch (IllegalArgumentException e) { // expected } } @Test public void testStringEnum() throws Exception { Dao<LocalEnumString, Object> fooDao = createDao(LocalEnumString.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumString foo = new LocalEnumString(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); List<LocalEnumString> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(ourEnum, fooList.get(0).ourEnum); } @Test public void testUnknownStringEnum() throws Exception { Dao<LocalEnumString, Object> fooDao = createDao(LocalEnumString.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumString foo = new LocalEnumString(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumString2, Object> foo2Dao = createDao(LocalEnumString2.class, false); try { foo2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testIntEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); List<LocalEnumInt> fooList = fooDao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(ourEnum, fooList.get(0).ourEnum); } @Test public void testUnknownIntEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumInt2, Object> foo2Dao = createDao(LocalEnumInt2.class, false); try { foo2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testUnknownIntUnknownValEnum() throws Exception { Dao<LocalEnumInt, Object> fooDao = createDao(LocalEnumInt.class, true); OurEnum ourEnum = OurEnum.SECOND; LocalEnumInt foo = new LocalEnumInt(); foo.ourEnum = ourEnum; assertEquals(1, fooDao.create(foo)); Dao<LocalEnumInt3, Object> foo2Dao = createDao(LocalEnumInt3.class, false); List<LocalEnumInt3> fooList = foo2Dao.queryForAll(); assertEquals(1, fooList.size()); assertEquals(OurEnum2.FIRST, fooList.get(0).ourEnum); } @Test public void testNullHandling() throws Exception { Dao<AllObjectTypes, Object> allDao = createDao(AllObjectTypes.class, true); AllObjectTypes all = new AllObjectTypes(); assertEquals(1, allDao.create(all)); List<AllObjectTypes> allList = allDao.queryForAll(); assertEquals(1, allList.size()); assertTrue(allDao.objectsEqual(all, allList.get(0))); } @Test public void testObjectNotNullHandling() throws Exception { Dao<AllObjectTypes, Object> allDao = createDao(AllObjectTypes.class, true); AllObjectTypes all = new AllObjectTypes(); all.stringField = "foo"; all.booleanField = false; Date dateValue = new Date(1279649192000L); all.dateField = dateValue; all.byteField = 0; all.shortField = 0; all.intField = 0; all.longField = 0L; all.floatField = 0F; all.doubleField = 0D; all.objectField = new SerialData(); all.ourEnum = OurEnum.FIRST; assertEquals(1, allDao.create(all)); assertEquals(1, allDao.refresh(all)); List<AllObjectTypes> allList = allDao.queryForAll(); assertEquals(1, allList.size()); assertTrue(allDao.objectsEqual(all, allList.get(0))); } @Test public void testDefaultValueHandling() throws Exception { Dao<AllTypesDefault, Object> allDao = createDao(AllTypesDefault.class, true); AllTypesDefault all = new AllTypesDefault(); assertEquals(1, allDao.create(all)); assertEquals(1, allDao.refresh(all)); List<AllTypesDefault> allList = allDao.queryForAll(); assertEquals(1, allList.size()); all.stringField = DEFAULT_STRING_VALUE; DateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); all.dateField = defaultDateFormat.parse(DEFAULT_DATE_VALUE); all.dateLongField = new Date(Long.parseLong(DEFAULT_DATE_LONG_VALUE)); DateFormat defaultDateStringFormat = new SimpleDateFormat(DEFAULT_DATE_STRING_FORMAT); all.dateStringField = defaultDateStringFormat.parse(DEFAULT_DATE_STRING_VALUE); all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.byteField = Byte.parseByte(DEFAULT_BYTE_VALUE); all.byteObj = Byte.parseByte(DEFAULT_BYTE_VALUE); all.shortField = Short.parseShort(DEFAULT_SHORT_VALUE); all.shortObj = Short.parseShort(DEFAULT_SHORT_VALUE); all.intField = Integer.parseInt(DEFAULT_INT_VALUE); all.intObj = Integer.parseInt(DEFAULT_INT_VALUE); all.longField = Long.parseLong(DEFAULT_LONG_VALUE); all.longObj = Long.parseLong(DEFAULT_LONG_VALUE); all.floatField = Float.parseFloat(DEFAULT_FLOAT_VALUE); all.floatObj = Float.parseFloat(DEFAULT_FLOAT_VALUE); all.doubleField = Double.parseDouble(DEFAULT_DOUBLE_VALUE); all.doubleObj = Double.parseDouble(DEFAULT_DOUBLE_VALUE); all.ourEnum = OurEnum.valueOf(DEFAULT_ENUM_VALUE); assertFalse(allDao.objectsEqual(all, allList.get(0))); } @Test public void testBooleanDefaultValueHandling() throws Exception { Dao<BooleanDefault, Object> allDao = createDao(BooleanDefault.class, true); BooleanDefault all = new BooleanDefault(); assertEquals(1, allDao.create(all)); List<BooleanDefault> allList = allDao.queryForAll(); assertEquals(1, allList.size()); all.booleanField = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); all.booleanObj = Boolean.parseBoolean(DEFAULT_BOOLEAN_VALUE); assertFalse(allDao.objectsEqual(all, allList.get(0))); } @Test public void testNullUnPersistToBooleanPrimitive() throws Exception { Dao<NullBoolean1, Object> null1Dao = createDao(NullBoolean1.class, true); NullBoolean1 nullThing = new NullBoolean1(); assertEquals(1, null1Dao.create(nullThing)); Dao<NullBoolean2, Object> null2Dao = createDao(NullBoolean2.class, false); try { null2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testNullUnPersistToIntPrimitive() throws Exception { Dao<NullInt1, Object> null1Dao = createDao(NullInt1.class, true); NullInt1 nullThing = new NullInt1(); assertEquals(1, null1Dao.create(nullThing)); Dao<NullInt2, Object> null2Dao = createDao(NullInt2.class, false); try { null2Dao.queryForAll(); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testQueryRawStrings() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; foo.stuff = stuff; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<String[]> results = fooDao.queryRaw(queryString); assertEquals(0, results.getResults().size()); assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); boolean gotId = false; boolean gotStuff = false; boolean gotVal = false; // all this crap is here because of android column order for (int colC = 0; colC < 3; colC++) { if (colNames[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { gotId = true; } else if (colNames[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { gotStuff = true; } else if (colNames[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { gotVal = true; } } assertTrue(gotId); assertTrue(gotStuff); assertTrue(gotVal); List<String[]> resultList = results.getResults(); assertEquals(1, resultList.size()); String[] result = resultList.get(0); assertEquals(colN, result.length); for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (results.getColumnNames()[colC] == "id") { assertEquals(Integer.toString(foo.id), result[colC]); } if (results.getColumnNames()[colC] == "stuff") { assertEquals(stuff, result[1]); } } } @Test public void testQueryRawStringsIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; int val = 12321411; foo.stuff = stuff; foo.val = val; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<String[]> results = fooDao.queryRaw(queryString); CloseableIterator<String[]> iterator = results.closeableIterator(); try { assertFalse(iterator.hasNext()); } finally { iterator.close(); } assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); String[] result = iterator.next(); assertEquals(colN, result.length); boolean foundId = false; boolean foundStuff = false; boolean foundVal = false; for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { assertEquals(Integer.toString(foo.id), result[colC]); foundId = true; } if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { assertEquals(stuff, result[colC]); foundStuff = true; } if (results.getColumnNames()[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { assertEquals(Integer.toString(val), result[colC]); foundVal = true; } } assertTrue(foundId); assertTrue(foundStuff); assertTrue(foundVal); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } @Test public void testQueryRawMappedIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); final Foo foo = new Foo(); String stuff = "eprjpejrre"; foo.stuff = stuff; String queryString = buildFooQueryAllString(fooDao); Mapper mapper = new Mapper(); GenericRawResults<Foo> rawResults = fooDao.queryRaw(queryString, mapper); assertEquals(0, rawResults.getResults().size()); assertEquals(1, fooDao.create(foo)); rawResults = fooDao.queryRaw(queryString, mapper); Iterator<Foo> iterator = rawResults.iterator(); assertTrue(iterator.hasNext()); Foo foo2 = iterator.next(); assertEquals(foo.id, foo2.id); assertEquals(foo.stuff, foo2.stuff); assertEquals(foo.val, foo2.val); assertFalse(iterator.hasNext()); } @Test public void testQueryRawObjectsIterator() throws Exception { Dao<Foo, Object> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "eprjpejrre"; int val = 213123; foo.stuff = stuff; foo.val = val; String queryString = buildFooQueryAllString(fooDao); GenericRawResults<Object[]> results = fooDao.queryRaw(queryString, new DataType[] { DataType.INTEGER, DataType.STRING, DataType.INTEGER }); CloseableIterator<Object[]> iterator = results.closeableIterator(); try { assertFalse(iterator.hasNext()); } finally { iterator.close(); } assertEquals(1, fooDao.create(foo)); results = fooDao.queryRaw(queryString, new DataType[] { DataType.INTEGER, DataType.STRING, DataType.INTEGER }); int colN = results.getNumberColumns(); String[] colNames = results.getColumnNames(); assertEquals(3, colNames.length); iterator = results.closeableIterator(); try { assertTrue(iterator.hasNext()); Object[] result = iterator.next(); assertEquals(colN, result.length); String[] columnNames = results.getColumnNames(); boolean foundId = false; boolean foundStuff = false; boolean foundVal = false; for (int colC = 0; colC < results.getNumberColumns(); colC++) { if (columnNames[colC].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { assertEquals(foo.id, result[colC]); foundId = true; } if (columnNames[colC].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { assertEquals(stuff, result[colC]); foundStuff = true; } if (columnNames[colC].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { assertEquals(val, result[colC]); foundVal = true; } } assertTrue(foundId); assertTrue(foundStuff); assertTrue(foundVal); assertFalse(iterator.hasNext()); } finally { iterator.close(); } } @Test public void testNotNullDefault() throws Exception { Dao<NotNullDefault, Object> dao = createDao(NotNullDefault.class, true); NotNullDefault notNullDefault = new NotNullDefault(); assertEquals(1, dao.create(notNullDefault)); } @Test public void testStringDefault() throws Exception { Dao<StringDefalt, Object> dao = createDao(StringDefalt.class, true); StringDefalt foo = new StringDefalt(); assertEquals(1, dao.create(foo)); } @Test public void testDateUpdate() throws Exception { Dao<LocalDate, Object> dao = createDao(LocalDate.class, true); LocalDate localDate = new LocalDate(); // note: this does not have milliseconds Date date = new Date(2131232000); localDate.date = date; assertEquals(1, dao.create(localDate)); List<LocalDate> allDates = dao.queryForAll(); assertEquals(1, allDates.size()); assertEquals(date, allDates.get(0).date); // now we update it assertEquals(1, dao.update(localDate)); allDates = dao.queryForAll(); assertEquals(1, allDates.size()); assertEquals(date, allDates.get(0).date); // now we set it to null localDate.date = null; // now we update it assertEquals(1, dao.update(localDate)); allDates = dao.queryForAll(); assertEquals(1, allDates.size()); // we should get null back and not some auto generated field assertNull(allDates.get(0).date); } @Test public void testDateRefresh() throws Exception { Dao<LocalDate, Object> dao = createDao(LocalDate.class, true); LocalDate localDate = new LocalDate(); // note: this does not have milliseconds Date date = new Date(2131232000); localDate.date = date; assertEquals(1, dao.create(localDate)); assertEquals(1, dao.refresh(localDate)); } @Test public void testSpringBadWiring() throws Exception { BaseDaoImpl<String, String> daoSupport = new BaseDaoImpl<String, String>(String.class) { }; try { daoSupport.initialize(); fail("expected exception"); } catch (IllegalStateException e) { // expected } } @Test public void testUnique() throws Exception { Dao<Unique, Long> dao = createDao(Unique.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; Unique unique = new Unique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new Unique(); unique.stuff = stuff; assertEquals(1, dao.create(unique)); unique = new Unique(); unique.uniqueStuff = uniqueStuff; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testDoubleUnique() throws Exception { Dao<DoubleUnique, Long> dao = createDao(DoubleUnique.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; DoubleUnique unique = new DoubleUnique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new DoubleUnique(); unique.stuff = stuff; try { // either 1st field can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } unique = new DoubleUnique(); unique.uniqueStuff = uniqueStuff; try { // nor 2nd field can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } unique = new DoubleUnique(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; try { // nor both fields can't be unique dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testDoubleUniqueCombo() throws Exception { Dao<DoubleUniqueCombo, Long> dao = createDao(DoubleUniqueCombo.class, true); String stuff = "this doesn't need to be unique"; String uniqueStuff = "this needs to be unique"; DoubleUniqueCombo unique = new DoubleUniqueCombo(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new DoubleUniqueCombo(); unique.stuff = stuff; assertEquals(1, dao.create(unique)); unique = new DoubleUniqueCombo(); unique.uniqueStuff = uniqueStuff; assertEquals(1, dao.create(unique)); unique = new DoubleUniqueCombo(); unique.stuff = stuff; unique.uniqueStuff = uniqueStuff; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testUniqueAndUniqueCombo() throws Exception { Dao<UniqueAndUniqueCombo, Long> dao = createDao(UniqueAndUniqueCombo.class, true); String unique1 = "unique but not combo"; String combo1 = "combo unique"; String combo2 = "another combo unique"; UniqueAndUniqueCombo unique = new UniqueAndUniqueCombo(); unique.unique1 = unique1; assertEquals(1, dao.create(unique)); // can't create it twice with the same stuff which needs to be unique unique = new UniqueAndUniqueCombo(); unique.unique1 = unique1; try { dao.create(unique); fail("this should throw"); } catch (Exception e) { // expected } unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = combo2; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = unique1; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = unique1; unique.combo2 = combo2; assertEquals(1, dao.create(unique)); unique = new UniqueAndUniqueCombo(); unique.combo1 = combo1; unique.combo2 = combo2; try { dao.create(unique); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testForeignQuery() throws Exception { Dao<ForeignWrapper, Integer> wrapperDao = createDao(ForeignWrapper.class, true); Dao<AllTypes, Integer> foreignDao = createDao(AllTypes.class, true); AllTypes foreign = new AllTypes(); String stuff1 = "stuff1"; foreign.stringField = stuff1; Date date = new Date(); foreign.dateField = date; // this sets the foreign id assertEquals(1, foreignDao.create(foreign)); ForeignWrapper wrapper = new ForeignWrapper(); wrapper.foreign = foreign; // this sets the wrapper id assertEquals(1, wrapperDao.create(wrapper)); QueryBuilder<ForeignWrapper, Integer> qb = wrapperDao.queryBuilder(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, foreign.id); List<ForeignWrapper> results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * now look it up not by foreign.id but by foreign which should extract the id automagically */ qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, foreign); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * Now let's try the same thing but with a SelectArg */ SelectArg selectArg = new SelectArg(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, selectArg); selectArg.setValue(foreign.id); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); /* * Now let's try the same thing but with a SelectArg with foreign value, not foreign.id */ selectArg = new SelectArg(); qb.where().eq(ForeignWrapper.FOREIGN_FIELD_NAME, selectArg); selectArg.setValue(foreign); results = wrapperDao.query(qb.prepare()); assertEquals(1, results.size()); assertNotNull(results.get(0).foreign); assertEquals(foreign.id, results.get(0).foreign.id); } @Test public void testPrepareStatementUpdateValueString() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); String stuff = "dqedqdq"; foo.stuff = stuff; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.STUFF_FIELD_NAME, stuff); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String newStuff = "fepojefpjo"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, newStuff); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.query(stmtb.prepare()); assertEquals(0, results.size()); } @Test public void testInSubQuery() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Basic, String> basicDao = createDao(Basic.class, true); Basic basic1 = new Basic(); String string1 = "ewpofjewgprgrg"; basic1.id = string1; assertEquals(1, basicDao.create(basic1)); Basic basic2 = new Basic(); String string2 = "e2432423432wpofjewgprgrg"; basic2.id = string2; assertEquals(1, basicDao.create(basic2)); Foo foo1 = new Foo(); foo1.stuff = basic1.id; Foo foo2 = new Foo(); foo2.stuff = basic2.id; Foo foo3 = new Foo(); String string3 = "neither of the others"; foo3.stuff = string3; int num1 = 7; for (int i = 0; i < num1; i++) { assertEquals(1, fooDao.create(foo1)); } int num2 = 17; for (int i = 0; i < num2; i++) { assertEquals(1, fooDao.create(foo2)); } int num3 = 29; long maxId = 0; for (int i = 0; i < num3; i++) { assertEquals(1, fooDao.create(foo3)); if (foo3.id > maxId) { maxId = foo3.id; } } QueryBuilder<Basic, String> bqb = basicDao.queryBuilder(); bqb.selectColumns(Basic.ID_FIELD); // string1 bqb.where().eq(Basic.ID_FIELD, string1); List<Foo> results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1, results.size()); // string2 bqb.where().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num2, results.size()); // ! string2 with not().in(...) bqb.where().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().not().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num3, results.size()); // string3 which there should be none bqb.where().eq(Basic.ID_FIELD, string3); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(0, results.size()); // string1 OR string2 bqb.where().eq(Basic.ID_FIELD, string1).or().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num2, results.size()); // all strings IN bqb.where().in(Basic.ID_FIELD, string1, string2, string3); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(num1 + num2, results.size()); // string1 AND string2 which there should be none bqb.where().eq(Basic.ID_FIELD, string1).and().eq(Basic.ID_FIELD, string2); results = fooDao.query(fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).prepare()); assertEquals(0, results.size()); } @Test public void testInSubQuerySelectArgs() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Dao<Basic, String> basicDao = createDao(Basic.class, true); Basic basic1 = new Basic(); String string1 = "ewpofjewgprgrg"; basic1.id = string1; assertEquals(1, basicDao.create(basic1)); Basic basic2 = new Basic(); String string2 = "e2432423432wpofjewgprgrg"; basic2.id = string2; assertEquals(1, basicDao.create(basic2)); Foo foo1 = new Foo(); foo1.stuff = basic1.id; Foo foo2 = new Foo(); foo2.stuff = basic2.id; int num1 = 7; for (int i = 0; i < num1; i++) { assertEquals(1, fooDao.create(foo1)); } int num2 = 17; long maxId = 0; for (int i = 0; i < num2; i++) { assertEquals(1, fooDao.create(foo2)); if (foo2.id > maxId) { maxId = foo2.id; } } // using seletArgs SelectArg arg1 = new SelectArg(); SelectArg arg2 = new SelectArg(); QueryBuilder<Basic, String> bqb = basicDao.queryBuilder(); bqb.selectColumns(Basic.ID_FIELD); bqb.where().eq(Basic.ID_FIELD, arg1); PreparedQuery<Foo> preparedQuery = fooDao.queryBuilder().where().in(Foo.STUFF_FIELD_NAME, bqb).and().lt(Foo.ID_FIELD_NAME, arg2).prepare(); arg1.setValue(string1); // this should get none arg2.setValue(0); List<Foo> results = fooDao.query(preparedQuery); assertEquals(0, results.size()); } @Test public void testPrepareStatementUpdateValueNumber() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); foo.val = 123213; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.ID_FIELD_NAME, foo.id); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); updateb.updateColumnValue(Foo.VAL_FIELD_NAME, foo.val + 1); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); assertEquals(foo.val + 1, results.get(0).val); } @Test public void testPrepareStatementUpdateValueExpression() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo = new Foo(); foo.val = 123213; assertEquals(1, fooDao.create(foo)); QueryBuilder<Foo, Integer> stmtb = fooDao.queryBuilder(); stmtb.where().eq(Foo.ID_FIELD_NAME, foo.id); List<Foo> results = fooDao.query(stmtb.prepare()); assertEquals(1, results.size()); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String stuff = "deopdjq"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, stuff); StringBuilder sb = new StringBuilder(); updateb.escapeColumnName(sb, Foo.VAL_FIELD_NAME); sb.append("+ 1"); updateb.updateColumnExpression(Foo.VAL_FIELD_NAME, sb.toString()); assertEquals(1, fooDao.update(updateb.prepare())); results = fooDao.queryForAll(); assertEquals(1, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(foo.val + 1, results.get(0).val); } @Test public void testPrepareStatementUpdateValueWhere() throws Exception { Dao<Foo, Integer> fooDao = createDao(Foo.class, true); Foo foo1 = new Foo(); foo1.val = 78582351; assertEquals(1, fooDao.create(foo1)); Foo foo2 = new Foo(); String stuff = "eopqjdepodje"; foo2.stuff = stuff; foo2.val = 123344131; assertEquals(1, fooDao.create(foo2)); UpdateBuilder<Foo, Integer> updateb = fooDao.updateBuilder(); String newStuff = "deopdjq"; updateb.updateColumnValue(Foo.STUFF_FIELD_NAME, newStuff); StringBuilder sb = new StringBuilder(); updateb.escapeColumnName(sb, Foo.VAL_FIELD_NAME); sb.append("+ 1"); updateb.updateColumnExpression(Foo.VAL_FIELD_NAME, sb.toString()); updateb.where().eq(Foo.ID_FIELD_NAME, foo2.id); assertEquals(1, fooDao.update(updateb.prepare())); List<Foo> results = fooDao.queryForAll(); assertEquals(2, results.size()); Foo foo = results.get(0); assertEquals(foo1.id, foo.id); assertEquals(foo1.val, foo.val); assertNull(foo.stuff); foo = results.get(1); assertEquals(foo2.id, foo.id); assertEquals(foo2.val + 1, foo.val); assertEquals(newStuff, foo.stuff); } @Test public void testStringAsId() throws Exception { checkTypeAsId(StringId.class, "foo", "bar"); } @Test public void testLongStringAsId() throws Exception { try { createDao(LongStringId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testBooleanAsId() throws Exception { try { createDao(BooleanId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testBooleanObjAsId() throws Exception { try { createDao(BooleanObjId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testDateAsId() throws Exception { // no milliseconds checkTypeAsId(DateId.class, new Date(1232312313000L), new Date(1232312783000L)); } @Test public void testDateLongAsId() throws Exception { // no milliseconds checkTypeAsId(DateLongId.class, new Date(1232312313000L), new Date(1232312783000L)); } @Test public void testDateStringAsId() throws Exception { // no milliseconds checkTypeAsId(DateStringId.class, new Date(1232312313000L), new Date(1232312783000L)); } @Test public void testByteAsId() throws Exception { checkTypeAsId(ByteId.class, (byte) 1, (byte) 2); } @Test public void testByteObjAsId() throws Exception { checkTypeAsId(ByteObjId.class, (byte) 1, (byte) 2); } @Test public void testShortAsId() throws Exception { checkTypeAsId(ShortId.class, (short) 1, (short) 2); } @Test public void testShortObjAsId() throws Exception { checkTypeAsId(ShortObjId.class, (short) 1, (short) 2); } @Test public void testIntAsId() throws Exception { checkTypeAsId(IntId.class, (int) 1, (int) 2); } @Test public void testIntObjAsId() throws Exception { checkTypeAsId(IntObjId.class, (int) 1, (int) 2); } @Test public void testLongAsId() throws Exception { checkTypeAsId(LongId.class, (long) 1, (long) 2); } @Test public void testLongObjAsId() throws Exception { checkTypeAsId(LongObjId.class, (long) 1, (long) 2); } @Test public void testFloatAsId() throws Exception { checkTypeAsId(FloatId.class, (float) 1, (float) 2); } @Test public void testFloatObjAsId() throws Exception { checkTypeAsId(FloatObjId.class, (float) 1, (float) 2); } @Test public void testDoubleAsId() throws Exception { checkTypeAsId(DoubleId.class, (double) 1, (double) 2); } @Test public void testDoubleObjAsId() throws Exception { checkTypeAsId(DoubleObjId.class, (double) 1, (double) 2); } @Test public void testEnumAsId() throws Exception { checkTypeAsId(EnumId.class, OurEnum.SECOND, OurEnum.FIRST); } @Test public void testEnumStringAsId() throws Exception { checkTypeAsId(EnumStringId.class, OurEnum.SECOND, OurEnum.FIRST); } @Test public void testEnumIntegerAsId() throws Exception { checkTypeAsId(EnumIntegerId.class, OurEnum.SECOND, OurEnum.FIRST); } @Test public void testSerializableAsId() throws Exception { try { createDao(SerializableId.class, true); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testRecursiveForeign() throws Exception { Dao<Recursive, Integer> recursiveDao = createDao(Recursive.class, true); Recursive recursive1 = new Recursive(); Recursive recursive2 = new Recursive(); recursive2.foreign = recursive1; assertEquals(recursiveDao.create(recursive1), 1); assertEquals(recursiveDao.create(recursive2), 1); Recursive recursive3 = recursiveDao.queryForId(recursive2.id); assertNotNull(recursive3); assertEquals(recursive1.id, recursive3.foreign.id); } @Test public void testSerializableWhere() throws Exception { Dao<AllTypes, Object> allDao = createDao(AllTypes.class, true); try { // can't query for a serial field allDao.queryBuilder().where().eq(AllTypes.SERIAL_FIELD_NAME, new SelectArg()); fail("expected exception"); } catch (SQLException e) { // expected } } @Test public void testSerializedBytes() throws Exception { Dao<SerializedBytes, Integer> dao = createDao(SerializedBytes.class, true); SerializedBytes serial = new SerializedBytes(); serial.bytes = new byte[] { 1, 25, 3, 124, 10 }; assertEquals(1, dao.create(serial)); SerializedBytes raw2 = dao.queryForId(serial.id); assertNotNull(raw2); assertEquals(serial.id, raw2.id); assertTrue(Arrays.equals(serial.bytes, raw2.bytes)); } @Test public void testByteArray() throws Exception { Dao<ByteArray, Integer> dao = createDao(ByteArray.class, true); ByteArray foo = new ByteArray(); foo.bytes = new byte[] { 17, 25, 3, 124, 0, 127, 10 }; assertEquals(1, dao.create(foo)); ByteArray raw2 = dao.queryForId(foo.id); assertNotNull(raw2); assertEquals(foo.id, raw2.id); assertTrue(Arrays.equals(foo.bytes, raw2.bytes)); } @Test public void testSuperClassAnnotations() throws Exception { Dao<Sub, Integer> dao = createDao(Sub.class, true); Sub sub1 = new Sub(); String stuff = "doepqjdpqdq"; sub1.stuff = stuff; assertEquals(1, dao.create(sub1)); Sub sub2 = dao.queryForId(sub1.id); assertNotNull(sub2); assertEquals(sub1.id, sub2.id); assertEquals(sub1.stuff, sub2.stuff); } @Test public void testFieldIndex() throws Exception { Dao<Index, Integer> dao = createDao(Index.class, true); Index index1 = new Index(); String stuff = "doepqjdpqdq"; index1.stuff = stuff; assertEquals(1, dao.create(index1)); Index index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); // this should work assertEquals(1, dao.create(index1)); PreparedQuery<Index> query = dao.queryBuilder().where().eq("stuff", index1.stuff).prepare(); List<Index> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(stuff, results.get(1).stuff); } @Test public void testFieldIndexColumnName() throws Exception { Dao<IndexColumnName, Integer> dao = createDao(IndexColumnName.class, true); IndexColumnName index1 = new IndexColumnName(); String stuff = "doepqjdpqdq"; index1.stuff = stuff; assertEquals(1, dao.create(index1)); IndexColumnName index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); // this should work assertEquals(1, dao.create(index1)); PreparedQuery<IndexColumnName> query = dao.queryBuilder().where().eq(IndexColumnName.STUFF_COLUMN_NAME, index1.stuff).prepare(); List<IndexColumnName> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(stuff, results.get(1).stuff); } @Test public void testFieldUniqueIndex() throws Exception { Dao<UniqueIndex, Integer> dao = createDao(UniqueIndex.class, true); UniqueIndex index1 = new UniqueIndex(); String stuff1 = "doepqjdpqdq"; index1.stuff = stuff1; assertEquals(1, dao.create(index1)); UniqueIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff1, index2.stuff); try { dao.create(index1); fail("This should have thrown"); } catch (SQLException e) { // expected } String stuff2 = "fewofwgwgwee"; index1.stuff = stuff2; assertEquals(1, dao.create(index1)); PreparedQuery<UniqueIndex> query = dao.queryBuilder().where().eq("stuff", stuff1).prepare(); List<UniqueIndex> results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff1, results.get(0).stuff); query = dao.queryBuilder().where().eq("stuff", stuff2).prepare(); results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff2, results.get(0).stuff); } @Test public void testComboFieldIndex() throws Exception { Dao<ComboIndex, Integer> dao = createDao(ComboIndex.class, true); ComboIndex index1 = new ComboIndex(); String stuff = "doepqjdpqdq"; long junk1 = 131234124213213L; index1.stuff = stuff; index1.junk = junk1; assertEquals(1, dao.create(index1)); ComboIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(stuff, index2.stuff); assertEquals(junk1, index2.junk); assertEquals(1, dao.create(index1)); PreparedQuery<ComboIndex> query = dao.queryBuilder().where().eq("stuff", index1.stuff).prepare(); List<ComboIndex> results = dao.query(query); assertNotNull(results); assertEquals(2, results.size()); assertEquals(stuff, results.get(0).stuff); assertEquals(junk1, results.get(0).junk); assertEquals(stuff, results.get(1).stuff); assertEquals(junk1, results.get(1).junk); } @Test public void testComboUniqueFieldIndex() throws Exception { Dao<ComboUniqueIndex, Integer> dao = createDao(ComboUniqueIndex.class, true); ComboUniqueIndex index1 = new ComboUniqueIndex(); String stuff1 = "doepqjdpqdq"; long junk = 131234124213213L; index1.stuff = stuff1; index1.junk = junk; assertEquals(1, dao.create(index1)); ComboUniqueIndex index2 = dao.queryForId(index1.id); assertNotNull(index2); assertEquals(index1.id, index2.id); assertEquals(index1.stuff, index2.stuff); assertEquals(index1.junk, index2.junk); try { dao.create(index1); fail("This should have thrown"); } catch (SQLException e) { // expected } String stuff2 = "fpeowjfewpf"; index1.stuff = stuff2; // same junk assertEquals(1, dao.create(index1)); PreparedQuery<ComboUniqueIndex> query = dao.queryBuilder().where().eq("stuff", stuff1).prepare(); List<ComboUniqueIndex> results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff1, results.get(0).stuff); assertEquals(junk, results.get(0).junk); query = dao.queryBuilder().where().eq("stuff", stuff2).prepare(); results = dao.query(query); assertNotNull(results); assertEquals(1, results.size()); assertEquals(stuff2, results.get(0).stuff); assertEquals(junk, results.get(0).junk); } @Test public void testLongVarChar() throws Exception { Dao<LongVarChar, Integer> dao = createDao(LongVarChar.class, true); LongVarChar lvc = new LongVarChar(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10240; i++) { sb.append("."); } String stuff = sb.toString(); lvc.stuff = stuff; assertEquals(1, dao.create(lvc)); LongVarChar lvc2 = dao.queryForId(lvc.id); assertNotNull(lvc2); assertEquals(stuff, lvc2.stuff); } @Test public void testTableExists() throws Exception { if (!isTableExistsWorks()) { return; } Dao<Foo, Integer> dao = createDao(Foo.class, false); assertFalse(dao.isTableExists()); TableUtils.createTable(connectionSource, Foo.class); assertTrue(dao.isTableExists()); TableUtils.dropTable(connectionSource, Foo.class, false); assertFalse(dao.isTableExists()); } @Test public void testRaw() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); Foo foo = new Foo(); int val = 131265312; foo.val = val; assertEquals(1, dao.create(foo)); StringBuilder sb = new StringBuilder(); databaseType.appendEscapedEntityName(sb, Foo.VAL_FIELD_NAME); String fieldName = sb.toString(); QueryBuilder<Foo, Integer> qb = dao.queryBuilder(); qb.where().eq(Foo.ID_FIELD_NAME, foo.id).and().raw(fieldName + " = " + val); assertEquals(1, dao.query(qb.prepare()).size()); qb.where().eq(Foo.ID_FIELD_NAME, foo.id).and().raw(fieldName + " != " + val); assertEquals(0, dao.query(qb.prepare()).size()); } @Test public void testUuidInsertQuery() throws Exception { Dao<UuidGeneratedId, UUID> dao = createDao(UuidGeneratedId.class, true); UuidGeneratedId uuid1 = new UuidGeneratedId(); String stuff1 = "fopewfjefjwgw"; uuid1.stuff = stuff1; assertNull(uuid1.id); assertEquals(1, dao.create(uuid1)); assertNotNull(uuid1.id); UuidGeneratedId uuid2 = new UuidGeneratedId(); String stuff2 = "fopefewjfepowfjefjwgw"; uuid2.stuff = stuff2; assertNull(uuid2.id); assertEquals(1, dao.create(uuid2)); assertNotNull(uuid2.id); assertFalse(uuid1.id.equals(uuid2.id)); List<UuidGeneratedId> uuids = dao.queryForAll(); assertEquals(2, uuids.size()); UuidGeneratedId uuid3 = dao.queryForId(uuid1.id); assertEquals(stuff1, uuid3.stuff); uuid3 = dao.queryForId(uuid2.id); assertEquals(stuff2, uuid3.stuff); } @Test public void testBaseDaoEnabled() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(dao); assertEquals(1, one.create()); } @Test public void testBaseDaoEnabledForeign() throws Exception { Dao<One, Integer> oneDao = createDao(One.class, true); Dao<ForeignDaoEnabled, Integer> foreignDao = createDao(ForeignDaoEnabled.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(oneDao); assertEquals(1, one.create()); ForeignDaoEnabled foreign = new ForeignDaoEnabled(); foreign.one = one; foreign.setDao(foreignDao); assertEquals(1, foreign.create()); ForeignDaoEnabled foreign2 = foreignDao.queryForId(foreign.id); assertNotNull(foreign2); assertEquals(one.id, foreign2.one.id); assertNull(foreign2.one.stuff); assertEquals(1, foreign2.one.refresh()); assertEquals(stuff, foreign2.one.stuff); } @Test public void testBasicEagerCollection() throws Exception { Dao<EagerAccount, Integer> accountDao = createDao(EagerAccount.class, true); Dao<EagerOrder, Integer> orderDao = createDao(EagerOrder.class, true); EagerAccount account = new EagerAccount(); String name = "fwepfjewfew"; account.name = name; assertEquals(1, accountDao.create(account)); EagerOrder order1 = new EagerOrder(); int val1 = 13123441; order1.val = val1; order1.account = account; assertEquals(1, orderDao.create(order1)); EagerOrder order2 = new EagerOrder(); int val2 = 113787097; order2.val = val2; order2.account = account; assertEquals(1, orderDao.create(order2)); EagerAccount account2 = accountDao.queryForId(account.id); assertEquals(name, account2.name); assertNotNull(account2.orders); int orderC = 0; for (EagerOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; } } assertEquals(2, orderC); // insert it via the collection EagerOrder order3 = new EagerOrder(); int val3 = 76557654; order3.val = val3; order3.account = account; account2.orders.add(order3); // the size should change immediately assertEquals(3, account2.orders.size()); // now insert it behind the collections back EagerOrder order4 = new EagerOrder(); int val4 = 1123587097; order4.val = val4; order4.account = account; assertEquals(1, orderDao.create(order4)); // account2's collection should not have changed assertEquals(3, account2.orders.size()); // now we refresh the collection assertEquals(1, accountDao.refresh(account2)); assertEquals(name, account2.name); assertNotNull(account2.orders); orderC = 0; for (EagerOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; case 4 : assertEquals(val4, order.val); break; } } assertEquals(4, orderC); } @Test public void testBasicLazyCollection() throws Exception { Dao<LazyAccount, Integer> accountDao = createDao(LazyAccount.class, true); Dao<LazyOrder, Integer> orderDao = createDao(LazyOrder.class, true); LazyAccount account = new LazyAccount(); String name = "fwepfjewfew"; account.name = name; assertEquals(1, accountDao.create(account)); LazyOrder order1 = new LazyOrder(); int val1 = 13123441; order1.val = val1; order1.account = account; assertEquals(1, orderDao.create(order1)); LazyOrder order2 = new LazyOrder(); int val2 = 113787097; order2.val = val2; order2.account = account; assertEquals(1, orderDao.create(order2)); LazyAccount account2 = accountDao.queryForId(account.id); assertEquals(name, account2.name); assertNotNull(account2.orders); int orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; } } assertEquals(2, orderC); // insert it via the collection LazyOrder order3 = new LazyOrder(); int val3 = 76557654; order3.val = val3; order3.account = account; account2.orders.add(order3); orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; } } assertEquals(3, orderC); // now insert it behind the collections back LazyOrder order4 = new LazyOrder(); int val4 = 1123587097; order4.val = val4; order4.account = account; assertEquals(1, orderDao.create(order4)); // without refreshing we should see the new order orderC = 0; for (LazyOrder order : account2.orders) { orderC++; switch (orderC) { case 1 : assertEquals(val1, order.val); break; case 2 : assertEquals(val2, order.val); break; case 3 : assertEquals(val3, order.val); break; case 4 : assertEquals(val4, order.val); break; } } assertEquals(4, orderC); } @SuppressWarnings("unchecked") @Test public void testUseOfAndMany() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id)); List<Foo> results = where.query(); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); // this should match none where.clear(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id), where.eq(Foo.ID_FIELD_NAME, notId)); results = where.query(); assertEquals(0, results.size()); } @Test @SuppressWarnings("unchecked") public void testUseOfAndInt() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.and(where.eq(Foo.VAL_FIELD_NAME, val), where.eq(Foo.ID_FIELD_NAME, id)); List<Foo> results = where.query(); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); // this should match none where.clear(); where.eq(Foo.VAL_FIELD_NAME, val); where.eq(Foo.ID_FIELD_NAME, id); where.eq(Foo.ID_FIELD_NAME, notId); where.and(3); results = where.query(); assertEquals(0, results.size()); } @SuppressWarnings("unchecked") @Test public void testUseOfOrMany() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.or(where.eq(Foo.ID_FIELD_NAME, id), where.eq(Foo.ID_FIELD_NAME, notId), where.eq(Foo.VAL_FIELD_NAME, val + 1), where.eq(Foo.VAL_FIELD_NAME, val + 1)); List<Foo> results = where.query(); assertEquals(2, results.size()); assertEquals(id, results.get(0).id); assertEquals(notId, results.get(1).id); } @Test public void testUseOfOrInt() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Where<Foo, Integer> where = dao.queryBuilder().where(); where.eq(Foo.ID_FIELD_NAME, id); where.eq(Foo.ID_FIELD_NAME, notId); where.eq(Foo.VAL_FIELD_NAME, val + 1); where.eq(Foo.VAL_FIELD_NAME, val + 1); where.or(4); List<Foo> results = where.query(); assertEquals(2, results.size()); assertEquals(id, results.get(0).id); assertEquals(notId, results.get(1).id); } @Test public void testQueryForMatching() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Foo match = new Foo(); match.val = val; List<Foo> results = dao.queryForMatching(match); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); match = new Foo(); match.id = notId; match.val = val; results = dao.queryForMatching(match); assertEquals(0, results.size()); } @Test public void testQueryForFieldValues() throws Exception { Dao<Foo, Integer> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id = 1; foo.id = id; int val = 1231231; foo.val = val; assertEquals(1, dao.create(foo)); int notId = id + 1; foo.id = notId; foo.val = val + 1; assertEquals(1, dao.create(foo)); Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put(Foo.VAL_FIELD_NAME, val); List<Foo> results = dao.queryForFieldValues(fieldValues); assertEquals(1, results.size()); assertEquals(id, results.get(0).id); fieldValues.put(Foo.ID_FIELD_NAME, notId); fieldValues.put(Foo.VAL_FIELD_NAME, val); results = dao.queryForFieldValues(fieldValues); assertEquals(0, results.size()); } @Test public void testInsertAutoGeneratedId() throws Exception { Dao<Foo, Integer> dao1 = createDao(Foo.class, true); Dao<NotQuiteFoo, Integer> dao2 = createDao(NotQuiteFoo.class, false); Foo foo = new Foo(); assertEquals(1, dao1.create(foo)); NotQuiteFoo notQuiteFoo = new NotQuiteFoo(); notQuiteFoo.id = foo.id + 1; assertEquals(1, dao2.create(notQuiteFoo)); List<Foo> results = dao1.queryForAll(); assertEquals(2, results.size()); assertEquals(foo.id, results.get(0).id); assertEquals(notQuiteFoo.id, results.get(1).id); } @Test public void testCreateWithAllowGeneratedIdInsert() throws Exception { if (databaseType == null || !databaseType.isAllowGeneratedIdInsertSupported()) { return; } Dao<AllowGeneratedIdInsert, Integer> dao = createDao(AllowGeneratedIdInsert.class, true); AllowGeneratedIdInsert foo = new AllowGeneratedIdInsert(); assertEquals(1, dao.create(foo)); AllowGeneratedIdInsert result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.id, result.id); AllowGeneratedIdInsert foo2 = new AllowGeneratedIdInsert(); assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.id, result.id); assertFalse(foo2.id == foo.id); AllowGeneratedIdInsert foo3 = new AllowGeneratedIdInsert(); foo3.id = 10002; assertEquals(1, dao.create(foo3)); result = dao.queryForId(foo3.id); assertNotNull(result); assertEquals(foo3.id, result.id); assertFalse(foo3.id == foo.id); assertFalse(foo3.id == foo2.id); } @Test public void testCreateWithAllowGeneratedIdInsertObject() throws Exception { if (databaseType == null || !databaseType.isAllowGeneratedIdInsertSupported()) { return; } Dao<AllowGeneratedIdInsertObject, Integer> dao = createDao(AllowGeneratedIdInsertObject.class, true); AllowGeneratedIdInsertObject foo = new AllowGeneratedIdInsertObject(); assertEquals(1, dao.create(foo)); AllowGeneratedIdInsertObject result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.id, result.id); AllowGeneratedIdInsertObject foo2 = new AllowGeneratedIdInsertObject(); assertEquals(1, dao.create(foo2)); result = dao.queryForId(foo2.id); assertNotNull(result); assertEquals(foo2.id, result.id); assertFalse(foo2.id == foo.id); AllowGeneratedIdInsertObject foo3 = new AllowGeneratedIdInsertObject(); foo3.id = 10002; assertEquals(1, dao.create(foo3)); result = dao.queryForId(foo3.id); assertNotNull(result); assertEquals(foo3.id, result.id); assertFalse(foo3.id == foo.id); assertFalse(foo3.id == foo2.id); } @Test public void testCreateOrUpdate() throws Exception { Dao<NotQuiteFoo, Integer> dao = createDao(NotQuiteFoo.class, true); NotQuiteFoo foo1 = new NotQuiteFoo(); foo1.stuff = "wow"; CreateOrUpdateStatus status = dao.createOrUpdate(foo1); assertTrue(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); String stuff2 = "4134132"; foo1.stuff = stuff2; status = dao.createOrUpdate(foo1); assertFalse(status.isCreated()); assertTrue(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); NotQuiteFoo result = dao.queryForId(foo1.id); assertEquals(stuff2, result.stuff); } @Test public void testCreateOrUpdateNull() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); CreateOrUpdateStatus status = dao.createOrUpdate(null); assertFalse(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(0, status.getNumLinesChanged()); } @Test public void testCreateOrUpdateNullId() throws Exception { Dao<CreateOrUpdateObjectId, Integer> dao = createDao(CreateOrUpdateObjectId.class, true); CreateOrUpdateObjectId foo = new CreateOrUpdateObjectId(); String stuff = "21313"; foo.stuff = stuff; CreateOrUpdateStatus status = dao.createOrUpdate(foo); assertTrue(status.isCreated()); assertFalse(status.isUpdated()); assertEquals(1, status.getNumLinesChanged()); CreateOrUpdateObjectId result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(stuff, result.stuff); String stuff2 = "pwojgfwe"; foo.stuff = stuff2; dao.createOrUpdate(foo); result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(stuff2, result.stuff); } @Test public void testUpdateNoChange() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); foo.id = 13567567; foo.val = 1232131; assertEquals(1, dao.create(foo)); assertEquals(1, dao.update(foo)); assertEquals(1, dao.update(foo)); } @Test public void testNullForeign() throws Exception { Dao<Order, Integer> orderDao = createDao(Order.class, true); int numOrders = 10; for (int orderC = 0; orderC < numOrders; orderC++) { Order order = new Order(); order.val = orderC; assertEquals(1, orderDao.create(order)); } List<Order> results = orderDao.queryBuilder().where().isNull(Order.ONE_FIELD_NAME).query(); assertNotNull(results); assertEquals(numOrders, results.size()); } @Test public void testSelfGeneratedIdPrimary() throws Exception { Dao<SelfGeneratedIdUuidPrimary, UUID> dao = createDao(SelfGeneratedIdUuidPrimary.class, true); SelfGeneratedIdUuidPrimary foo = new SelfGeneratedIdUuidPrimary(); foo.stuff = "ewpfojwefjo"; assertEquals(1, dao.create(foo)); SelfGeneratedIdUuidPrimary result = dao.queryForId(foo.id); assertNotNull(result); assertEquals(foo.stuff, result.stuff); } @Test public void testCreateIfNotExists() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo1 = new Foo(); String stuff = "stuff"; foo1.stuff = stuff; Foo fooResult = dao.createIfNotExists(foo1); assertSame(foo1, fooResult); // now if we do it again, we should get the database copy of foo fooResult = dao.createIfNotExists(foo1); assertNotSame(foo1, fooResult); assertEquals(foo1.id, fooResult.id); assertEquals(foo1.stuff, fooResult.stuff); } @Test public void testCreateIfNotExistsNull() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); assertNull(dao.createIfNotExists(null)); } @Test public void testCountOf() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); foo.id = 1; assertEquals(1, dao.create(foo)); assertEquals(1, dao.countOf()); foo.id = 2; assertEquals(1, dao.create(foo)); assertEquals(2, dao.countOf()); } @Test public void testCountOfPrepared() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); assertEquals(0, dao.countOf()); Foo foo = new Foo(); int id1 = 1; foo.id = id1; assertEquals(1, dao.create(foo)); foo.id = 2; assertEquals(1, dao.create(foo)); assertEquals(2, dao.countOf()); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.setCountOf(true).where().eq(Foo.ID_FIELD_NAME, id1); assertEquals(1, dao.countOf(qb.prepare())); } @Test public void testCountOfPreparedNoCountOf() throws Exception { if (connectionSource == null) { throw new IllegalArgumentException("Simulation"); } Dao<Foo, String> dao = createDao(Foo.class, true); QueryBuilder<Foo, String> qb = dao.queryBuilder(); try { dao.countOf(qb.prepare()); fail("Should have thrown"); } catch (IllegalArgumentException e) { // expected } } @Test public void testSelectRaw() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); assertEquals(1, dao.create(foo)); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.selectRaw("COUNT(*)"); GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString()); List<String[]> list = results.getResults(); assertEquals(1, list.size()); String[] array = list.get(0); assertEquals(1, array.length); assertEquals("1", array[0]); } @Test public void testSelectRawNotQuery() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); Foo foo = new Foo(); assertEquals(1, dao.create(foo)); QueryBuilder<Foo, String> qb = dao.queryBuilder(); qb.selectRaw("COUNTOF(*)"); try { qb.query(); } catch (SQLException e) { // expected } } /* ==================================================================================== */ private <T extends TestableType<ID>, ID> void checkTypeAsId(Class<T> clazz, ID id1, ID id2) throws Exception { Constructor<T> constructor = clazz.getDeclaredConstructor(); Dao<T, ID> dao = createDao(clazz, true); String s1 = "stuff"; T data1 = constructor.newInstance(); data1.setId(id1); data1.setStuff(s1); // create it assertEquals(1, dao.create(data1)); // refresh it assertEquals(1, dao.refresh(data1)); // now we query for foo from the database to make sure it was persisted right T data2 = dao.queryForId(id1); assertNotNull(data2); assertEquals(id1, data2.getId()); assertEquals(s1, data2.getStuff()); // now we update 1 row in a the database after changing stuff String s2 = "stuff2"; data2.setStuff(s2); assertEquals(1, dao.update(data2)); // now we get it from the db again to make sure it was updated correctly T data3 = dao.queryForId(id1); assertEquals(s2, data3.getStuff()); // change its id assertEquals(1, dao.updateId(data2, id2)); // the old id should not exist assertNull(dao.queryForId(id1)); T data4 = dao.queryForId(id2); assertNotNull(data4); assertEquals(s2, data4.getStuff()); // delete it assertEquals(1, dao.delete(data2)); // should not find it assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); // create data1 and data2 data1.setId(id1); assertEquals(1, dao.create(data1)); data2 = constructor.newInstance(); data2.setId(id2); assertEquals(1, dao.create(data2)); data3 = dao.queryForId(id1); assertNotNull(data3); assertEquals(id1, data3.getId()); data4 = dao.queryForId(id2); assertNotNull(data4); assertEquals(id2, data4.getId()); // delete a collection of ids List<ID> idList = new ArrayList<ID>(); idList.add(id1); idList.add(id2); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, dao.deleteIds(idList)); } else { assertEquals(2, dao.deleteIds(idList)); } assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); // delete a collection of objects assertEquals(1, dao.create(data1)); assertEquals(1, dao.create(data2)); List<T> dataList = new ArrayList<T>(); dataList.add(data1); dataList.add(data2); if (UPDATE_ROWS_RETURNS_ONE) { assertEquals(1, dao.delete(dataList)); } else { assertEquals(2, dao.delete(dataList)); } assertNull(dao.queryForId(id1)); assertNull(dao.queryForId(id2)); } /** * Returns the object if the query failed or null otherwise. */ private boolean checkQueryResult(Dao<AllTypes, Integer> allDao, QueryBuilder<AllTypes, Integer> qb, AllTypes allTypes, String fieldName, Object value, boolean required) throws SQLException { qb.where().eq(fieldName, value); List<AllTypes> results = allDao.query(qb.prepare()); if (required) { assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } else if (results.size() == 1) { assertTrue(allDao.objectsEqual(allTypes, results.get(0))); } else { return false; } SelectArg selectArg = new SelectArg(); qb.where().eq(fieldName, selectArg); selectArg.setValue(value); results = allDao.query(qb.prepare()); assertEquals(1, results.size()); assertTrue(allDao.objectsEqual(allTypes, results.get(0))); return true; } private String buildFooQueryAllString(Dao<Foo, Object> fooDao) throws SQLException { String queryString = fooDao.queryBuilder() .selectColumns(Foo.ID_FIELD_NAME, Foo.STUFF_FIELD_NAME, Foo.VAL_FIELD_NAME) .prepareStatementString(); return queryString; } private interface TestableType<ID> { String getStuff(); void setStuff(String stuff); ID getId(); void setId(ID id); } private static class Mapper implements RawRowMapper<Foo> { public Foo mapRow(String[] columnNames, String[] resultColumns) { Foo foo = new Foo(); for (int i = 0; i < columnNames.length; i++) { if (columnNames[i].equalsIgnoreCase(Foo.ID_FIELD_NAME)) { foo.id = Integer.parseInt(resultColumns[i]); } else if (columnNames[i].equalsIgnoreCase(Foo.STUFF_FIELD_NAME)) { foo.stuff = resultColumns[i]; } else if (columnNames[i].equalsIgnoreCase(Foo.VAL_FIELD_NAME)) { foo.val = Integer.parseInt(resultColumns[i]); } } return foo; } } /* ==================================================================================== */ @DatabaseTable(tableName = FOO_TABLE_NAME) protected static class Foo { public final static String ID_FIELD_NAME = "id"; public final static String STUFF_FIELD_NAME = "stuff"; public final static String VAL_FIELD_NAME = "val"; @DatabaseField(generatedId = true, columnName = ID_FIELD_NAME) public int id; @DatabaseField(columnName = STUFF_FIELD_NAME) public String stuff; @DatabaseField(columnName = VAL_FIELD_NAME) public int val; public Foo() { } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return id == ((Foo) other).id; } @Override public int hashCode() { return id; } @Override public String toString() { return "Foo.id=" + id; } } @DatabaseTable(tableName = FOO_TABLE_NAME) protected static class NotQuiteFoo { @DatabaseField(id = true, columnName = Foo.ID_FIELD_NAME) public int id; @DatabaseField(columnName = Foo.STUFF_FIELD_NAME) public String stuff; @DatabaseField(columnName = Foo.VAL_FIELD_NAME) public int val; public NotQuiteFoo() { } } protected static class DoubleCreate { @DatabaseField(id = true) int id; } protected static class NoId { @DatabaseField public String notId; } private static class JustId { @DatabaseField(id = true) public String id; } private static class ForeignWrapper { private final static String FOREIGN_FIELD_NAME = "foreign"; @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true, columnName = FOREIGN_FIELD_NAME) AllTypes foreign; } private static class MultipleForeignWrapper { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true) AllTypes foreign; @DatabaseField(foreign = true) ForeignWrapper foreignWrapper; } protected static class GetSet { @DatabaseField(generatedId = true, useGetSet = true) private int id; @DatabaseField(useGetSet = true) private String stuff; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } protected static class NoAnno { public int id; public String stuff; public NoAnno() { } } protected static class NoAnnoFor { public int id; public NoAnno foreign; public NoAnnoFor() { } } protected static class GeneratedIdNotNull { @DatabaseField(generatedId = true, canBeNull = false) public int id; @DatabaseField public String stuff; public GeneratedIdNotNull() { } } protected static class Basic { public final static String ID_FIELD = "id"; @DatabaseField(id = true, columnName = ID_FIELD) String id; } private static class DefaultValue { @DatabaseField(defaultValue = DEFAULT_VALUE_STRING) Integer intField; DefaultValue() { } } protected static class NotNull { @DatabaseField(canBeNull = false) String notNull; NotNull() { } } protected static class GeneratedId { @DatabaseField(generatedId = true) int id; @DatabaseField String other; public GeneratedId() { } } protected static class AllTypes { public static final String STRING_FIELD_NAME = "stringField"; public static final String BOOLEAN_FIELD_NAME = "booleanField"; public static final String DATE_FIELD_NAME = "dateField"; public static final String DATE_LONG_FIELD_NAME = "dateLongField"; public static final String DATE_STRING_FIELD_NAME = "dateStringField"; public static final String SERIAL_FIELD_NAME = "serialField"; public static final String CHAR_FIELD_NAME = "charField"; public static final String BYTE_FIELD_NAME = "byteField"; public static final String SHORT_FIELD_NAME = "shortField"; public static final String INT_FIELD_NAME = "intField"; public static final String LONG_FIELD_NAME = "longField"; public static final String FLOAT_FIELD_NAME = "floatField"; public static final String DOUBLE_FIELD_NAME = "doubleField"; public static final String ENUM_FIELD_NAME = "enumField"; public static final String ENUM_STRING_FIELD_NAME = "enumStringField"; public static final String ENUM_INTEGER_FIELD_NAME = "enumIntegerField"; @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = STRING_FIELD_NAME) String stringField; @DatabaseField(columnName = BOOLEAN_FIELD_NAME) boolean booleanField; @DatabaseField(columnName = DATE_FIELD_NAME) Date dateField; @DatabaseField(columnName = DATE_LONG_FIELD_NAME, dataType = DataType.DATE_LONG) Date dateLongField; @DatabaseField(columnName = DATE_STRING_FIELD_NAME, dataType = DataType.DATE_STRING, format = DEFAULT_DATE_STRING_FORMAT) Date dateStringField; @DatabaseField(columnName = CHAR_FIELD_NAME) char charField; @DatabaseField(columnName = BYTE_FIELD_NAME) byte byteField; @DatabaseField(columnName = SHORT_FIELD_NAME) short shortField; @DatabaseField(columnName = INT_FIELD_NAME) int intField; @DatabaseField(columnName = LONG_FIELD_NAME) long longField; @DatabaseField(columnName = FLOAT_FIELD_NAME) float floatField; @DatabaseField(columnName = DOUBLE_FIELD_NAME) double doubleField; @DatabaseField(columnName = SERIAL_FIELD_NAME, dataType = DataType.SERIALIZABLE) SerialData serialField; @DatabaseField(columnName = ENUM_FIELD_NAME) OurEnum enumField; @DatabaseField(columnName = ENUM_STRING_FIELD_NAME, dataType = DataType.ENUM_STRING) OurEnum enumStringField; @DatabaseField(columnName = ENUM_INTEGER_FIELD_NAME, dataType = DataType.ENUM_INTEGER) OurEnum enumIntegerField; AllTypes() { } } protected static class AllTypesDefault { @DatabaseField(generatedId = true) int id; @DatabaseField(defaultValue = DEFAULT_STRING_VALUE) String stringField; @DatabaseField(defaultValue = DEFAULT_DATE_VALUE) Date dateField; @DatabaseField(dataType = DataType.DATE_LONG, defaultValue = DEFAULT_DATE_LONG_VALUE) Date dateLongField; @DatabaseField(dataType = DataType.DATE_STRING, defaultValue = DEFAULT_DATE_STRING_VALUE, format = DEFAULT_DATE_STRING_FORMAT) Date dateStringField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) boolean booleanField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) Boolean booleanObj; @DatabaseField(defaultValue = DEFAULT_BYTE_VALUE) byte byteField; @DatabaseField(defaultValue = DEFAULT_BYTE_VALUE) Byte byteObj; @DatabaseField(defaultValue = DEFAULT_SHORT_VALUE) short shortField; @DatabaseField(defaultValue = DEFAULT_SHORT_VALUE) Short shortObj; @DatabaseField(defaultValue = DEFAULT_INT_VALUE) int intField; @DatabaseField(defaultValue = DEFAULT_INT_VALUE) Integer intObj; @DatabaseField(defaultValue = DEFAULT_LONG_VALUE) long longField; @DatabaseField(defaultValue = DEFAULT_LONG_VALUE) Long longObj; @DatabaseField(defaultValue = DEFAULT_FLOAT_VALUE) float floatField; @DatabaseField(defaultValue = DEFAULT_FLOAT_VALUE) Float floatObj; @DatabaseField(defaultValue = DEFAULT_DOUBLE_VALUE) double doubleField; @DatabaseField(defaultValue = DEFAULT_DOUBLE_VALUE) Double doubleObj; @DatabaseField(dataType = DataType.SERIALIZABLE) SerialData objectField; @DatabaseField(defaultValue = DEFAULT_ENUM_VALUE) OurEnum ourEnum; @DatabaseField(defaultValue = DEFAULT_ENUM_NUMBER_VALUE, dataType = DataType.ENUM_INTEGER) OurEnum ourEnumNumber; AllTypesDefault() { } } protected static class BooleanDefault { @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) boolean booleanField; @DatabaseField(defaultValue = DEFAULT_BOOLEAN_VALUE) Boolean booleanObj; BooleanDefault() { } } protected static class AllObjectTypes { @DatabaseField(generatedId = true) int id; @DatabaseField String stringField; @DatabaseField Boolean booleanField; @DatabaseField Date dateField; @DatabaseField Byte byteField; @DatabaseField Short shortField; @DatabaseField Integer intField; @DatabaseField Long longField; @DatabaseField Float floatField; @DatabaseField Double doubleField; @DatabaseField(dataType = DataType.SERIALIZABLE) SerialData objectField; @DatabaseField OurEnum ourEnum; AllObjectTypes() { } } protected static class NumberTypes { @DatabaseField(generatedId = true) public int id; @DatabaseField public byte byteField; @DatabaseField public short shortField; @DatabaseField public int intField; @DatabaseField public long longField; @DatabaseField public float floatField; @DatabaseField public double doubleField; public NumberTypes() { } } protected static class StringWidth { @DatabaseField(width = ALL_TYPES_STRING_WIDTH) String stringField; StringWidth() { } } // for testing reserved table names as fields private static class Create { @DatabaseField(id = true) public String id; } // for testing reserved words as field names protected static class ReservedField { @DatabaseField(id = true) public int select; @DatabaseField public String from; @DatabaseField public String table; @DatabaseField public String where; @DatabaseField public String group; @DatabaseField public String order; @DatabaseField public String values; public ReservedField() { } } // test the field name that has a capital letter in it protected static class GeneratedColumnCapital { @DatabaseField(generatedId = true, columnName = "idCap") int id; @DatabaseField String other; public GeneratedColumnCapital() { } } protected static class ObjectHolder { @DatabaseField(generatedId = true) public int id; @DatabaseField(dataType = DataType.SERIALIZABLE) public SerialData obj; @DatabaseField(dataType = DataType.SERIALIZABLE) public String strObj; public ObjectHolder() { } } protected static class NotSerializable { @DatabaseField(generatedId = true) public int id; @DatabaseField(dataType = DataType.SERIALIZABLE) public ObjectHolder obj; public NotSerializable() { } } protected static class SerialData implements Serializable { private static final long serialVersionUID = -3883857119616908868L; public Map<String, String> map; public SerialData() { } public void addEntry(String key, String value) { if (map == null) { map = new HashMap<String, String>(); } map.put(key, value); } @Override public int hashCode() { return map.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } SerialData other = (SerialData) obj; if (map == null) { return other.map == null; } else { return map.equals(other.map); } } } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumString { @DatabaseField OurEnum ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumString2 { @DatabaseField OurEnum2 ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt { @DatabaseField(dataType = DataType.ENUM_INTEGER) OurEnum ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt2 { @DatabaseField(dataType = DataType.ENUM_INTEGER) OurEnum2 ourEnum; } @DatabaseTable(tableName = ENUM_TABLE_NAME) protected static class LocalEnumInt3 { @DatabaseField(dataType = DataType.ENUM_INTEGER, unknownEnumName = "FIRST") OurEnum2 ourEnum; } private enum OurEnum { FIRST, SECOND, ; } private enum OurEnum2 { FIRST, ; } @DatabaseTable(tableName = NULL_BOOLEAN_TABLE_NAME) protected static class NullBoolean1 { @DatabaseField Boolean val; } @DatabaseTable(tableName = NULL_BOOLEAN_TABLE_NAME) protected static class NullBoolean2 { @DatabaseField(throwIfNull = true) boolean val; } @DatabaseTable(tableName = NULL_INT_TABLE_NAME) protected static class NullInt1 { @DatabaseField Integer val; } @DatabaseTable(tableName = NULL_INT_TABLE_NAME) protected static class NullInt2 { @DatabaseField(throwIfNull = true) int val; } @DatabaseTable protected static class NotNullDefault { @DatabaseField(canBeNull = false, defaultValue = "3") String stuff; } @DatabaseTable protected static class Unique { @DatabaseField(generatedId = true) int id; @DatabaseField String stuff; @DatabaseField(unique = true) String uniqueStuff; } @DatabaseTable protected static class DoubleUnique { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String stuff; @DatabaseField(unique = true) String uniqueStuff; } @DatabaseTable protected static class DoubleUniqueCombo { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueCombo = true) String stuff; @DatabaseField(uniqueCombo = true) String uniqueStuff; } @DatabaseTable protected static class UniqueAndUniqueCombo { @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) String unique1; @DatabaseField(uniqueCombo = true) String combo1; @DatabaseField(uniqueCombo = true) String combo2; } @DatabaseTable protected static class StringDefalt { @DatabaseField(defaultValue = "3") String stuff; } @DatabaseTable protected static class LocalDate { @DatabaseField(generatedId = true) int id; @DatabaseField Date date; } @DatabaseTable protected static class StringId implements TestableType<String> { @DatabaseField(id = true) String id; @DatabaseField String stuff; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongStringId implements TestableType<String> { @DatabaseField(id = true, dataType = DataType.LONG_STRING) String id; @DatabaseField String stuff; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class BooleanId implements TestableType<Boolean> { @DatabaseField(id = true) boolean id; @DatabaseField String stuff; public Boolean getId() { return id; } public void setId(Boolean bool) { this.id = bool; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class BooleanObjId implements TestableType<Boolean> { @DatabaseField(id = true) Boolean id; @DatabaseField String stuff; public Boolean getId() { return id; } public void setId(Boolean bool) { this.id = bool; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateId implements TestableType<Date> { @DatabaseField(id = true) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateLongId implements TestableType<Date> { @DatabaseField(id = true, dataType = DataType.DATE_LONG) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DateStringId implements TestableType<Date> { @DatabaseField(id = true, dataType = DataType.DATE_STRING) Date id; @DatabaseField String stuff; public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ByteId implements TestableType<Byte> { @DatabaseField(id = true) byte id; @DatabaseField String stuff; public Byte getId() { return id; } public void setId(Byte id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ByteObjId implements TestableType<Byte> { @DatabaseField(id = true) Byte id; @DatabaseField String stuff; public Byte getId() { return id; } public void setId(Byte id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ShortId implements TestableType<Short> { @DatabaseField(id = true) short id; @DatabaseField String stuff; public Short getId() { return id; } public void setId(Short id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class ShortObjId implements TestableType<Short> { @DatabaseField(id = true) Short id; @DatabaseField String stuff; public Short getId() { return id; } public void setId(Short id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class IntId implements TestableType<Integer> { @DatabaseField(id = true) int id; @DatabaseField String stuff; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class IntObjId implements TestableType<Integer> { @DatabaseField(id = true) Integer id; @DatabaseField String stuff; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongId implements TestableType<Long> { @DatabaseField(id = true) long id; @DatabaseField String stuff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class LongObjId implements TestableType<Long> { @DatabaseField(id = true) Long id; @DatabaseField String stuff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class FloatId implements TestableType<Float> { @DatabaseField(id = true) float id; @DatabaseField String stuff; public Float getId() { return id; } public void setId(Float id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class FloatObjId implements TestableType<Float> { @DatabaseField(id = true) Float id; @DatabaseField String stuff; public Float getId() { return id; } public void setId(Float id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DoubleId implements TestableType<Double> { @DatabaseField(id = true) double id; @DatabaseField String stuff; public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class DoubleObjId implements TestableType<Double> { @DatabaseField(id = true) Double id; @DatabaseField String stuff; public Double getId() { return id; } public void setId(Double id) { this.id = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumId implements TestableType<OurEnum> { @DatabaseField(id = true) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumStringId implements TestableType<OurEnum> { @DatabaseField(id = true, dataType = DataType.ENUM_STRING) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class EnumIntegerId implements TestableType<OurEnum> { @DatabaseField(id = true, dataType = DataType.ENUM_INTEGER) OurEnum ourEnum; @DatabaseField String stuff; public OurEnum getId() { return ourEnum; } public void setId(OurEnum id) { this.ourEnum = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class SerializableId implements TestableType<SerialData> { @DatabaseField(id = true, dataType = DataType.SERIALIZABLE) SerialData serial; @DatabaseField String stuff; public SerialData getId() { return serial; } public void setId(SerialData id) { this.serial = id; } public String getStuff() { return stuff; } public void setStuff(String stuff) { this.stuff = stuff; } } @DatabaseTable protected static class Recursive { @DatabaseField(generatedId = true) int id; @DatabaseField(foreign = true) Recursive foreign; public Recursive() { } } @DatabaseTable protected static class SerializedBytes { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.SERIALIZABLE) byte[] bytes; public SerializedBytes() { } } @DatabaseTable protected static class ByteArray { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.BYTE_ARRAY) byte[] bytes; public ByteArray() { } } @DatabaseTable protected static class Index { @DatabaseField(generatedId = true) int id; @DatabaseField(index = true) String stuff; public Index() { } } @DatabaseTable protected static class IndexColumnName { public static final String STUFF_COLUMN_NAME = "notStuff"; @DatabaseField(generatedId = true) int id; @DatabaseField(index = true, columnName = STUFF_COLUMN_NAME) String stuff; public IndexColumnName() { } } @DatabaseTable protected static class UniqueIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueIndex = true) String stuff; public UniqueIndex() { } } @DatabaseTable protected static class ComboIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(indexName = "stuffjunk") String stuff; @DatabaseField(indexName = "stuffjunk") long junk; public ComboIndex() { } } @DatabaseTable protected static class ComboUniqueIndex { @DatabaseField(generatedId = true) int id; @DatabaseField(uniqueIndexName = "stuffjunk") String stuff; @DatabaseField(uniqueIndexName = "stuffjunk") long junk; public ComboUniqueIndex() { } } @DatabaseTable protected static class LongVarChar { @DatabaseField(generatedId = true) int id; @DatabaseField(dataType = DataType.LONG_STRING) String stuff; public LongVarChar() { } } protected static class Base { @DatabaseField(id = true) int id; public Base() { // for ormlite } } protected static class Sub extends Base { @DatabaseField String stuff; public Sub() { // for ormlite } } protected static class UuidGeneratedId { @DatabaseField(generatedId = true) public UUID id; @DatabaseField public String stuff; public UuidGeneratedId() { } } protected static class One extends BaseDaoEnabled<One, Integer> { @DatabaseField(generatedId = true) public int id; @DatabaseField public String stuff; public One() { } } protected static class ForeignDaoEnabled extends BaseDaoEnabled<ForeignDaoEnabled, Integer> { @DatabaseField(generatedId = true) public int id; @DatabaseField(foreign = true) public One one; public ForeignDaoEnabled() { } } protected static class EagerAccount { @DatabaseField(generatedId = true) int id; @DatabaseField String name; @ForeignCollectionField(eager = true) Collection<EagerOrder> orders; protected EagerAccount() { } } protected static class EagerOrder { @DatabaseField(generatedId = true) int id; @DatabaseField int val; @DatabaseField(foreign = true) EagerAccount account; protected EagerOrder() { } } protected static class LazyAccount { @DatabaseField(generatedId = true) int id; @DatabaseField String name; @ForeignCollectionField Collection<LazyOrder> orders; protected LazyAccount() { } } protected static class LazyOrder { @DatabaseField(generatedId = true) int id; @DatabaseField int val; @DatabaseField(foreign = true) LazyAccount account; protected LazyOrder() { } } protected static class AllowGeneratedIdInsert { @DatabaseField(generatedId = true, allowGeneratedIdInsert = true) int id; @DatabaseField String stuff; } protected static class SelfGeneratedIdUuidPrimary { @DatabaseField(generatedId = true) UUID id; @DatabaseField String stuff; } protected static class AllowGeneratedIdInsertObject { @DatabaseField(generatedId = true, allowGeneratedIdInsert = true) Integer id; @DatabaseField String stuff; } protected static class CreateOrUpdateObjectId { @DatabaseField(generatedId = true) public Integer id; @DatabaseField public String stuff; public CreateOrUpdateObjectId() { } } protected static class Order { public static final String ONE_FIELD_NAME = "one_id"; @DatabaseField(generatedId = true) int id; @DatabaseField(unique = true) int val; @DatabaseField(foreign = true, columnName = ONE_FIELD_NAME) One one; protected Order() { } } }
Fixed foreignAutoCreate bug where parent object didn't get foreign id. Thanks to Chase. Fixes bug #3434550.
src/test/java/com/j256/ormlite/dao/JdbcBaseDaoImplTest.java
Fixed foreignAutoCreate bug where parent object didn't get foreign id. Thanks to Chase. Fixes bug #3434550.
<ide><path>rc/test/java/com/j256/ormlite/dao/JdbcBaseDaoImplTest.java <ide> } <ide> } <ide> <add> @Test <add> public void testForeignAutoCreate() throws Exception { <add> Dao<ForeignAutoCreate, Long> foreignAutoCreateDao = createDao(ForeignAutoCreate.class, true); <add> Dao<ForeignAutoCreateForeign, Long> foreignAutoCreateForeignDao = <add> createDao(ForeignAutoCreateForeign.class, true); <add> <add> List<ForeignAutoCreateForeign> results = foreignAutoCreateForeignDao.queryForAll(); <add> assertEquals(0, results.size()); <add> <add> ForeignAutoCreateForeign foreign = new ForeignAutoCreateForeign(); <add> String stuff = "fopewjfpwejfpwjfw"; <add> foreign.stuff = stuff; <add> <add> ForeignAutoCreate foo1 = new ForeignAutoCreate(); <add> foo1.foreign = foreign; <add> assertEquals(1, foreignAutoCreateDao.create(foo1)); <add> <add> // we should not get something from the other dao <add> results = foreignAutoCreateForeignDao.queryForAll(); <add> assertEquals(1, results.size()); <add> assertEquals(foreign.id, results.get(0).id); <add> <add> // if we get foo back, we should see the foreign-id <add> List<ForeignAutoCreate> foreignAutoCreateResults = foreignAutoCreateDao.queryForAll(); <add> assertEquals(1, foreignAutoCreateResults.size()); <add> assertEquals(foo1.id, foreignAutoCreateResults.get(0).id); <add> assertNotNull(foreignAutoCreateResults.get(0).foreign); <add> assertEquals(foo1.foreign.id, foreignAutoCreateResults.get(0).foreign.id); <add> <add> // now we create it when the foreign field already has an id set <add> ForeignAutoCreate foo2 = new ForeignAutoCreate(); <add> foo2.foreign = foreign; <add> assertEquals(1, foreignAutoCreateDao.create(foo1)); <add> <add> results = foreignAutoCreateForeignDao.queryForAll(); <add> // no additional results should be found <add> assertEquals(1, results.size()); <add> assertEquals(foreign.id, results.get(0).id); <add> } <add> <ide> /* ==================================================================================== */ <ide> <ide> private <T extends TestableType<ID>, ID> void checkTypeAsId(Class<T> clazz, ID id1, ID id2) throws Exception { <ide> protected Order() { <ide> } <ide> } <add> <add> protected static class ForeignAutoCreate { <add> @DatabaseField(generatedId = true) <add> int id; <add> @DatabaseField(foreign = true, foreignAutoCreate = true) <add> public ForeignAutoCreateForeign foreign; <add> } <add> <add> protected static class ForeignAutoCreateForeign { <add> @DatabaseField(generatedId = true) <add> int id; <add> @DatabaseField <add> String stuff; <add> } <ide> }
Java
apache-2.0
6a295dfcf677fee698751c2fa784f03d642503b7
0
apache/aries,graben/aries,alien11689/aries,apache/aries,graben/aries,alien11689/aries,graben/aries,rotty3000/aries,apache/aries,rotty3000/aries,rotty3000/aries,alien11689/aries,graben/aries,rotty3000/aries,alien11689/aries,apache/aries
/** * 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.aries.jmx.framework; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.management.openmbean.CompositeData; import org.apache.aries.jmx.codec.BatchActionResult; import org.apache.aries.jmx.codec.BatchInstallResult; import org.apache.aries.jmx.util.FrameworkUtils; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.jmx.framework.FrameworkMBean; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; /** * <p> * <tt>Framework</tt> represents {@link FrameworkMBean} implementation. * </p> * @see FrameworkMBean * * @version $Rev$ $Date$ */ public class Framework implements FrameworkMBean { private StartLevel startLevel; private PackageAdmin packageAdmin; private BundleContext context; /** * Constructs new FrameworkMBean. * * @param context bundle context of jmx bundle. * @param startLevel @see {@link StartLevel} service reference. * @param packageAdmin @see {@link PackageAdmin} service reference. */ public Framework(BundleContext context, StartLevel startLevel, PackageAdmin packageAdmin) { this.context = context; this.startLevel = startLevel; this.packageAdmin = packageAdmin; } /** * @see org.osgi.jmx.framework.FrameworkMBean#getFrameworkStartLevel() */ public int getFrameworkStartLevel() throws IOException { return startLevel.getStartLevel(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#getInitialBundleStartLevel() */ public int getInitialBundleStartLevel() throws IOException { return startLevel.getInitialBundleStartLevel(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundle(java.lang.String) */ public long installBundle(String location) throws IOException { try { Bundle bundle = context.installBundle(location); return bundle.getBundleId(); } catch (BundleException e) { IOException ioex = new IOException("Can't install bundle with location " + location); ioex.initCause(e); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundleFromURL(String, String) */ public long installBundleFromURL(String location, String url) throws IOException { InputStream inputStream = null; try { inputStream = createStream(url); Bundle bundle = context.installBundle(location, inputStream); return bundle.getBundleId(); } catch (BundleException e) { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { } } IOException ioex = new IOException("Can't install bundle with location " + location); ioex.initCause(e); throw ioex; } } public InputStream createStream(String url) throws IOException { return new URL(url).openStream(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundles(java.lang.String[]) */ public CompositeData installBundles(String[] locations) throws IOException { if(locations == null){ return new BatchInstallResult("Failed to install bundles locations can't be null").toCompositeData(); } long[] ids = new long[locations.length]; for (int i = 0; i < locations.length; i++) { try { long id = installBundle(locations[i]); ids[i] = id; } catch (Throwable t) { long[] completed = new long[i]; System.arraycopy(ids, 0, completed, 0, i); String[] remaining = new String[locations.length - i - 1]; System.arraycopy(locations, i + 1, remaining, 0, remaining.length); return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData(); } } return new BatchInstallResult(ids).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundlesFromURL(String[], String[]) */ public CompositeData installBundlesFromURL(String[] locations, String[] urls) throws IOException { if(locations == null || urls == null){ return new BatchInstallResult("Failed to install bundles arguments can't be null").toCompositeData(); } if(locations.length != urls.length){ return new BatchInstallResult("Failed to install bundles size of arguments should be same").toCompositeData(); } long[] ids = new long[locations.length]; for (int i = 0; i < locations.length; i++) { try { long id = installBundleFromURL(locations[i], urls[i]); ids[i] = id; } catch (Throwable t) { long[] completed = new long[i]; System.arraycopy(ids, 0, completed, 0, i); String[] remaining = new String[locations.length - i - 1]; System.arraycopy(locations, i + 1, remaining, 0, remaining.length); return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData(); } } return new BatchInstallResult(ids).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#refreshBundle(long) */ public void refreshBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); packageAdmin.refreshPackages(new Bundle[] { bundle }); } /** * @see org.osgi.jmx.framework.FrameworkMBean#refreshBundles(long[]) */ public void refreshBundles(long[] bundleIdentifiers) throws IOException { Bundle[] bundles = null; if(bundleIdentifiers != null) { bundles = new Bundle[bundleIdentifiers.length]; for (int i = 0; i < bundleIdentifiers.length; i++) { bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]); } } packageAdmin.refreshPackages(bundles); } /** * @see org.osgi.jmx.framework.FrameworkMBean#resolveBundle(long) */ public boolean resolveBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); return packageAdmin.resolveBundles(new Bundle[] { bundle }); } /** * @see org.osgi.jmx.framework.FrameworkMBean#resolveBundles(long[]) */ public boolean resolveBundles(long[] bundleIdentifiers) throws IOException { Bundle[] bundles = null; if(bundleIdentifiers != null) { bundles = new Bundle[bundleIdentifiers.length]; for (int i = 0; i < bundleIdentifiers.length; i++) { bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]); } } return packageAdmin.resolveBundles(bundles); } /** * @see org.osgi.jmx.framework.FrameworkMBean#restartFramework() */ public void restartFramework() throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, 0); try { bundle.update(); } catch (BundleException be) { IOException ioex = new IOException("Failed to restart framework"); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevel(long, int) */ public void setBundleStartLevel(long bundleIdentifier, int newlevel) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); startLevel.setBundleStartLevel(bundle, newlevel); } /** * @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevels(long[], int[]) */ public CompositeData setBundleStartLevels(long[] bundleIdentifiers, int[] newlevels) throws IOException { if(bundleIdentifiers == null || newlevels == null){ return new BatchActionResult("Failed to setBundleStartLevels arguments can't be null").toCompositeData(); } if(bundleIdentifiers != null && newlevels != null && bundleIdentifiers.length != newlevels.length){ return new BatchActionResult("Failed to setBundleStartLevels size of arguments should be same").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { setBundleStartLevel(bundleIdentifiers[i], newlevels[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#setFrameworkStartLevel(int) */ public void setFrameworkStartLevel(int newlevel) throws IOException { startLevel.setStartLevel(newlevel); } /** * @see org.osgi.jmx.framework.FrameworkMBean#setInitialBundleStartLevel(int) */ public void setInitialBundleStartLevel(int newlevel) throws IOException { startLevel.setInitialBundleStartLevel(newlevel); } /** * @see org.osgi.jmx.framework.FrameworkMBean#shutdownFramework() */ public void shutdownFramework() throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, 0); try { bundle.stop(); } catch (BundleException be) { IOException ioex = new IOException("Failed to shutdown framework"); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#startBundle(long) */ public void startBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); if (bundle != null) { try { bundle.start(); } catch (BundleException be) { IOException ioex = new IOException("Failed to start bundle with id " + bundleIdentifier); ioex.initCause(be); throw ioex; } } } /** * @see org.osgi.jmx.framework.FrameworkMBean#startBundles(long[]) */ public CompositeData startBundles(long[] bundleIdentifiers) throws IOException { if(bundleIdentifiers == null){ return new BatchActionResult("Failed to start bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { startBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#stopBundle(long) */ public void stopBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); if (bundle != null) { try { bundle.stop(); } catch (BundleException e) { IOException ioex = new IOException("Failed to stop bundle with id " + bundleIdentifier); ioex.initCause(e); throw ioex; } } } /** * @see org.osgi.jmx.framework.FrameworkMBean#stopBundles(long[]) */ public CompositeData stopBundles(long[] bundleIdentifiers) throws IOException { if(bundleIdentifiers == null){ return new BatchActionResult("Failed to stop bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { stopBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundle(long) */ public void uninstallBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); if (bundle != null) { try { bundle.uninstall(); } catch (BundleException be) { IOException ioex = new IOException("Failed to uninstall bundle with id " + bundleIdentifier); ioex.initCause(be); throw ioex; } } } /** * @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundles(long[]) */ public CompositeData uninstallBundles(long[] bundleIdentifiers) throws IOException { if(bundleIdentifiers == null){ return new BatchActionResult("Failed uninstall bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { uninstallBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundle(long) */ public void updateBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); try { bundle.update(); } catch (BundleException be) { IOException ioex = new IOException("Failed to update bundle with id " + bundleIdentifier); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundleFromURL(long, String) */ public void updateBundleFromURL(long bundleIdentifier, String url) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);; InputStream inputStream = null; try { inputStream = createStream(url); bundle.update(inputStream); } catch (BundleException be) { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { } } IOException ioex = new IOException("Can't update system bundle"); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundles(long[]) */ public CompositeData updateBundles(long[] bundleIdentifiers) throws IOException { if (bundleIdentifiers == null) { return new BatchActionResult("Failed to update bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { updateBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundlesFromURL(long[], String[]) */ public CompositeData updateBundlesFromURL(long[] bundleIdentifiers, String[] urls) throws IOException { if(bundleIdentifiers == null || urls == null){ return new BatchActionResult("Failed to update bundles arguments can't be null").toCompositeData(); } if(bundleIdentifiers != null && urls != null && bundleIdentifiers.length != urls.length){ return new BatchActionResult("Failed to update bundles size of arguments should be same").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { updateBundleFromURL(bundleIdentifiers[i], urls[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateFramework() */ public void updateFramework() throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, 0); try { bundle.update(); } catch (BundleException be) { IOException ioex = new IOException("Failed to update system bundle"); ioex.initCause(be); throw ioex; } } /** * Create {@link BatchActionResult}, when the operation fail. * * @param bundleIdentifiers bundle ids for operation. * @param i index of loop pointing on which operation fails. * @param t Throwable thrown by failed operation. * @return created BatchActionResult instance. */ private CompositeData createFailedBatchActionResult(long[] bundleIdentifiers, int i, Throwable t) { long[] completed = new long[i]; System.arraycopy(bundleIdentifiers, 0, completed, 0, i); long[] remaining = new long[bundleIdentifiers.length - i - 1]; System.arraycopy(bundleIdentifiers, i + 1, remaining, 0, remaining.length); return new BatchActionResult(completed, t.toString(), remaining, bundleIdentifiers[i]).toCompositeData(); } }
jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.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.aries.jmx.framework; import java.io.IOException; import java.io.InputStream; import java.net.URL; import javax.management.openmbean.CompositeData; import org.apache.aries.jmx.codec.BatchActionResult; import org.apache.aries.jmx.codec.BatchInstallResult; import org.apache.aries.jmx.util.FrameworkUtils; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.jmx.framework.FrameworkMBean; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.startlevel.StartLevel; /** * <p> * <tt>Framework</tt> represents {@link FrameworkMBean} implementation. * </p> * @see FrameworkMBean * * @version $Rev$ $Date$ */ public class Framework implements FrameworkMBean { private StartLevel startLevel; private PackageAdmin packageAdmin; private BundleContext context; /** * Constructs new FrameworkMBean. * * @param context bundle context of jmx bundle. * @param startLevel @see {@link StartLevel} service reference. * @param packageAdmin @see {@link PackageAdmin} service reference. */ public Framework(BundleContext context, StartLevel startLevel, PackageAdmin packageAdmin) { this.context = context; this.startLevel = startLevel; this.packageAdmin = packageAdmin; } /** * @see org.osgi.jmx.framework.FrameworkMBean#getFrameworkStartLevel() */ public int getFrameworkStartLevel() throws IOException { return startLevel.getStartLevel(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#getInitialBundleStartLevel() */ public int getInitialBundleStartLevel() throws IOException { return startLevel.getInitialBundleStartLevel(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundle(java.lang.String) */ public long installBundle(String location) throws IOException { try { Bundle bundle = context.installBundle(location); return bundle.getBundleId(); } catch (BundleException e) { IOException ioex = new IOException("Can't install bundle with location " + location); ioex.initCause(e); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundleFromURL(String, String) */ public long installBundleFromURL(String location, String url) throws IOException { InputStream inputStream = null; try { inputStream = createStream(url); Bundle bundle = context.installBundle(location, inputStream); return bundle.getBundleId(); } catch (BundleException e) { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { } } IOException ioex = new IOException("Can't install bundle with location " + location); ioex.initCause(e); throw ioex; } } public InputStream createStream(String url) throws IOException { return new URL(url).openStream(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundles(java.lang.String[]) */ public CompositeData installBundles(String[] locations) throws IOException { if(locations == null){ return new BatchInstallResult("Failed to install bundles locations can't be null").toCompositeData(); } long[] ids = new long[locations.length]; for (int i = 0; i < locations.length; i++) { try { long id = installBundle(locations[i]); ids[i] = id; } catch (Throwable t) { long[] completed = new long[i]; System.arraycopy(ids, 0, completed, 0, i); String[] remaining = new String[locations.length - i - 1]; System.arraycopy(locations, i + 1, remaining, 0, remaining.length); return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData(); } } return new BatchInstallResult(ids).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#installBundlesFromURL(String[], String[]) */ public CompositeData installBundlesFromURL(String[] locations, String[] urls) throws IOException { if(locations == null || urls == null){ return new BatchInstallResult("Failed to install bundles arguments can't be null").toCompositeData(); } if(locations.length != urls.length){ return new BatchInstallResult("Failed to install bundles size of arguments should be same").toCompositeData(); } long[] ids = new long[locations.length]; for (int i = 0; i < locations.length; i++) { try { long id = installBundleFromURL(locations[i], urls[i]); ids[i] = id; } catch (Throwable t) { long[] completed = new long[i]; System.arraycopy(ids, 0, completed, 0, i); String[] remaining = new String[locations.length - i - 1]; System.arraycopy(locations, i + 1, remaining, 0, remaining.length); return new BatchInstallResult(completed, t.toString(), remaining, locations[i]).toCompositeData(); } } return new BatchInstallResult(ids).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#refreshBundle(long) */ public void refreshBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); packageAdmin.refreshPackages(new Bundle[] { bundle }); } /** * @see org.osgi.jmx.framework.FrameworkMBean#refreshBundles(long[]) */ public void refreshBundles(long[] bundleIdentifiers) throws IOException { Bundle[] bundles = null; if(bundleIdentifiers != null) { bundles = new Bundle[bundleIdentifiers.length]; for (int i = 0; i < bundleIdentifiers.length; i++) { bundles[i] = context.getBundle(bundleIdentifiers[i]); } } packageAdmin.refreshPackages(bundles); } /** * @see org.osgi.jmx.framework.FrameworkMBean#resolveBundle(long) */ public boolean resolveBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); return packageAdmin.resolveBundles(new Bundle[] { bundle }); } /** * @see org.osgi.jmx.framework.FrameworkMBean#resolveBundles(long[]) */ public boolean resolveBundles(long[] bundleIdentifiers) throws IOException { Bundle[] bundles = null; if(bundleIdentifiers != null) { bundles = new Bundle[bundleIdentifiers.length]; for (int i = 0; i < bundleIdentifiers.length; i++) { bundles[i] = context.getBundle(bundleIdentifiers[i]); } } return packageAdmin.resolveBundles(bundles); } /** * @see org.osgi.jmx.framework.FrameworkMBean#restartFramework() */ public void restartFramework() throws IOException { Bundle bundle = context.getBundle(0); try { bundle.update(); } catch (BundleException be) { IOException ioex = new IOException("Failed to restart framework"); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevel(long, int) */ public void setBundleStartLevel(long bundleIdentifier, int newlevel) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); startLevel.setBundleStartLevel(bundle, newlevel); } /** * @see org.osgi.jmx.framework.FrameworkMBean#setBundleStartLevels(long[], int[]) */ public CompositeData setBundleStartLevels(long[] bundleIdentifiers, int[] newlevels) throws IOException { if(bundleIdentifiers == null || newlevels == null){ return new BatchActionResult("Failed to setBundleStartLevels arguments can't be null").toCompositeData(); } if(bundleIdentifiers != null && newlevels != null && bundleIdentifiers.length != newlevels.length){ return new BatchActionResult("Failed to setBundleStartLevels size of arguments should be same").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { setBundleStartLevel(bundleIdentifiers[i], newlevels[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#setFrameworkStartLevel(int) */ public void setFrameworkStartLevel(int newlevel) throws IOException { startLevel.setStartLevel(newlevel); } /** * @see org.osgi.jmx.framework.FrameworkMBean#setInitialBundleStartLevel(int) */ public void setInitialBundleStartLevel(int newlevel) throws IOException { startLevel.setInitialBundleStartLevel(newlevel); } /** * @see org.osgi.jmx.framework.FrameworkMBean#shutdownFramework() */ public void shutdownFramework() throws IOException { Bundle bundle = context.getBundle(0); try { bundle.stop(); } catch (BundleException be) { IOException ioex = new IOException("Failed to shutdown framework"); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#startBundle(long) */ public void startBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); if (bundle != null) { try { bundle.start(); } catch (BundleException be) { IOException ioex = new IOException("Failed to start bundle with id " + bundleIdentifier); ioex.initCause(be); throw ioex; } } } /** * @see org.osgi.jmx.framework.FrameworkMBean#startBundles(long[]) */ public CompositeData startBundles(long[] bundleIdentifiers) throws IOException { if(bundleIdentifiers == null){ return new BatchActionResult("Failed to start bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { startBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#stopBundle(long) */ public void stopBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); if (bundle != null) { try { bundle.stop(); } catch (BundleException e) { IOException ioex = new IOException("Failed to stop bundle with id " + bundleIdentifier); ioex.initCause(e); throw ioex; } } } /** * @see org.osgi.jmx.framework.FrameworkMBean#stopBundles(long[]) */ public CompositeData stopBundles(long[] bundleIdentifiers) throws IOException { if(bundleIdentifiers == null){ return new BatchActionResult("Failed to stop bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { stopBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundle(long) */ public void uninstallBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); if (bundle != null) { try { bundle.uninstall(); } catch (BundleException be) { IOException ioex = new IOException("Failed to uninstall bundle with id " + bundleIdentifier); ioex.initCause(be); throw ioex; } } } /** * @see org.osgi.jmx.framework.FrameworkMBean#uninstallBundles(long[]) */ public CompositeData uninstallBundles(long[] bundleIdentifiers) throws IOException { if(bundleIdentifiers == null){ return new BatchActionResult("Failed uninstall bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { uninstallBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundle(long) */ public void updateBundle(long bundleIdentifier) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier); try { bundle.update(); } catch (BundleException be) { IOException ioex = new IOException("Failed to update bundle with id " + bundleIdentifier); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundleFromURL(long, String) */ public void updateBundleFromURL(long bundleIdentifier, String url) throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, bundleIdentifier);; InputStream inputStream = null; try { inputStream = createStream(url); bundle.update(inputStream); } catch (BundleException be) { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { } } IOException ioex = new IOException("Can't update system bundle"); ioex.initCause(be); throw ioex; } } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundles(long[]) */ public CompositeData updateBundles(long[] bundleIdentifiers) throws IOException { if (bundleIdentifiers == null) { return new BatchActionResult("Failed to update bundles, bundle id's can't be null").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { updateBundle(bundleIdentifiers[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateBundlesFromURL(long[], String[]) */ public CompositeData updateBundlesFromURL(long[] bundleIdentifiers, String[] urls) throws IOException { if(bundleIdentifiers == null || urls == null){ return new BatchActionResult("Failed to update bundles arguments can't be null").toCompositeData(); } if(bundleIdentifiers != null && urls != null && bundleIdentifiers.length != urls.length){ return new BatchActionResult("Failed to update bundles size of arguments should be same").toCompositeData(); } for (int i = 0; i < bundleIdentifiers.length; i++) { try { updateBundleFromURL(bundleIdentifiers[i], urls[i]); } catch (Throwable t) { return createFailedBatchActionResult(bundleIdentifiers, i, t); } } return new BatchActionResult(bundleIdentifiers).toCompositeData(); } /** * @see org.osgi.jmx.framework.FrameworkMBean#updateFramework() */ public void updateFramework() throws IOException { Bundle bundle = FrameworkUtils.resolveBundle(context, 0); try { bundle.update(); } catch (BundleException be) { IOException ioex = new IOException("Failed to update system bundle"); ioex.initCause(be); throw ioex; } } /** * Create {@link BatchActionResult}, when the operation fail. * * @param bundleIdentifiers bundle ids for operation. * @param i index of loop pointing on which operation fails. * @param t Throwable thrown by failed operation. * @return created BatchActionResult instance. */ private CompositeData createFailedBatchActionResult(long[] bundleIdentifiers, int i, Throwable t) { long[] completed = new long[i]; System.arraycopy(bundleIdentifiers, 0, completed, 0, i); long[] remaining = new long[bundleIdentifiers.length - i - 1]; System.arraycopy(bundleIdentifiers, i + 1, remaining, 0, remaining.length); return new BatchActionResult(completed, t.toString(), remaining, bundleIdentifiers[i]).toCompositeData(); } }
ARIES-177 git-svn-id: 212869a37fe990abe2323f86150f3c4d5a6279c2@922890 13f79535-47bb-0310-9956-ffa450edef68
jmx/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.java
ARIES-177
<ide><path>mx/jmx-core/src/main/java/org/apache/aries/jmx/framework/Framework.java <ide> bundles = new Bundle[bundleIdentifiers.length]; <ide> for (int i = 0; i < bundleIdentifiers.length; i++) <ide> { <del> bundles[i] = context.getBundle(bundleIdentifiers[i]); <add> bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]); <ide> } <ide> } <ide> packageAdmin.refreshPackages(bundles); <ide> bundles = new Bundle[bundleIdentifiers.length]; <ide> for (int i = 0; i < bundleIdentifiers.length; i++) <ide> { <del> bundles[i] = context.getBundle(bundleIdentifiers[i]); <add> bundles[i] = FrameworkUtils.resolveBundle(context, bundleIdentifiers[i]); <ide> } <ide> } <ide> return packageAdmin.resolveBundles(bundles); <ide> * @see org.osgi.jmx.framework.FrameworkMBean#restartFramework() <ide> */ <ide> public void restartFramework() throws IOException { <del> Bundle bundle = context.getBundle(0); <add> Bundle bundle = FrameworkUtils.resolveBundle(context, 0); <ide> try { <ide> bundle.update(); <ide> } catch (BundleException be) { <ide> * @see org.osgi.jmx.framework.FrameworkMBean#shutdownFramework() <ide> */ <ide> public void shutdownFramework() throws IOException { <del> Bundle bundle = context.getBundle(0); <add> Bundle bundle = FrameworkUtils.resolveBundle(context, 0); <ide> try { <ide> bundle.stop(); <ide> } catch (BundleException be) {
Java
mit
fcdaff8f6e31e050da6c2872e964732523873631
0
gscrot/gscrot
package com.redpois0n.guiscrot; import java.awt.AWTException; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Robot; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.event.MouseInputListener; import org.jnativehook.GlobalScreen; import org.jnativehook.mouse.NativeMouseEvent; import org.jnativehook.mouse.NativeMouseMotionListener; @SuppressWarnings("serial") public class CoverFrame extends JFrame implements MouseMotionListener, MouseInputListener, NativeMouseMotionListener { public static final float OPACITY = 0.5F; private Rectangle rect; private Image image; private int x; private int y; private int x2; private int y2; private boolean dragging; private int seed; private RepaintThread thread; public CoverFrame(Rectangle rect) { this(rect, null); } public CoverFrame(Rectangle rect, Image image) { this.rect = rect; this.image = image; GlobalScreen.addNativeMouseMotionListener(this); setUndecorated(true); setBounds(rect); setContentPane(new CoverPanel()); addMouseListener(this); addMouseMotionListener(this); if (image == null) { setOpacity(OPACITY); } thread = new RepaintThread(); thread.start(); } private class RepaintThread extends Thread { @Override public void run() { while (!interrupted()) { if (seed++ >= 20) { seed = 0; } repaint(); try { Thread.sleep(100L); } catch (Exception ex) { ex.printStackTrace(); } } } } private class CoverPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (g instanceof Graphics2D) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); } if (x > x2 && x2 != 0) { int temp = x; x = x2; x2 = temp; } if (y > y2 && y2 != 0) { int temp = y; y = y2; y2 = temp; } /** If nothing is selected, default to x and y**/ int tx = x2 == 0 ? x : x2; int ty = y2 == 0 ? y : y2; if (image != null) { /** Draw image over frame **/ g.drawImage(image, 0, 0, getWidth(), getHeight(), null); /** Set color to transparent black **/ g.setColor(new Color(0, 0, 0, 100)); /** Draw black transparent color over all areas that isn't being selected **/ g.fillRect(0, 0, x, getHeight()); g.fillRect(x, 0, getWidth(), y); g.fillRect(tx, y, getWidth(), getHeight()); g.fillRect(x, ty, tx - x, getHeight()); } else { g.setColor(Color.black); g.fillRect(0, 0, getWidth(), getHeight()); } g.setColor(Color.white); RendererUtils.drawMovingRect(x, 0, 1, getHeight(), g, seed); RendererUtils.drawMovingRect(0, y, getWidth(), 1, g, seed); g.setFont(new Font("Arial", Font.BOLD, 16)); RendererUtils.drawOutlinedString("X " + (x + rect.x) + " / Y " + (y + rect.y), x + 2, y - 2, Color.white, Color.black, g); if (x2 != 0 && y2 != 0) { RendererUtils.drawOutlinedString("Width " + (x2 - x) + " / Height " + (y2 - y), x + 2, y - 4 - g.getFontMetrics().getHeight(), Color.white, Color.black, g); } if (x2 != 0 && y2 != 0) { g.setColor(Color.red); g.drawRect(x, y, tx - x, ty - y); RendererUtils.drawMovingRect(x, y, tx - x, ty - y, g, seed); } } } @Override protected void finalize() { thread.interrupt(); } @Override public void nativeMouseDragged(NativeMouseEvent arg0) { x2 = arg0.getX() - rect.x; y2 = arg0.getY() - rect.y; repaint(); } @Override public void nativeMouseMoved(NativeMouseEvent arg0) { } @Override public void mouseDragged(MouseEvent arg0) { dragging = true; } @Override public void mouseMoved(MouseEvent arg0) { if (!dragging && x2 == 0 && y2 == 0) { x = arg0.getX(); y = arg0.getY(); } repaint(); } @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { dragging = true; x = arg0.getX(); y = arg0.getY(); x2 = 0; y2 = 0; repaint(); } @Override public void mouseReleased(MouseEvent arg0) { dragging = false; repaint(); } }
src/com/redpois0n/guiscrot/CoverFrame.java
package com.redpois0n.guiscrot; import java.awt.AWTException; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Robot; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.event.MouseInputListener; import org.jnativehook.GlobalScreen; import org.jnativehook.mouse.NativeMouseEvent; import org.jnativehook.mouse.NativeMouseMotionListener; @SuppressWarnings("serial") public class CoverFrame extends JFrame implements MouseMotionListener, MouseInputListener, NativeMouseMotionListener { public static final float OPACITY = 0.5F; private Rectangle rect; private Image image; private int x; private int y; private int x2; private int y2; private boolean dragging; private int seed; private RepaintThread thread; public CoverFrame(Rectangle rect) { this(rect, null); } public CoverFrame(Rectangle rect, Image image) { this.rect = rect; this.image = image; GlobalScreen.addNativeMouseMotionListener(this); setUndecorated(true); setBounds(rect); setContentPane(new CoverPanel()); addMouseListener(this); addMouseMotionListener(this); if (image == null) { setOpacity(OPACITY); } thread = new RepaintThread(); thread.start(); } private class RepaintThread extends Thread { @Override public void run() { while (!interrupted()) { if (seed++ >= 20) { seed = 0; } repaint(); try { Thread.sleep(100L); } catch (Exception ex) { ex.printStackTrace(); } } } } private class CoverPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (g instanceof Graphics2D) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); } if (x > x2 && x2 != 0) { int temp = x; x = x2; x2 = temp; } if (y > y2 && y2 != 0) { int temp = y; y = y2; y2 = temp; } /** If nothing is selected, default to x and y**/ int tx = x2 == 0 ? x : x2; int ty = y2 == 0 ? y : y2; if (image != null) { /** Draw image over frame **/ g.drawImage(image, 0, 0, getWidth(), getHeight(), null); /** Set color to transparent black **/ g.setColor(new Color(0, 0, 0, 100)); /** Draw black transparent color over all areas that isn't being selected **/ g.fillRect(0, 0, x, getHeight()); g.fillRect(x, 0, getWidth(), y); g.fillRect(tx, y, getWidth(), getHeight()); g.fillRect(x, ty, tx - x, getHeight()); } else { g.setColor(Color.black); g.fillRect(0, 0, getWidth(), getHeight()); } g.setColor(Color.white); RendererUtils.drawMovingRect(x, 0, 1, getHeight(), g, seed); RendererUtils.drawMovingRect(0, y, getWidth(), 1, g, seed); g.setFont(new Font("Arial", Font.BOLD, 16)); RendererUtils.drawOutlinedString("X " + (x + rect.x) + " / Y " + (y + rect.y), x + 2, y - 2, Color.white, Color.black, g); if (dragging) { RendererUtils.drawOutlinedString("Width " + (x2 - x) + " / Height " + (y2 - y), x + 2, y - 4 - g.getFontMetrics().getHeight(), Color.white, Color.black, g); } if (x2 != 0 && y2 != 0) { g.setColor(Color.red); g.drawRect(x, y, tx - x, ty - y); RendererUtils.drawMovingRect(x, y, tx - x, ty - y, g, seed); } } } @Override protected void finalize() { thread.interrupt(); } @Override public void nativeMouseDragged(NativeMouseEvent arg0) { x2 = arg0.getX() - rect.x; y2 = arg0.getY() - rect.y; repaint(); } @Override public void nativeMouseMoved(NativeMouseEvent arg0) { } @Override public void mouseDragged(MouseEvent arg0) { dragging = true; } @Override public void mouseMoved(MouseEvent arg0) { if (!dragging) { x = arg0.getX();// - rect.x; y = arg0.getY();// - rect.y; } repaint(); } @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { dragging = true; repaint(); } @Override public void mouseReleased(MouseEvent arg0) { dragging = false; x2 = 0; y2 = 0; repaint(); } }
Behavior changed
src/com/redpois0n/guiscrot/CoverFrame.java
Behavior changed
<ide><path>rc/com/redpois0n/guiscrot/CoverFrame.java <ide> <ide> RendererUtils.drawOutlinedString("X " + (x + rect.x) + " / Y " + (y + rect.y), x + 2, y - 2, Color.white, Color.black, g); <ide> <del> if (dragging) { <add> if (x2 != 0 && y2 != 0) { <ide> RendererUtils.drawOutlinedString("Width " + (x2 - x) + " / Height " + (y2 - y), x + 2, y - 4 - g.getFontMetrics().getHeight(), Color.white, Color.black, g); <ide> } <del> <add> <ide> if (x2 != 0 && y2 != 0) { <ide> g.setColor(Color.red); <ide> g.drawRect(x, y, tx - x, ty - y); <ide> <ide> @Override <ide> public void mouseMoved(MouseEvent arg0) { <del> if (!dragging) { <del> x = arg0.getX();// - rect.x; <del> y = arg0.getY();// - rect.y; <add> if (!dragging && x2 == 0 && y2 == 0) { <add> x = arg0.getX(); <add> y = arg0.getY(); <ide> } <ide> <ide> repaint(); <ide> @Override <ide> public void mousePressed(MouseEvent arg0) { <ide> dragging = true; <del> <add> x = arg0.getX(); <add> y = arg0.getY(); <add> x2 = 0; <add> y2 = 0; <ide> repaint(); <ide> } <ide> <ide> @Override <ide> public void mouseReleased(MouseEvent arg0) { <ide> dragging = false; <del> x2 = 0; <del> y2 = 0; <ide> repaint(); <ide> } <ide>
Java
apache-2.0
2c817225e4551c8dec5ba39d56bc60dbc06ea154
0
dhmay/msInspect,dhmay/msInspect,dhmay/msInspect
/* * Copyright (c) 2003-2007 Fred Hutchinson Cancer Research 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 org.fhcrc.cpl.viewer.amt.commandline; import org.fhcrc.cpl.viewer.commandline.modules.BaseCommandLineModuleImpl; import org.fhcrc.cpl.viewer.commandline.arguments.*; import org.fhcrc.cpl.viewer.amt.*; import org.fhcrc.cpl.viewer.feature.FeatureSet; import org.fhcrc.cpl.toolbox.ApplicationContext; import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException; import org.fhcrc.cpl.toolbox.commandline.CommandLineModule; import org.fhcrc.cpl.toolbox.commandline.arguments.CommandLineArgumentDefinition; import org.fhcrc.cpl.toolbox.commandline.arguments.ArgumentValidationException; import org.fhcrc.cpl.toolbox.commandline.arguments.EnumeratedValuesArgumentDefinition; import org.fhcrc.cpl.toolbox.commandline.arguments.ArgumentDefinitionFactory; import org.apache.log4j.Logger; import java.io.File; /** * Command linemodule for refining AMT databases */ public class AmtDatabaseManagerCommandLineModule extends BaseCommandLineModuleImpl implements CommandLineModule { protected static Logger _log = Logger.getLogger(AmtDatabaseManagerCommandLineModule.class); protected AmtDatabase amtDatabase = null; protected File outFile = null; boolean fromAcrylamideToNot = true; protected int mode=-1; protected static final int REMOVE_OUTLIER_OBSERVATIONS_MODE=0; protected static final int REMOVE_PREDICTED_H_OUTLIERS_MODE=1; protected static final int REMOVE_FEW_OBSERVATIONS_MODE=2; protected static final int REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE=3; protected static final int ALIGN_ALL_RUNS_MODE=4; protected static final int ADJUST_ACRYLAMIDE_MODE=5; protected static final int REMOVE_PEPTIDES_WITH_RESIDUE_MODE=6; protected float predictedHOutlierDeviationMultipleCutoff = .001f; protected final static String[] modeStrings = { "removeoutlierobservations", "removepredictedhoutliers", "removefewobservations", "removerunswithoutmassmatches", "alignallruns", "adjustacrylamide", "removepeptideswithresidue", }; protected static final String[] modeExplanations = { "Remove all individual observations that are at least 3 standard deviations from the median for that peptide, for peptides with at least three observations", "Remove all peptides with only one observation, for which that observation is at least 2 standard deviations away from the prediction", "Remove all peptides with fewer than minobservations observations", "Make mass matches between each run's entries and an MS1 feature file. Remove all runs that don't mass-match at least minmassmatchpercent percent of peptides", "Nonlinearly align all runs in the database to a single run, starting with the run with the " + "most peptide overlap with other runs in the database. This is an extremely important step.", "Adjust all Cysteine-bearing observations to take the H contribution of acrylamide into account. Direction of adjustment depends on the 'fromacryltonot' parameter", "Remove all peptides containing a given residue" }; protected int minObservations = 2; protected int minMassMatchPercent = 20; protected int maxEntriesInMassMatchedDatabase = Integer.MAX_VALUE; protected int maxRunsInMassMatchedDatabase = Integer.MAX_VALUE; protected FeatureSet ms1FeatureSet = null; protected boolean showCharts = false; protected String residueToRemove = null; //todo: parameterize protected float massMatchDeltaMass = AmtDatabaseMatcher.DEFAULT_MASS_MATCH_DELTA_MASS; protected int massMatchDeltaMassType = AmtDatabaseMatcher.DEFAULT_MASS_MATCH_DELTA_MASS_TYPE; public AmtDatabaseManagerCommandLineModule() { init(); } protected void init() { mCommandName = "manageamt"; mShortDescription = "Tools for managing an AMT database"; mHelpMessage = "Refine an AMT database by removing outlier observations or peptides, " + "or nonlinearly aligning all runs to each other"; CommandLineArgumentDefinition[] basicArgDefs = { createEnumeratedArgumentDefinition("mode",true,modeStrings, modeExplanations), createFileToWriteArgumentDefinition("out", false, null), createUnnamedFileArgumentDefinition(true, "AMT database file"), createIntegerArgumentDefinition("minobservations", false, "Minimum number of observations for features kept in the database", minObservations), createBooleanArgumentDefinition("showcharts", false, "Show charts?", showCharts), createStringArgumentDefinition("residue", false, "Residue (for 'removepeptideswithresidue' mode)") }; addArgumentDefinitions(basicArgDefs); CommandLineArgumentDefinition[] advancedArgDefs = { createIntegerArgumentDefinition("minmassmatchpercent", false, "Minimum percent of peptides mass-matched to MS1, per run " + "(removerunswithoutmassmatches mode only)", minMassMatchPercent), createIntegerArgumentDefinition("maxentries", false, "Maximum DB entries (removerunswithoutmassmatches mode only)", maxEntriesInMassMatchedDatabase), createIntegerArgumentDefinition("maxruns", false, "Maximum DB runs (removerunswithoutmassmatches mode only)", maxRunsInMassMatchedDatabase), createFeatureFileArgumentDefinition("ms1features", false, "MS1 features (removerunswithoutmassmatches mode only)"), createBooleanArgumentDefinition("fromacryltonot", false, "For mode adjustacrylamide. If true, adjusts all observations to _remove_ the effect " + " of acrylamide. If false, adjusts observations to _add_ the effect.") }; addArgumentDefinitions(advancedArgDefs, true); } public void assignArgumentValues() throws ArgumentValidationException { mode = ((EnumeratedValuesArgumentDefinition) getArgumentDefinition("mode")).getIndexForArgumentValue(getStringArgumentValue("mode")); File dbFile = getFileArgumentValue(CommandLineArgumentDefinition.UNNAMED_PARAMETER_VALUE_ARGUMENT); try { AmtXmlReader amtXmlReader = new AmtXmlReader(dbFile); amtDatabase = amtXmlReader.getDatabase(); _log.info("Loaded AMT database: " + amtDatabase); } catch (Exception e) { throw new ArgumentValidationException(e); } if (mode == REMOVE_FEW_OBSERVATIONS_MODE) { assertArgumentPresent("minobservations"); minObservations = getIntegerArgumentValue("minobservations"); } else assertArgumentAbsent("minobservations"); if (mode == REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE) { assertArgumentPresent("minmassmatchpercent"); minMassMatchPercent = getIntegerArgumentValue("minmassmatchpercent"); assertArgumentPresent("ms1features"); ms1FeatureSet = getFeatureSetArgumentValue("ms1features"); assertArgumentPresent("maxentries"); maxEntriesInMassMatchedDatabase = getIntegerArgumentValue("maxentries"); maxRunsInMassMatchedDatabase = getIntegerArgumentValue("maxruns"); } else { assertArgumentAbsent("minmassmatchpercent"); assertArgumentAbsent("ms1features"); } if (mode == ADJUST_ACRYLAMIDE_MODE) { assertArgumentPresent("fromacryltonot"); fromAcrylamideToNot = getBooleanArgumentValue("fromacryltonot"); } else { assertArgumentAbsent("fromacryltonot"); } residueToRemove = getStringArgumentValue("residue"); if (mode == REMOVE_PEPTIDES_WITH_RESIDUE_MODE) assertArgumentPresent("residue","mode"); outFile = getFileArgumentValue("out"); showCharts = getBooleanArgumentValue("showcharts"); } /** * do the actual work */ public void execute() throws CommandLineModuleExecutionException { ApplicationContext.infoMessage("Read AMT Database with " + amtDatabase.numEntries() + " entries."); switch (mode) { case REMOVE_OUTLIER_OBSERVATIONS_MODE: { int numObsBefore = 0; for (AmtRunEntry runEntry : amtDatabase.getRuns()) numObsBefore += amtDatabase.getObservationsForRun(runEntry).length; //todo: parameterize AmtDatabaseManager.removeHydrophobicityOutliers(amtDatabase, 3); int numObsAfter = 0; for (AmtRunEntry runEntry : amtDatabase.getRuns()) numObsAfter += amtDatabase.getObservationsForRun(runEntry).length; ApplicationContext.infoMessage("\nRemoved " + (numObsBefore - numObsAfter) + " observations (out of " + numObsBefore + ")"); break; } case REMOVE_PREDICTED_H_OUTLIERS_MODE: { //todo: parameterize double maxHDiff = amtDatabase.calculateMeanDifferenceFromPredictedHydro() + (predictedHOutlierDeviationMultipleCutoff * amtDatabase.calculateStandardDeviationDifferenceFromPredictedHydro()); ApplicationContext.infoMessage("Removing entries with one observation and observed hydro > " + maxHDiff + " different from predicted"); AmtDatabaseManager.removePredictedHOutliers(amtDatabase, (float) maxHDiff); break; } case REMOVE_FEW_OBSERVATIONS_MODE: { ApplicationContext.infoMessage("Removing entries with less than " + minObservations + " observations"); for (AmtPeptideEntry peptideEntry : amtDatabase.getEntries()) { if (peptideEntry.getNumObservations() < minObservations) amtDatabase.removeEntry(peptideEntry.getPeptideSequence()); } break; } case REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE: { amtDatabase = AmtDatabaseManager.removeRunsWithoutMassMatches( amtDatabase, ms1FeatureSet.getFeatures(), minMassMatchPercent, massMatchDeltaMass, massMatchDeltaMassType, maxEntriesInMassMatchedDatabase, maxRunsInMassMatchedDatabase, AmtDatabaseMatcherCLM.defaultMS2ModificationsForMatching, showCharts); break; } case ALIGN_ALL_RUNS_MODE: { amtDatabase = AmtDatabaseManager.alignAllRunsUsingCommonPeptides( amtDatabase, 10, showCharts); // ApplicationContext.infoMessage("Repeating..."); // amtDatabase = // AmtDatabaseManager.alignAllRunsUsingCommonPeptides(amtDatabase, 10, showCharts); break; } case ADJUST_ACRYLAMIDE_MODE: { amtDatabase = AmtDatabaseManager.adjustEntriesForAcrylamide( amtDatabase, fromAcrylamideToNot, showCharts); break; } case REMOVE_PEPTIDES_WITH_RESIDUE_MODE: { ApplicationContext.infoMessage("Removing all peptides containing '" + residueToRemove + "'..."); for (AmtPeptideEntry peptideEntry : amtDatabase.getEntries()) { if (peptideEntry.getPeptideSequence().contains(residueToRemove)) amtDatabase.removeEntry(peptideEntry.getPeptideSequence()); } } } if (outFile != null && amtDatabase != null) writeAmtDatabase(amtDatabase, outFile); } /** * * @param amtDatabase * @param outAmtXmlFile */ protected static void writeAmtDatabase(AmtDatabase amtDatabase, File outAmtXmlFile) { try { AmtXmlWriter amtXmlWriter = new AmtXmlWriter(amtDatabase); amtXmlWriter.write(outAmtXmlFile); ApplicationContext.infoMessage("Wrote " + amtDatabase.numEntries() + " entries to amtxml file " + outAmtXmlFile.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(System.err); ApplicationContext.infoMessage("Error writing amt file " + outAmtXmlFile.getAbsolutePath()); } } }
src/org/fhcrc/cpl/viewer/amt/commandline/AmtDatabaseManagerCommandLineModule.java
/* * Copyright (c) 2003-2007 Fred Hutchinson Cancer Research 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 org.fhcrc.cpl.viewer.amt.commandline; import org.fhcrc.cpl.viewer.commandline.modules.BaseCommandLineModuleImpl; import org.fhcrc.cpl.viewer.commandline.arguments.*; import org.fhcrc.cpl.viewer.amt.*; import org.fhcrc.cpl.viewer.feature.FeatureSet; import org.fhcrc.cpl.toolbox.ApplicationContext; import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException; import org.fhcrc.cpl.toolbox.commandline.CommandLineModule; import org.fhcrc.cpl.toolbox.commandline.arguments.CommandLineArgumentDefinition; import org.fhcrc.cpl.toolbox.commandline.arguments.ArgumentValidationException; import org.fhcrc.cpl.toolbox.commandline.arguments.EnumeratedValuesArgumentDefinition; import org.fhcrc.cpl.toolbox.commandline.arguments.ArgumentDefinitionFactory; import org.apache.log4j.Logger; import java.io.File; /** * Command linemodule for refining AMT databases */ public class AmtDatabaseManagerCommandLineModule extends BaseCommandLineModuleImpl implements CommandLineModule { protected static Logger _log = Logger.getLogger(AmtDatabaseManagerCommandLineModule.class); protected AmtDatabase amtDatabase = null; protected File outFile = null; boolean fromAcrylamideToNot = true; protected int mode=-1; protected static final int REMOVE_OUTLIER_OBSERVATIONS_MODE=0; protected static final int REMOVE_PREDICTED_H_OUTLIERS_MODE=1; protected static final int REMOVE_FEW_OBSERVATIONS_MODE=2; protected static final int REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE=3; protected static final int ALIGN_ALL_RUNS_MODE=4; protected static final int ADJUST_ACRYLAMIDE_MODE=5; protected float predictedHOutlierDeviationMultipleCutoff = .001f; protected final static String[] modeStrings = { "removeoutlierobservations", "removepredictedhoutliers","removefewobservations", "removerunswithoutmassmatches", "alignallruns", "adjustacrylamide" }; protected static final String[] modeExplanations = { "Remove all individual observations that are at least 3 standard deviations from the median for that peptide, for peptides with at least three observations", "Remove all peptides with only one observation, for which that observation is at least 2 standard deviations away from the prediction", "Remove all peptides with fewer than minobservations observations", "Make mass matches between each run's entries and an MS1 feature file. Remove all runs that don't mass-match at least minmassmatchpercent percent of peptides", "Nonlinearly align all runs in the database to a single run, starting with the run with the " + "most peptide overlap with other runs in the database. This is an extremely important step.", "Adjust all Cysteine-bearing observations to take the H contribution of acrylamide into account. Direction of adjustment depends on the 'fromacryltonot' parameter", }; protected int minObservations = 2; protected int minMassMatchPercent = 20; protected int maxEntriesInMassMatchedDatabase = Integer.MAX_VALUE; protected int maxRunsInMassMatchedDatabase = Integer.MAX_VALUE; protected FeatureSet ms1FeatureSet = null; protected boolean showCharts = false; //todo: parameterize protected float massMatchDeltaMass = AmtDatabaseMatcher.DEFAULT_MASS_MATCH_DELTA_MASS; protected int massMatchDeltaMassType = AmtDatabaseMatcher.DEFAULT_MASS_MATCH_DELTA_MASS_TYPE; public AmtDatabaseManagerCommandLineModule() { init(); } protected void init() { mCommandName = "manageamt"; mShortDescription = "Tools for managing an AMT database"; mHelpMessage = "Refine an AMT database by removing outlier observations or peptides, " + "or nonlinearly aligning all runs to each other"; CommandLineArgumentDefinition[] basicArgDefs = { createEnumeratedArgumentDefinition("mode",true,modeStrings, modeExplanations), createFileToWriteArgumentDefinition("out", false, null), createUnnamedFileArgumentDefinition(true, "AMT database file"), createIntegerArgumentDefinition("minobservations", false, "Minimum number of observations for features kept in the database", minObservations), createBooleanArgumentDefinition("showcharts", false, "Show charts?", showCharts), }; addArgumentDefinitions(basicArgDefs); CommandLineArgumentDefinition[] advancedArgDefs = { createIntegerArgumentDefinition("minmassmatchpercent", false, "Minimum percent of peptides mass-matched to MS1, per run " + "(removerunswithoutmassmatches mode only)", minMassMatchPercent), createIntegerArgumentDefinition("maxentries", false, "Maximum DB entries (removerunswithoutmassmatches mode only)", maxEntriesInMassMatchedDatabase), createIntegerArgumentDefinition("maxruns", false, "Maximum DB runs (removerunswithoutmassmatches mode only)", maxRunsInMassMatchedDatabase), createFeatureFileArgumentDefinition("ms1features", false, "MS1 features (removerunswithoutmassmatches mode only)"), createBooleanArgumentDefinition("fromacryltonot", false, "For mode adjustacrylamide. If true, adjusts all observations to _remove_ the effect " + " of acrylamide. If false, adjusts observations to _add_ the effect.") }; addArgumentDefinitions(advancedArgDefs, true); } public void assignArgumentValues() throws ArgumentValidationException { mode = ((EnumeratedValuesArgumentDefinition) getArgumentDefinition("mode")).getIndexForArgumentValue(getStringArgumentValue("mode")); File dbFile = getFileArgumentValue(CommandLineArgumentDefinition.UNNAMED_PARAMETER_VALUE_ARGUMENT); try { AmtXmlReader amtXmlReader = new AmtXmlReader(dbFile); amtDatabase = amtXmlReader.getDatabase(); _log.info("Loaded AMT database: " + amtDatabase); } catch (Exception e) { throw new ArgumentValidationException(e); } if (mode == REMOVE_FEW_OBSERVATIONS_MODE) { assertArgumentPresent("minobservations"); minObservations = getIntegerArgumentValue("minobservations"); } else assertArgumentAbsent("minobservations"); if (mode == REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE) { assertArgumentPresent("minmassmatchpercent"); minMassMatchPercent = getIntegerArgumentValue("minmassmatchpercent"); assertArgumentPresent("ms1features"); ms1FeatureSet = getFeatureSetArgumentValue("ms1features"); assertArgumentPresent("maxentries"); maxEntriesInMassMatchedDatabase = getIntegerArgumentValue("maxentries"); maxRunsInMassMatchedDatabase = getIntegerArgumentValue("maxruns"); } else { assertArgumentAbsent("minmassmatchpercent"); assertArgumentAbsent("ms1features"); } if (mode == ADJUST_ACRYLAMIDE_MODE) { assertArgumentPresent("fromacryltonot"); fromAcrylamideToNot = getBooleanArgumentValue("fromacryltonot"); } else { assertArgumentAbsent("fromacryltonot"); } outFile = getFileArgumentValue("out"); showCharts = getBooleanArgumentValue("showcharts"); } /** * do the actual work */ public void execute() throws CommandLineModuleExecutionException { switch (mode) { case REMOVE_OUTLIER_OBSERVATIONS_MODE: { int numObsBefore = 0; for (AmtRunEntry runEntry : amtDatabase.getRuns()) numObsBefore += amtDatabase.getObservationsForRun(runEntry).length; //todo: parameterize AmtDatabaseManager.removeHydrophobicityOutliers(amtDatabase, 3); int numObsAfter = 0; for (AmtRunEntry runEntry : amtDatabase.getRuns()) numObsAfter += amtDatabase.getObservationsForRun(runEntry).length; ApplicationContext.infoMessage("\nRemoved " + (numObsBefore - numObsAfter) + " observations (out of " + numObsBefore + ")"); break; } case REMOVE_PREDICTED_H_OUTLIERS_MODE: { //todo: parameterize double maxHDiff = amtDatabase.calculateMeanDifferenceFromPredictedHydro() + (predictedHOutlierDeviationMultipleCutoff * amtDatabase.calculateStandardDeviationDifferenceFromPredictedHydro()); ApplicationContext.infoMessage("Removing entries with one observation and observed hydro > " + maxHDiff + " different from predicted"); AmtDatabaseManager.removePredictedHOutliers(amtDatabase, (float) maxHDiff); break; } case REMOVE_FEW_OBSERVATIONS_MODE: { ApplicationContext.infoMessage("Removing entries with less than " + minObservations + " observations"); for (AmtPeptideEntry peptideEntry : amtDatabase.getEntries()) { if (peptideEntry.getNumObservations() < minObservations) amtDatabase.removeEntry(peptideEntry.getPeptideSequence()); } break; } case REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE: { amtDatabase = AmtDatabaseManager.removeRunsWithoutMassMatches( amtDatabase, ms1FeatureSet.getFeatures(), minMassMatchPercent, massMatchDeltaMass, massMatchDeltaMassType, maxEntriesInMassMatchedDatabase, maxRunsInMassMatchedDatabase, AmtDatabaseMatcherCLM.defaultMS2ModificationsForMatching, showCharts); break; } case ALIGN_ALL_RUNS_MODE: { amtDatabase = AmtDatabaseManager.alignAllRunsUsingCommonPeptides( amtDatabase, 10, showCharts); // ApplicationContext.infoMessage("Repeating..."); // amtDatabase = // AmtDatabaseManager.alignAllRunsUsingCommonPeptides(amtDatabase, 10, showCharts); break; } case ADJUST_ACRYLAMIDE_MODE: { amtDatabase = AmtDatabaseManager.adjustEntriesForAcrylamide( amtDatabase, fromAcrylamideToNot, showCharts); break; } } if (outFile != null && amtDatabase != null) writeAmtDatabase(amtDatabase, outFile); } /** * * @param amtDatabase * @param outAmtXmlFile */ protected static void writeAmtDatabase(AmtDatabase amtDatabase, File outAmtXmlFile) { try { AmtXmlWriter amtXmlWriter = new AmtXmlWriter(amtDatabase); amtXmlWriter.write(outAmtXmlFile); ApplicationContext.infoMessage("Wrote " + amtDatabase.numEntries() + " entries to amtxml file " + outAmtXmlFile.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(System.err); ApplicationContext.infoMessage("Error writing amt file " + outAmtXmlFile.getAbsolutePath()); } } }
adding the ability to strip peptides containing a particular residue from AMT databases
src/org/fhcrc/cpl/viewer/amt/commandline/AmtDatabaseManagerCommandLineModule.java
adding the ability to strip peptides containing a particular residue from AMT databases
<ide><path>rc/org/fhcrc/cpl/viewer/amt/commandline/AmtDatabaseManagerCommandLineModule.java <ide> protected static final int REMOVE_RUNS_WITHOUT_MASS_MATCHES_MODE=3; <ide> protected static final int ALIGN_ALL_RUNS_MODE=4; <ide> protected static final int ADJUST_ACRYLAMIDE_MODE=5; <add> protected static final int REMOVE_PEPTIDES_WITH_RESIDUE_MODE=6; <add> <ide> <ide> protected float predictedHOutlierDeviationMultipleCutoff = .001f; <ide> <ide> <ide> protected final static String[] modeStrings = { <ide> "removeoutlierobservations", <del> "removepredictedhoutliers","removefewobservations", <add> "removepredictedhoutliers", <add> "removefewobservations", <ide> "removerunswithoutmassmatches", <ide> "alignallruns", <del> "adjustacrylamide" <add> "adjustacrylamide", <add> "removepeptideswithresidue", <ide> }; <ide> <ide> protected static final String[] modeExplanations = <ide> "Nonlinearly align all runs in the database to a single run, starting with the run with the " + <ide> "most peptide overlap with other runs in the database. This is an extremely important step.", <ide> "Adjust all Cysteine-bearing observations to take the H contribution of acrylamide into account. Direction of adjustment depends on the 'fromacryltonot' parameter", <add> "Remove all peptides containing a given residue" <ide> }; <ide> <ide> protected int minObservations = 2; <ide> <ide> protected FeatureSet ms1FeatureSet = null; <ide> protected boolean showCharts = false; <add> <add> <add> protected String residueToRemove = null; <ide> <ide> //todo: parameterize <ide> protected float massMatchDeltaMass = AmtDatabaseMatcher.DEFAULT_MASS_MATCH_DELTA_MASS; <ide> minObservations), <ide> createBooleanArgumentDefinition("showcharts", false, <ide> "Show charts?", showCharts), <add> createStringArgumentDefinition("residue", false, <add> "Residue (for 'removepeptideswithresidue' mode)") <ide> }; <ide> addArgumentDefinitions(basicArgDefs); <ide> <ide> assertArgumentAbsent("fromacryltonot"); <ide> } <ide> <add> residueToRemove = getStringArgumentValue("residue"); <add> if (mode == REMOVE_PEPTIDES_WITH_RESIDUE_MODE) <add> assertArgumentPresent("residue","mode"); <add> <ide> outFile = getFileArgumentValue("out"); <ide> <ide> showCharts = getBooleanArgumentValue("showcharts"); <ide> */ <ide> public void execute() throws CommandLineModuleExecutionException <ide> { <add> ApplicationContext.infoMessage("Read AMT Database with " + amtDatabase.numEntries() + " entries."); <ide> switch (mode) <ide> { <ide> case REMOVE_OUTLIER_OBSERVATIONS_MODE: <ide> <ide> break; <ide> } <add> case REMOVE_PEPTIDES_WITH_RESIDUE_MODE: <add> { <add> ApplicationContext.infoMessage("Removing all peptides containing '" + residueToRemove + "'..."); <add> for (AmtPeptideEntry peptideEntry : amtDatabase.getEntries()) <add> { <add> if (peptideEntry.getPeptideSequence().contains(residueToRemove)) <add> amtDatabase.removeEntry(peptideEntry.getPeptideSequence()); <add> } <add> } <ide> } <ide> if (outFile != null && amtDatabase != null) <ide> writeAmtDatabase(amtDatabase, outFile);
Java
mit
7d3a266185e1dbab312427f5b8a67537c1affd26
0
eaglesakura/andriders-central-engine-sdk
package com.eaglesakura.andriders.central; import com.eaglesakura.andriders.command.CommandKey; import com.eaglesakura.andriders.serialize.NotificationProtocol; import com.eaglesakura.andriders.serialize.RawIntent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.List; /** * Centralに送信された通知情報をハンドリングする */ public abstract class CentralNotificationHandler { /** * 新たに通知が発行された */ public void onReceivedNotification(@NonNull NotificationProtocol.RawNotification notification) { } /** * コマンドの起動が行われた * * @param key 起動されたコマンドキー * @param aceInternalExtras 起動されたコマンドのACEオプション(ACEのアップデートにより変動の可能性があるため、信頼性はない) */ public void onReceivedCommandBoot(@NonNull CommandKey key, @Nullable List<RawIntent.Extra> aceInternalExtras) { } }
src/main/java/com/eaglesakura/andriders/central/CentralNotificationHandler.java
package com.eaglesakura.andriders.central; import com.eaglesakura.andriders.command.CommandKey; import com.eaglesakura.andriders.command.SerializableIntent; import com.eaglesakura.andriders.serialize.NotificationProtocol; import com.eaglesakura.andriders.serialize.RawIntent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.List; /** * Centralに送信された通知情報をハンドリングする */ public abstract class CentralNotificationHandler { /** * 新たに通知が発行された */ public void onReceivedNotification(@NonNull NotificationProtocol.RawNotification notification) { } /** * コマンドの起動が行われた * * @param key 起動されたコマンドキー * @param aceInternalExtras 起動されたコマンドのACEオプション(ACEのアップデートにより変動の可能性があるため、信頼性はない) */ public void onReceivedCommandBoot(@NonNull CommandKey key, @Nullable List<RawIntent.Extra> aceInternalExtras) { } }
import整理
src/main/java/com/eaglesakura/andriders/central/CentralNotificationHandler.java
import整理
<ide><path>rc/main/java/com/eaglesakura/andriders/central/CentralNotificationHandler.java <ide> package com.eaglesakura.andriders.central; <ide> <ide> import com.eaglesakura.andriders.command.CommandKey; <del>import com.eaglesakura.andriders.command.SerializableIntent; <ide> import com.eaglesakura.andriders.serialize.NotificationProtocol; <ide> import com.eaglesakura.andriders.serialize.RawIntent; <ide>
Java
bsd-2-clause
361b1315e6819747c0ed3bcb854824d65e2bda37
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
/* * Copyright (c) 2003-2005 jMonkeyEngine * 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 'jMonkeyEngine' 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 jmetest; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.Collection; import java.util.Enumeration; import java.util.Vector; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import jmetest.curve.TestBezierCurve; import jmetest.effects.TestDynamicSmoker; import jmetest.effects.TestParticleSystem; import jmetest.effects.cloth.TestCloth; import jmetest.input.TestThirdPersonController; import jmetest.intersection.TestCollision; import jmetest.intersection.TestOBBPick; import jmetest.intersection.TestOBBTree; import jmetest.intersection.TestPick; import jmetest.renderer.TestAnisotropic; import jmetest.renderer.TestAutoClodMesh; import jmetest.renderer.TestBezierMesh; import jmetest.renderer.TestBoxColor; import jmetest.renderer.TestCameraMan; import jmetest.renderer.TestDiscreteLOD; import jmetest.renderer.TestEnvMap; import jmetest.renderer.TestImposterNode; import jmetest.renderer.TestMultitexture; import jmetest.renderer.TestPQTorus; import jmetest.renderer.TestRenderQueue; import jmetest.renderer.TestRenderToTexture; import jmetest.renderer.TestScenegraph; import jmetest.renderer.TestSkybox; import jmetest.renderer.loader.TestASEJmeWrite; import jmetest.renderer.loader.TestFireMilk; import jmetest.renderer.loader.TestMaxJmeWrite; import jmetest.renderer.loader.TestMd2JmeWrite; import jmetest.renderer.loader.TestMilkJmeWrite; import jmetest.renderer.loader.TestObjJmeWrite; import jmetest.renderer.state.TestFragmentProgramState; import jmetest.renderer.state.TestGLSLShaderObjectsState; import jmetest.renderer.state.TestLightState; import jmetest.renderer.state.TestVertexProgramState; import jmetest.terrain.TestTerrain; import jmetest.terrain.TestTerrainLighting; import jmetest.terrain.TestTerrainPage; import org.lwjgl.Sys; /** * Class with a main method that displays a dialog to choose any jME demo to be started. */ public class TestChooser extends JDialog { private static final long serialVersionUID = 1L; /** * Constructs a new TestChooser that is initially invisible. */ public TestChooser() throws HeadlessException { super( (JFrame) null, "TestChooser", true ); } /** * @param classes vector that receives the found classes * @return classes vector, list of all the classes in a given package (must be found in classpath). */ protected Vector find( String pckgname, boolean recursive, Vector classes ) { URL url; // Translate the package name into an absolute path String name = new String( pckgname ); if ( !name.startsWith( "/" ) ) { name = "/" + name; } name = name.replace( '.', '/' ); // Get a File object for the package // URL url = UPBClassLoader.get().getResource(name); url = this.getClass().getResource( name ); // URL url = ClassLoader.getSystemClassLoader().getResource(name); pckgname = pckgname + "."; File directory; try { directory = new File( URLDecoder.decode( url.getFile(), "UTF-8" ) ); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( e ); //should never happen } if ( directory.exists() ) { System.out.println( "Searching for Demo classes in \"" + directory.getName() + "\"." ); addAllFilesInDirectory( directory, classes, pckgname, recursive ); } else { try { // It does not work with the filesystem: we must // be in the case of a package contained in a jar file. System.out.println( "Searching for Demo classes in \"" + url + "\"." ); URLConnection urlConnection = url.openConnection(); if ( urlConnection instanceof JarURLConnection ) { JarURLConnection conn = (JarURLConnection) urlConnection; JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while ( e.hasMoreElements() ) { ZipEntry entry = (ZipEntry) e.nextElement(); Class result = load( entry.getName() ); if ( result != null ) { classes.add( result ); } } } } catch ( IOException ioex ) { ioex.printStackTrace(); } catch ( Exception e ) { e.printStackTrace(); } } return classes; } /** * Load a class specified by a file- or entry-name * * @param name name of a file or entry * @return class file that was denoted by the name, null if no class or does not contain a main method */ private Class load( String name ) { if ( name.endsWith( ".class" ) && name.indexOf( "Test" ) >= 0 && name.indexOf( '$' ) < 0 ) { String classname = name.substring( 0, name.length() - ".class".length() ); if ( classname.startsWith( "/" ) ) { classname = classname.substring( 1 ); } classname = classname.replace( '/', '.' ); try { final Class cls = Class.forName( classname ); cls.getMethod( "main", new Class[]{String[].class} ); if ( !getClass().equals( cls ) ) { return cls; } } catch ( ClassNotFoundException e ) { //class not in classpath return null; } catch ( NoSuchMethodException e ) { //class does not have a main method return null; } } return null; } /** * Used to descent in directories, loads classes via {@link #load} * * @param directory where to search for class files * @param allClasses add loaded classes to this collection * @param packageName current package name for the diven directory * @param recursive true to descent into subdirectories */ private void addAllFilesInDirectory( File directory, Collection allClasses, String packageName, boolean recursive ) { // Get the list of the files contained in the package File[] files = directory.listFiles( getFileFilter() ); if ( files != null ) { for ( int i = 0; i < files.length; i++ ) { // we are only interested in .class files if ( files[i].isDirectory() ) { if ( recursive ) { addAllFilesInDirectory( files[i], allClasses, packageName + files[i].getName() + ".", true ); } } else { Class result = load( packageName + files[i].getName() ); if ( result != null ) { allClasses.add( result ); } } } } } /** * @return FileFilter for searching class files (no inner classes, only thos with "Test" in the name) */ private FileFilter getFileFilter() { return new FileFilter() { /** * @see FileFilter */ public boolean accept( File pathname ) { return pathname.isDirectory() || ( pathname.getName().endsWith( ".class" ) && pathname.getName().indexOf( "Test" ) >= 0 && pathname.getName().indexOf( '$' ) < 0 ); } }; } /** * getter for field selectedClass * * @return current value of field selectedClass */ public Class getSelectedClass() { return this.selectedClass; } /** * store the value for field selectedClass */ private Class selectedClass; /** * setter for field selectedClass * * @param value new value */ public void setSelectedClass( final Class value ) { final Class oldValue = this.selectedClass; if ( oldValue != value ) { this.selectedClass = value; firePropertyChange( "selectedClass", oldValue, value ); } } /** * Code to create components and action listeners. * * @param classes what Classes to show in the list box */ private void setup( Vector classes ) { final JPanel mainPanel = new JPanel(); mainPanel.setLayout( new BorderLayout() ); getContentPane().setLayout( new BorderLayout() ); getContentPane().add( mainPanel, BorderLayout.CENTER ); mainPanel.setBorder( new EmptyBorder( 10, 10, 10, 10 ) ); mainPanel.add( new JLabel( "Choose a Demo to start: " ), BorderLayout.NORTH ); final JList list = new JList( classes ); mainPanel.add( new JScrollPane( list ), BorderLayout.CENTER ); list.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent e ) { setSelectedClass( (Class) list.getSelectedValue() ); } } ); final JPanel buttonPanel = new JPanel( new FlowLayout( FlowLayout.CENTER ) ); mainPanel.add( buttonPanel, BorderLayout.PAGE_END ); final JButton okButton = new JButton( "Ok" ); okButton.setMnemonic( 'O' ); buttonPanel.add( okButton ); getRootPane().setDefaultButton( okButton ); okButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { dispose(); } } ); final JButton cancelButton = new JButton( "Cancel" ); cancelButton.setMnemonic( 'C' ); buttonPanel.add( cancelButton ); cancelButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { setSelectedClass( null ); dispose(); } } ); pack(); center(); } /** * center the frame. */ private void center() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = this.getSize(); if ( frameSize.height > screenSize.height ) { frameSize.height = screenSize.height; } if ( frameSize.width > screenSize.width ) { frameSize.width = screenSize.width; } this.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); } /** * Start the chooser. * * @param args command line parameters */ public static void main( String[] args ) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch ( Exception e ) { //ok, keep the ugly one then :\ } try { TestChooser chooser = new TestChooser(); final Vector classes = new Vector(); System.out.println( "Composing Test list..." ); Sys.class.getName(); //to check loading lwjgl library //put some featured tests at the beginning classes.add( TestCloth.class ); classes.add( TestEnvMap.class ); classes.add( TestMultitexture.class ); classes.add( TestParticleSystem.class ); classes.add( TestDynamicSmoker.class ); classes.add( TestFireMilk.class ); classes.add( TestThirdPersonController.class ); classes.add( TestBoxColor.class ); classes.add( TestLightState.class ); classes.add( TestRenderQueue.class ); classes.add( TestScenegraph.class ); classes.add( TestBezierMesh.class ); classes.add( TestBezierCurve.class ); classes.add( TestPQTorus.class ); classes.add( TestAnisotropic.class ); classes.add( TestCollision.class ); classes.add( TestOBBTree.class ); classes.add( TestPick.class ); classes.add( TestOBBPick.class ); classes.add( TestImposterNode.class ); classes.add( TestRenderToTexture.class ); classes.add( TestCameraMan.class ); classes.add( TestFragmentProgramState.class ); classes.add( TestGLSLShaderObjectsState.class ); classes.add( TestVertexProgramState.class ); classes.add( TestAutoClodMesh.class ); classes.add( TestDiscreteLOD.class ); classes.add( TestASEJmeWrite.class ); classes.add( TestMaxJmeWrite.class ); classes.add( TestMd2JmeWrite.class ); classes.add( TestMilkJmeWrite.class ); classes.add( TestObjJmeWrite.class ); classes.add( TestSkybox.class ); classes.add( TestTerrain.class ); classes.add( TestTerrainLighting.class ); classes.add( TestTerrainPage.class ); chooser.find( "jmetest", true, classes ); chooser.setup( classes ); Class cls; do { chooser.setVisible(true); cls = chooser.getSelectedClass(); if ( cls != null ) { try { final Method method = cls.getMethod( "main", new Class[]{String[].class} ); method.invoke( null, new Object[]{args} ); } catch ( NoSuchMethodException e ) { //should not happen (filtered non-main classes already) e.printStackTrace(); } catch ( IllegalAccessException e ) { //whoops non-public / non-static main method ?! e.printStackTrace(); } catch ( InvocationTargetException e ) { //exception in main e.printStackTrace(); } } } while ( cls != null ); System.exit( 0 ); } catch ( UnsatisfiedLinkError e ) { e.printStackTrace(); JOptionPane.showMessageDialog( null, "A required native library could not be loaded.\n" + "Specifying -Djava.library.path=./lib when invoking jME applications " + "or copying native libraries to your Java bin directory might help.\n" + "Error message was: " + e.getMessage(), "Error loading library", JOptionPane.ERROR_MESSAGE ); System.exit(-1); } } }
src/jmetest/TestChooser.java
/* * Copyright (c) 2003-2005 jMonkeyEngine * 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 'jMonkeyEngine' 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 jmetest; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.Collection; import java.util.Enumeration; import java.util.Vector; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import jmetest.curve.TestBezierCurve; import jmetest.effects.TestDynamicSmoker; import jmetest.effects.TestParticleSystem; import jmetest.effects.cloth.TestCloth; import jmetest.intersection.TestCollision; import jmetest.intersection.TestOBBPick; import jmetest.intersection.TestOBBTree; import jmetest.intersection.TestPick; import jmetest.renderer.TestAnisotropic; import jmetest.renderer.TestAutoClodMesh; import jmetest.renderer.TestBezierMesh; import jmetest.renderer.TestBoxColor; import jmetest.renderer.TestCameraMan; import jmetest.renderer.TestDiscreteLOD; import jmetest.renderer.TestEnvMap; import jmetest.renderer.TestImposterNode; import jmetest.renderer.TestMultitexture; import jmetest.renderer.TestPQTorus; import jmetest.renderer.TestRenderQueue; import jmetest.renderer.TestRenderToTexture; import jmetest.renderer.TestScenegraph; import jmetest.renderer.TestSkybox; import jmetest.renderer.loader.TestASEJmeWrite; import jmetest.renderer.loader.TestFireMilk; import jmetest.renderer.loader.TestMaxJmeWrite; import jmetest.renderer.loader.TestMd2JmeWrite; import jmetest.renderer.loader.TestMilkJmeWrite; import jmetest.renderer.loader.TestObjJmeWrite; import jmetest.renderer.state.TestFragmentProgramState; import jmetest.renderer.state.TestGLSLShaderObjectsState; import jmetest.renderer.state.TestLightState; import jmetest.renderer.state.TestVertexProgramState; import jmetest.terrain.TestTerrain; import jmetest.terrain.TestTerrainLighting; import jmetest.terrain.TestTerrainPage; import org.lwjgl.Sys; /** * Class with a main method that displays a dialog to choose any jME demo to be started. */ public class TestChooser extends JDialog { private static final long serialVersionUID = 1L; /** * Constructs a new TestChooser that is initially invisible. */ public TestChooser() throws HeadlessException { super( (JFrame) null, "TestChooser", true ); } /** * @param classes vector that receives the found classes * @return classes vector, list of all the classes in a given package (must be found in classpath). */ protected Vector find( String pckgname, boolean recursive, Vector classes ) { URL url; // Translate the package name into an absolute path String name = new String( pckgname ); if ( !name.startsWith( "/" ) ) { name = "/" + name; } name = name.replace( '.', '/' ); // Get a File object for the package // URL url = UPBClassLoader.get().getResource(name); url = this.getClass().getResource( name ); // URL url = ClassLoader.getSystemClassLoader().getResource(name); pckgname = pckgname + "."; File directory; try { directory = new File( URLDecoder.decode( url.getFile(), "UTF-8" ) ); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( e ); //should never happen } if ( directory.exists() ) { System.out.println( "Searching for Demo classes in \"" + directory.getName() + "\"." ); addAllFilesInDirectory( directory, classes, pckgname, recursive ); } else { try { // It does not work with the filesystem: we must // be in the case of a package contained in a jar file. System.out.println( "Searching for Demo classes in \"" + url + "\"." ); URLConnection urlConnection = url.openConnection(); if ( urlConnection instanceof JarURLConnection ) { JarURLConnection conn = (JarURLConnection) urlConnection; JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while ( e.hasMoreElements() ) { ZipEntry entry = (ZipEntry) e.nextElement(); Class result = load( entry.getName() ); if ( result != null ) { classes.add( result ); } } } } catch ( IOException ioex ) { ioex.printStackTrace(); } catch ( Exception e ) { e.printStackTrace(); } } return classes; } /** * Load a class specified by a file- or entry-name * * @param name name of a file or entry * @return class file that was denoted by the name, null if no class or does not contain a main method */ private Class load( String name ) { if ( name.endsWith( ".class" ) && name.indexOf( "Test" ) >= 0 && name.indexOf( '$' ) < 0 ) { String classname = name.substring( 0, name.length() - ".class".length() ); if ( classname.startsWith( "/" ) ) { classname = classname.substring( 1 ); } classname = classname.replace( '/', '.' ); try { final Class cls = Class.forName( classname ); cls.getMethod( "main", new Class[]{String[].class} ); if ( !getClass().equals( cls ) ) { return cls; } } catch ( ClassNotFoundException e ) { //class not in classpath return null; } catch ( NoSuchMethodException e ) { //class does not have a main method return null; } } return null; } /** * Used to descent in directories, loads classes via {@link #load} * * @param directory where to search for class files * @param allClasses add loaded classes to this collection * @param packageName current package name for the diven directory * @param recursive true to descent into subdirectories */ private void addAllFilesInDirectory( File directory, Collection allClasses, String packageName, boolean recursive ) { // Get the list of the files contained in the package File[] files = directory.listFiles( getFileFilter() ); if ( files != null ) { for ( int i = 0; i < files.length; i++ ) { // we are only interested in .class files if ( files[i].isDirectory() ) { if ( recursive ) { addAllFilesInDirectory( files[i], allClasses, packageName + files[i].getName() + ".", true ); } } else { Class result = load( packageName + files[i].getName() ); if ( result != null ) { allClasses.add( result ); } } } } } /** * @return FileFilter for searching class files (no inner classes, only thos with "Test" in the name) */ private FileFilter getFileFilter() { return new FileFilter() { /** * @see FileFilter */ public boolean accept( File pathname ) { return pathname.isDirectory() || ( pathname.getName().endsWith( ".class" ) && pathname.getName().indexOf( "Test" ) >= 0 && pathname.getName().indexOf( '$' ) < 0 ); } }; } /** * getter for field selectedClass * * @return current value of field selectedClass */ public Class getSelectedClass() { return this.selectedClass; } /** * store the value for field selectedClass */ private Class selectedClass; /** * setter for field selectedClass * * @param value new value */ public void setSelectedClass( final Class value ) { final Class oldValue = this.selectedClass; if ( oldValue != value ) { this.selectedClass = value; firePropertyChange( "selectedClass", oldValue, value ); } } /** * Code to create components and action listeners. * * @param classes what Classes to show in the list box */ private void setup( Vector classes ) { final JPanel mainPanel = new JPanel(); mainPanel.setLayout( new BorderLayout() ); getContentPane().setLayout( new BorderLayout() ); getContentPane().add( mainPanel, BorderLayout.CENTER ); mainPanel.setBorder( new EmptyBorder( 10, 10, 10, 10 ) ); mainPanel.add( new JLabel( "Choose a Demo to start: " ), BorderLayout.NORTH ); final JList list = new JList( classes ); mainPanel.add( new JScrollPane( list ), BorderLayout.CENTER ); list.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent e ) { setSelectedClass( (Class) list.getSelectedValue() ); } } ); final JPanel buttonPanel = new JPanel( new FlowLayout( FlowLayout.CENTER ) ); mainPanel.add( buttonPanel, BorderLayout.PAGE_END ); final JButton okButton = new JButton( "Ok" ); okButton.setMnemonic( 'O' ); buttonPanel.add( okButton ); getRootPane().setDefaultButton( okButton ); okButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { dispose(); } } ); final JButton cancelButton = new JButton( "Cancel" ); cancelButton.setMnemonic( 'C' ); buttonPanel.add( cancelButton ); cancelButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { setSelectedClass( null ); dispose(); } } ); pack(); center(); } /** * center the frame. */ private void center() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = this.getSize(); if ( frameSize.height > screenSize.height ) { frameSize.height = screenSize.height; } if ( frameSize.width > screenSize.width ) { frameSize.width = screenSize.width; } this.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); } /** * Start the chooser. * * @param args command line parameters */ public static void main( String[] args ) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch ( Exception e ) { //ok, keep the ugly one then :\ } try { TestChooser chooser = new TestChooser(); final Vector classes = new Vector(); System.out.println( "Composing Test list..." ); Sys.class.getName(); //to check loading lwjgl library //put some featured tests at the beginning classes.add( TestCloth.class ); classes.add( TestEnvMap.class ); classes.add( TestMultitexture.class ); classes.add( TestParticleSystem.class ); classes.add( TestDynamicSmoker.class ); classes.add( TestFireMilk.class ); classes.add( TestBoxColor.class ); classes.add( TestLightState.class ); classes.add( TestRenderQueue.class ); classes.add( TestScenegraph.class ); classes.add( TestBezierMesh.class ); classes.add( TestBezierCurve.class ); classes.add( TestPQTorus.class ); classes.add( TestAnisotropic.class ); classes.add( TestCollision.class ); classes.add( TestOBBTree.class ); classes.add( TestPick.class ); classes.add( TestOBBPick.class ); classes.add( TestImposterNode.class ); classes.add( TestRenderToTexture.class ); classes.add( TestCameraMan.class ); classes.add( TestFragmentProgramState.class ); classes.add( TestGLSLShaderObjectsState.class ); classes.add( TestVertexProgramState.class ); classes.add( TestAutoClodMesh.class ); classes.add( TestDiscreteLOD.class ); classes.add( TestASEJmeWrite.class ); classes.add( TestMaxJmeWrite.class ); classes.add( TestMd2JmeWrite.class ); classes.add( TestMilkJmeWrite.class ); classes.add( TestObjJmeWrite.class ); classes.add( TestSkybox.class ); classes.add( TestTerrain.class ); classes.add( TestTerrainLighting.class ); classes.add( TestTerrainPage.class ); chooser.find( "jmetest", true, classes ); chooser.setup( classes ); Class cls; do { chooser.setVisible(true); cls = chooser.getSelectedClass(); if ( cls != null ) { try { final Method method = cls.getMethod( "main", new Class[]{String[].class} ); method.invoke( null, new Object[]{args} ); } catch ( NoSuchMethodException e ) { //should not happen (filtered non-main classes already) e.printStackTrace(); } catch ( IllegalAccessException e ) { //whoops non-public / non-static main method ?! e.printStackTrace(); } catch ( InvocationTargetException e ) { //exception in main e.printStackTrace(); } } } while ( cls != null ); System.exit( 0 ); } catch ( UnsatisfiedLinkError e ) { e.printStackTrace(); JOptionPane.showMessageDialog( null, "A required native library could not be loaded.\n" + "Specifying -Djava.library.path=./lib when invoking jME applications " + "or copying native libraries to your Java bin directory might help.\n" + "Error message was: " + e.getMessage(), "Error loading library", JOptionPane.ERROR_MESSAGE ); System.exit(-1); } } }
MINOR: Added TestThirdPersonController to test lineup. git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@2588 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/jmetest/TestChooser.java
MINOR: Added TestThirdPersonController to test lineup.
<ide><path>rc/jmetest/TestChooser.java <ide> import jmetest.effects.TestDynamicSmoker; <ide> import jmetest.effects.TestParticleSystem; <ide> import jmetest.effects.cloth.TestCloth; <add>import jmetest.input.TestThirdPersonController; <ide> import jmetest.intersection.TestCollision; <ide> import jmetest.intersection.TestOBBPick; <ide> import jmetest.intersection.TestOBBTree; <ide> classes.add( TestParticleSystem.class ); <ide> classes.add( TestDynamicSmoker.class ); <ide> classes.add( TestFireMilk.class ); <add> classes.add( TestThirdPersonController.class ); <ide> classes.add( TestBoxColor.class ); <ide> classes.add( TestLightState.class ); <ide> classes.add( TestRenderQueue.class );
Java
apache-2.0
abf89399ccbe79d1705a22f14e2cd589cf10d212
0
Donnerbart/hazelcast,mesutcelik/hazelcast,tombujok/hazelcast,dbrimley/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,juanavelez/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,mesutcelik/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,tombujok/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,tkountis/hazelcast
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.internal.networking; import java.io.Closeable; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.ConcurrentMap; /** * Wraps a {@link java.nio.channels.SocketChannel}. * * The reason this class exists is because for enterprise encryption. Ideally the SocketChannel should have been decorated * with this encryption functionality, but unfortunately that isn't possible with this class. * * That is why a new 'wrapper' interface is introduced which acts like a SocketChannel and the implementations wrap a * SocketChannel. * * In the future we should get rid of this class and rely on {@link ChannelInboundHandler}/{@link ChannelOutboundHandler} * chaining to add encryption. This will remove more artifacts from the architecture that can't carry their weight. * * <h1>Future note</h1> * Below you can find some notes about the future of the Channel. This will hopefully act as a guide how to move forward. * * <h2>Fragmentation</h2> * Packets are currently not fragmented, meaning that they are send as 1 atomic unit and this can cause a 2 way communication * blackout for operations (since either operation or response can get blocked). Fragmentation needs to be added to make sure * the system doesn't suffer from head of line blocking. * * <h2>Ordering</h2> * In a channel messages don't need to be ordered. Currently they are, but as soon as we add packet fragmentation, packets * can get out of order. Under certain conditions you want to keep ordering, e.g. for events. In this case it should be possible * to have multiple streams in a channel. Within a stream there will be ordering. * * <h2>Reliability</h2> * A channel doesn't provide reliability. TCP/IP does provide reliability, but 1: who says we want to keep using TCP/IP, but * if a TCP/IP connection is lost and needs to be re-established, packets are lost. Reliability can be added, just like TCP/IP * adds it; we don't discard the data until it has been acknowledged. * * <h2>Flow and congestion control</h2> * On the Channel level we have no flow of congestion control; frames are always accepted no matter if on the sending side * the write-queue is overloaded, or on the receiving side the system is overloaded (e.g. many pending operations on the * operation queue). Just like with TCP/IP, flow and congestion control should be added. * * <h2>UDP</h2> * With ordering, reliability and flow and congestion control in place, we can ask ourselves the question if UDP is not a * more practical solution. */ public interface Channel extends Closeable { /** * Returns the attribute map. * * Attribute map can be used to store data into a socket. For example to find the Connection for a Channel, one can * store the Connection in this channel using some well known key. * * @return the attribute map. */ ConcurrentMap attributeMap(); /** * @see java.nio.channels.SocketChannel#socket() * * This method will be removed from the interface. Only an explicit cast to NioChannel will expose the Socket. */ Socket socket(); /** * @return the remote address. Returned value could be null. */ SocketAddress getRemoteSocketAddress(); /** * @return the local address. Returned value could be null */ SocketAddress getLocalSocketAddress(); /** * This method will be removed from the interface. Only an explicit cast to NioChannel will expose the SocketChannel. */ SocketChannel socketChannel(); /** * @see java.nio.channels.SocketChannel#read(ByteBuffer) */ int read(ByteBuffer dst) throws IOException; /** * @see java.nio.channels.SocketChannel#write(ByteBuffer) */ int write(ByteBuffer src) throws IOException; /** * @see java.nio.channels.SocketChannel#configureBlocking(boolean) */ SelectableChannel configureBlocking(boolean block) throws IOException; /** * @see java.nio.channels.SocketChannel#isOpen() */ boolean isOpen(); /** * Closes inbound. * * <p>Not thread safe. Should be called in channel reader thread.</p> * * @throws IOException */ void closeInbound() throws IOException; /** * Closes outbound. * * <p>Not thread safe. Should be called in channel writer thread.</p> * * @throws IOException */ void closeOutbound() throws IOException; /** * @see java.nio.channels.SocketChannel#close() */ void close() throws IOException; }
hazelcast/src/main/java/com/hazelcast/internal/networking/Channel.java
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.internal.networking; import java.io.Closeable; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.ConcurrentMap; /** * Wraps a {@link java.nio.channels.SocketChannel}. * * The reason this class exists is because for enterprise encryption. Ideally the SocketChannel should have been decorated * with this encryption functionality, but unfortunately that isn't possible with this class. * * That is why a new 'wrapper' interface is introduced which acts like a SocketChannel and the implementations wrap a * SocketChannel. * * In the future we should get rid of this class and rely on {@link ChannelInboundHandler}/{@link ChannelOutboundHandler} * chaining to add encryption. This will remove more artifacts from the architecture that can't carry their weight. */ public interface Channel extends Closeable { /** * Returns the attribute map. * * Attribute map can be used to store data into a socket. For example to find the Connection for a Channel, one can * store the Connection in this channel using some well known key. * * @return the attribute map. */ ConcurrentMap attributeMap(); /** * @see java.nio.channels.SocketChannel#socket() * * This method will be removed from the interface. Only an explicit cast to NioChannel will expose the Socket. */ Socket socket(); /** * @return the remote address. Returned value could be null. */ SocketAddress getRemoteSocketAddress(); /** * @return the local address. Returned value could be null */ SocketAddress getLocalSocketAddress(); /** * This method will be removed from the interface. Only an explicit cast to NioChannel will expose the SocketChannel. */ SocketChannel socketChannel(); /** * @see java.nio.channels.SocketChannel#read(ByteBuffer) */ int read(ByteBuffer dst) throws IOException; /** * @see java.nio.channels.SocketChannel#write(ByteBuffer) */ int write(ByteBuffer src) throws IOException; /** * @see java.nio.channels.SocketChannel#configureBlocking(boolean) */ SelectableChannel configureBlocking(boolean block) throws IOException; /** * @see java.nio.channels.SocketChannel#isOpen() */ boolean isOpen(); /** * Closes inbound. * * <p>Not thread safe. Should be called in channel reader thread.</p> * * @throws IOException */ void closeInbound() throws IOException; /** * Closes outbound. * * <p>Not thread safe. Should be called in channel writer thread.</p> * * @throws IOException */ void closeOutbound() throws IOException; /** * @see java.nio.channels.SocketChannel#close() */ void close() throws IOException; }
Added javadoc notes to Channel
hazelcast/src/main/java/com/hazelcast/internal/networking/Channel.java
Added javadoc notes to Channel
<ide><path>azelcast/src/main/java/com/hazelcast/internal/networking/Channel.java <ide> * <ide> * In the future we should get rid of this class and rely on {@link ChannelInboundHandler}/{@link ChannelOutboundHandler} <ide> * chaining to add encryption. This will remove more artifacts from the architecture that can't carry their weight. <add> * <add> * <h1>Future note</h1> <add> * Below you can find some notes about the future of the Channel. This will hopefully act as a guide how to move forward. <add> * <add> * <h2>Fragmentation</h2> <add> * Packets are currently not fragmented, meaning that they are send as 1 atomic unit and this can cause a 2 way communication <add> * blackout for operations (since either operation or response can get blocked). Fragmentation needs to be added to make sure <add> * the system doesn't suffer from head of line blocking. <add> * <add> * <h2>Ordering</h2> <add> * In a channel messages don't need to be ordered. Currently they are, but as soon as we add packet fragmentation, packets <add> * can get out of order. Under certain conditions you want to keep ordering, e.g. for events. In this case it should be possible <add> * to have multiple streams in a channel. Within a stream there will be ordering. <add> * <add> * <h2>Reliability</h2> <add> * A channel doesn't provide reliability. TCP/IP does provide reliability, but 1: who says we want to keep using TCP/IP, but <add> * if a TCP/IP connection is lost and needs to be re-established, packets are lost. Reliability can be added, just like TCP/IP <add> * adds it; we don't discard the data until it has been acknowledged. <add> * <add> * <h2>Flow and congestion control</h2> <add> * On the Channel level we have no flow of congestion control; frames are always accepted no matter if on the sending side <add> * the write-queue is overloaded, or on the receiving side the system is overloaded (e.g. many pending operations on the <add> * operation queue). Just like with TCP/IP, flow and congestion control should be added. <add> * <add> * <h2>UDP</h2> <add> * With ordering, reliability and flow and congestion control in place, we can ask ourselves the question if UDP is not a <add> * more practical solution. <ide> */ <ide> public interface Channel extends Closeable { <ide>
JavaScript
apache-2.0
ad54321d94aad7567ca99e6b2c17e019a2dc9aa3
0
rojr/SuperCMS,rojr/SuperCMS
var bridge = function (leafPath) { window.rhubarb.viewBridgeClasses.ViewBridge.apply(this, arguments); }; bridge.prototype = new window.rhubarb.viewBridgeClasses.ViewBridge(); bridge.prototype.constructor = bridge; bridge.prototype.attachEvents = function () { var firstTab = $('.nav-bar-tabs-first'); var self = this; $('#tab-add-button').click(function(){ var lastSelected = $('.product-list-tabs.active a').data('id'); self.raiseServerEvent('AddNewProduct', lastSelected); }); $('#' + this.leafPath + '_VariationName').keyup(function(){ firstTab.find('a').html($(this).val() + '<span class="delete-variation"><i class="fa fa-times fa-1x" aria-hidden="true"></i></span>'); }); }; bridge.prototype.onBeforeUpdateDomUpdateFromServer = function() { tinymce.remove('#' + this.leafPath + '_Description'); tinymce.remove('#' + this.leafPath + '_VariationDescription'); }; window.rhubarb.viewBridgeClasses.ProductsEditViewBridge = bridge;
src/Leaves/Admin/Products/ProductsEditViewBridge.js
var bridge = function (leafPath) { window.rhubarb.viewBridgeClasses.ViewBridge.apply(this, arguments); }; bridge.prototype = new window.rhubarb.viewBridgeClasses.ViewBridge(); bridge.prototype.constructor = bridge; bridge.prototype.attachEvents = function () { var firstTab = $('.nav-bar-tabs-first'); var self = this; $('.product-variation-tab').click(function(event) { $(this).closest('.form-body').addClass('ajax-progress'); if (!event.target.classList.contains('fa')) { var lastSelected = $('.product-list-tabs.active a').data('id'); changeTab($(this).parent()); self.raiseServerEvent('ChangeProductVariation', lastSelected, $(this).data('id')); event.preventDefault(); return false; } else { if (confirm('Are you sure you want to remove this variation?')) { self.raiseServerEvent('VariationDelete', $(this).data('id')); } event.preventDefault(); event.stopPropagation(); return false; } }); $('#tab-add-button').click(function(){ var lastSelected = $('.product-list-tabs.active a').data('id'); self.raiseServerEvent('AddNewProduct', lastSelected); }); function changeTab(tab) { $('#' + this.leaftPath + ' .active').removeClass('active'); tab.addClass('active'); } $('#' + this.leafPath + '_VariationName').keyup(function(){ firstTab.find('a').html($(this).val() + '<span class="delete-variation"><i class="fa fa-times fa-1x" aria-hidden="true"></i></span>'); }); }; bridge.prototype.onBeforeUpdateDomUpdateFromServer = function() { tinymce.remove('#' + this.leafPath + '_Description'); tinymce.remove('#' + this.leafPath + '_VariationDescription'); }; window.rhubarb.viewBridgeClasses.ProductsEditViewBridge = bridge;
Detaching javascript events from event edit viewbridge
src/Leaves/Admin/Products/ProductsEditViewBridge.js
Detaching javascript events from event edit viewbridge
<ide><path>rc/Leaves/Admin/Products/ProductsEditViewBridge.js <ide> var firstTab = $('.nav-bar-tabs-first'); <ide> var self = this; <ide> <del> $('.product-variation-tab').click(function(event) { <del> $(this).closest('.form-body').addClass('ajax-progress'); <del> if (!event.target.classList.contains('fa')) { <del> var lastSelected = $('.product-list-tabs.active a').data('id'); <del> changeTab($(this).parent()); <del> <del> self.raiseServerEvent('ChangeProductVariation', lastSelected, $(this).data('id')); <del> event.preventDefault(); <del> return false; <del> } else { <del> if (confirm('Are you sure you want to remove this variation?')) { <del> self.raiseServerEvent('VariationDelete', $(this).data('id')); <del> } <del> event.preventDefault(); <del> event.stopPropagation(); <del> return false; <del> } <del> <del> }); <del> <ide> $('#tab-add-button').click(function(){ <ide> var lastSelected = $('.product-list-tabs.active a').data('id'); <ide> <ide> self.raiseServerEvent('AddNewProduct', lastSelected); <ide> }); <del> <del> function changeTab(tab) { <del> $('#' + this.leaftPath + ' .active').removeClass('active'); <del> <del> tab.addClass('active'); <del> } <ide> <ide> $('#' + this.leafPath + '_VariationName').keyup(function(){ <ide> firstTab.find('a').html($(this).val() + '<span class="delete-variation"><i class="fa fa-times fa-1x" aria-hidden="true"></i></span>');
Java
isc
c498d9a5cee30705ad8761586cce9790214d2b42
0
TealCube/facecore
/** * The MIT License * Copyright (c) 2015 Teal Cube Games * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.facecore.ui; import com.tealcube.minecraft.bukkit.facecore.utilities.TextUtils; import com.tealcube.minecraft.bukkit.mirror.ClassType; import com.tealcube.minecraft.bukkit.mirror.Mirror; import org.bukkit.entity.Player; import java.lang.reflect.Method; public class ActionBarMessage { private final String message; private final Class<?> chatSerializer; private final Class<?> chatBaseComponent; private final Class<?> playOutChatPacket; public ActionBarMessage(String message) { this.message = message; this.chatSerializer = Mirror.getClass("IChatBaseComponent.ChatSerializer", ClassType.NMS); this.chatBaseComponent = Mirror.getClass("IChatBaseComponent", ClassType.NMS); this.playOutChatPacket = Mirror.getClass("PacketPlayOutChat", ClassType.NMS); } public void send(Iterable<Player> players) { for (Player player : players) { send(player); } } public void send(Player player) { try { Class<?> packetClass = Mirror.getClass("Packet", ClassType.NMS); Object handle = Mirror.getMethod(player.getClass(), "getHandle").invoke(player); Object connection = Mirror.getField(handle.getClass(), "playerConnection").get(handle); Method sendPacket = Mirror.getMethod(connection.getClass(), "sendPacket", packetClass); Object serialized = Mirror.getMethod(chatSerializer, "a", String.class).invoke(null, "{\"text\":\"" + TextUtils.color(message) + "\"}"); Object packet = playOutChatPacket.getConstructor(chatBaseComponent, Byte.TYPE).newInstance(serialized, (byte) 2); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); } } }
src/main/java/com/tealcube/minecraft/bukkit/facecore/ui/ActionBarMessage.java
/** * The MIT License * Copyright (c) 2015 Teal Cube Games * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.facecore.ui; import com.tealcube.minecraft.bukkit.facecore.utilities.TextUtils; import com.tealcube.minecraft.bukkit.mirror.ClassType; import com.tealcube.minecraft.bukkit.mirror.Mirror; import org.bukkit.entity.Player; import java.lang.reflect.Method; public class ActionBarMessage { private final String message; private final Class<?> chatSerializer; private final Class<?> chatBaseComponent; private final Class<?> playOutChatPacket; public ActionBarMessage(String message) { this.message = message; this.chatSerializer = Mirror.getClass("ChatSerializer", ClassType.NMS); this.chatBaseComponent = Mirror.getClass("IChatBaseComponent", ClassType.NMS); this.playOutChatPacket = Mirror.getClass("PacketPlayOutChat", ClassType.NMS); } public void send(Iterable<Player> players) { for (Player player : players) { send(player); } } public void send(Player player) { try { Class<?> packetClass = Mirror.getClass("Packet", ClassType.NMS); Object handle = Mirror.getMethod(player.getClass(), "getHandle").invoke(player); Object connection = Mirror.getField(handle.getClass(), "playerConnection").get(handle); Method sendPacket = Mirror.getMethod(connection.getClass(), "sendPacket", packetClass); Object serialized = Mirror.getMethod(chatSerializer, "a", String.class).invoke(null, "{\"text\":\"" + TextUtils.color(message) + "\"}"); Object packet = playOutChatPacket.getConstructor(chatBaseComponent, Byte.TYPE).newInstance(serialized, (byte) 2); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); } } }
fixing class location in ActionBarMessage
src/main/java/com/tealcube/minecraft/bukkit/facecore/ui/ActionBarMessage.java
fixing class location in ActionBarMessage
<ide><path>rc/main/java/com/tealcube/minecraft/bukkit/facecore/ui/ActionBarMessage.java <ide> <ide> public ActionBarMessage(String message) { <ide> this.message = message; <del> this.chatSerializer = Mirror.getClass("ChatSerializer", ClassType.NMS); <add> this.chatSerializer = Mirror.getClass("IChatBaseComponent.ChatSerializer", ClassType.NMS); <ide> this.chatBaseComponent = Mirror.getClass("IChatBaseComponent", ClassType.NMS); <ide> this.playOutChatPacket = Mirror.getClass("PacketPlayOutChat", ClassType.NMS); <ide> }
Java
apache-2.0
2bf7f20127a2d01ed9cecf300e74fed3247b0d17
0
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* Copyright 2017 Integration Partners B.V. 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.nn.adapterframework.jdbc.migration; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.configuration.IbisContext; import nl.nn.adapterframework.jdbc.JdbcException; import nl.nn.adapterframework.jdbc.JdbcFacade; import nl.nn.adapterframework.util.AppConstants; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.exception.ValidationFailedException; /** * LiquiBase implementation for IAF * * @author Niels Meijer * @since 7.0-B4 * */ public class Migrator extends JdbcFacade { private IbisContext ibisContext; private LiquibaseImpl instance; public Migrator() { } public void configure() throws ConfigurationException { configure(null, null, null); } public void configure(String configurationName) throws ConfigurationException { configure(configurationName, null, null); } public void configure(String configurationName, ClassLoader classLoader) throws ConfigurationException { configure(configurationName, classLoader, null); } public synchronized void configure(String configurationName, ClassLoader classLoader, String changeLogFile) throws ConfigurationException { AppConstants appConstants = AppConstants.getInstance(classLoader); if(changeLogFile == null) changeLogFile = appConstants.getString("liquibase.changeLogFile", "DatabaseChangelog.xml"); LiquibaseClassLoader cl = new LiquibaseClassLoader(classLoader); if(cl.getResource(changeLogFile) == null) { String msg = "unable to find database changelog file ["+changeLogFile+"]"; if(configurationName != null) msg += " configuration ["+configurationName+"]"; log.debug(msg); } else { String dataSource = appConstants.getString("jdbc.migrator.dataSource", "jdbc/" + appConstants.getResolvedProperty("instance.name.lc")); setDatasourceName(dataSource); try { JdbcConnection connection = new JdbcConnection(getConnection()); instance = new LiquibaseImpl(ibisContext, cl, connection, configurationName, changeLogFile); } catch (JdbcException e) { throw new ConfigurationException("migrator error connecting to database ["+dataSource+"]", e); } catch (ValidationFailedException e) { throw new ConfigurationException("liquibase validation failed", e); } catch (LiquibaseException e) { throw new ConfigurationException("liquibase failed to initialize", e); } } } public void setIbisContext(IbisContext ibisContext) { this.ibisContext = ibisContext; } public void update() { if(this.instance != null) instance.update(); } }
core/src/main/java/nl/nn/adapterframework/jdbc/migration/Migrator.java
/* Copyright 2017 Integration Partners B.V. 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.nn.adapterframework.jdbc.migration; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.configuration.IbisContext; import nl.nn.adapterframework.jdbc.JdbcException; import nl.nn.adapterframework.jdbc.JdbcFacade; import nl.nn.adapterframework.util.AppConstants; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.exception.ValidationFailedException; /** * LiquiBase implementation for IAF * * @author Niels Meijer * @since 7.0-B4 * */ public class Migrator extends JdbcFacade { private IbisContext ibisContext; private LiquibaseImpl instance; public Migrator() { } public void configure(String configurationName) throws ConfigurationException { configure(configurationName, null, null); } public void configure(String configurationName, ClassLoader classLoader) throws ConfigurationException { configure(configurationName, classLoader, null); } public synchronized void configure(String configurationName, ClassLoader classLoader, String changeLogFile) throws ConfigurationException { if(configurationName == null) throw new ConfigurationException("configurationName cannot be null"); AppConstants appConstants = AppConstants.getInstance(classLoader); if(changeLogFile == null) changeLogFile = appConstants.getString("liquibase.changeLogFile", "DatabaseChangelog.xml"); LiquibaseClassLoader cl = new LiquibaseClassLoader(classLoader); if(cl.getResource(changeLogFile) == null) { log.debug("unable to find database changelog file ["+changeLogFile+"] configuration ["+configurationName+"]"); } else { String dataSource = appConstants.getString("jdbc.migrator.dataSource", "jdbc/" + appConstants.getResolvedProperty("instance.name.lc")); setDatasourceName(dataSource); try { JdbcConnection connection = new JdbcConnection(getConnection()); instance = new LiquibaseImpl(ibisContext, cl, connection, configurationName, changeLogFile); } catch (JdbcException e) { throw new ConfigurationException("migrator error connecting to database ["+dataSource+"]", e); } catch (ValidationFailedException e) { throw new ConfigurationException("liquibase validation failed", e); } catch (LiquibaseException e) { throw new ConfigurationException("liquibase failed to initialize", e); } } } public void setIbisContext(IbisContext ibisContext) { this.ibisContext = ibisContext; } public void update() { if(this.instance != null) instance.update(); } }
Add option to configure jdbcMigrators without configurationName
core/src/main/java/nl/nn/adapterframework/jdbc/migration/Migrator.java
Add option to configure jdbcMigrators without configurationName
<ide><path>ore/src/main/java/nl/nn/adapterframework/jdbc/migration/Migrator.java <ide> public Migrator() { <ide> } <ide> <add> public void configure() throws ConfigurationException { <add> configure(null, null, null); <add> } <add> <ide> public void configure(String configurationName) throws ConfigurationException { <ide> configure(configurationName, null, null); <ide> } <ide> } <ide> <ide> public synchronized void configure(String configurationName, ClassLoader classLoader, String changeLogFile) throws ConfigurationException { <del> if(configurationName == null) <del> throw new ConfigurationException("configurationName cannot be null"); <ide> <ide> AppConstants appConstants = AppConstants.getInstance(classLoader); <ide> <ide> <ide> LiquibaseClassLoader cl = new LiquibaseClassLoader(classLoader); <ide> if(cl.getResource(changeLogFile) == null) { <del> log.debug("unable to find database changelog file ["+changeLogFile+"] configuration ["+configurationName+"]"); <add> String msg = "unable to find database changelog file ["+changeLogFile+"]"; <add> if(configurationName != null) <add> msg += " configuration ["+configurationName+"]"; <add> <add> log.debug(msg); <ide> } <ide> else { <ide> String dataSource = appConstants.getString("jdbc.migrator.dataSource", "jdbc/" + appConstants.getResolvedProperty("instance.name.lc"));
Java
apache-2.0
e866faf76106640edeb5d340cca91b4fdc50cd4f
0
PSCGroup/mongo-java-driver,gianpaj/mongo-java-driver,jyemin/mongo-java-driver,kay-kim/mongo-java-driver,wanggc/mongo-java-driver,davydotcom/mongo-java-driver,rozza/mongo-java-driver,jsonking/mongo-java-driver,jsonking/mongo-java-driver,jyemin/mongo-java-driver,wanggc/mongo-java-driver,rozza/mongo-java-driver,davydotcom/mongo-java-driver
/** * Copyright 2008 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bson.util.concurrent; import static org.bson.util.concurrent.Assertions.notNull; import static java.util.Collections.unmodifiableCollection; import static java.util.Collections.unmodifiableSet; import org.bson.util.concurrent.annotations.GuardedBy; import org.bson.util.concurrent.annotations.ThreadSafe; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Abstract base class for COW {@link Map} implementations that delegate to an * internal map. * * @param <K> The key type * @param <V> The value type * @param <M> the internal {@link Map} or extension for things like sorted and * navigable maps. */ @ThreadSafe public abstract class AbstractCopyOnWriteMap<K, V, M extends Map<K, V>> implements ConcurrentMap<K, V>, Serializable { private static final long serialVersionUID = 4508989182041753878L; @GuardedBy("lock") private volatile M delegate; // import edu.umd.cs.findbugs.annotations.@SuppressWarnings private final transient Lock lock = new ReentrantLock(); // private final transient EntrySet entrySet = new EntrySet(); // private final transient KeySet keySet = new KeySet(); // private final transient Values values = new Values(); // private final View.Type viewType; private final View<K, V> view; /** * Create a new {@link CopyOnWriteMap} with the supplied {@link Map} to * initialize the values. * * @param map the initial map to initialize with * @param viewType for writable or read-only key, value and entrySet views */ protected <N extends Map<? extends K, ? extends V>> AbstractCopyOnWriteMap(final N map, final View.Type viewType) { this.delegate = notNull("delegate", copy(notNull("map", map))); this.view = notNull("viewType", viewType).get(this); } /** * Copy function, implemented by sub-classes. * * @param <N> the map to copy and return. * @param map the initial values of the newly created map. * @return a new map. Will never be modified after construction. */ @GuardedBy("lock") abstract <N extends Map<? extends K, ? extends V>> M copy(N map); // // mutable operations // public final void clear() { lock.lock(); try { set(copy(Collections.<K, V> emptyMap())); } finally { lock.unlock(); } } public final V remove(final Object key) { lock.lock(); try { // short circuit if key doesn't exist if (!delegate.containsKey(key)) { return null; } final M map = copy(); try { return map.remove(key); } finally { set(map); } } finally { lock.unlock(); } } public boolean remove(final Object key, final Object value) { lock.lock(); try { if (delegate.containsKey(key) && equals(value, delegate.get(key))) { final M map = copy(); map.remove(key); set(map); return true; } else { return false; } } finally { lock.unlock(); } } public boolean replace(final K key, final V oldValue, final V newValue) { lock.lock(); try { if (!delegate.containsKey(key) || !equals(oldValue, delegate.get(key))) { return false; } final M map = copy(); map.put(key, newValue); set(map); return true; } finally { lock.unlock(); } } public V replace(final K key, final V value) { lock.lock(); try { if (!delegate.containsKey(key)) { return null; } final M map = copy(); try { return map.put(key, value); } finally { set(map); } } finally { lock.unlock(); } } public final V put(final K key, final V value) { lock.lock(); try { final M map = copy(); try { return map.put(key, value); } finally { set(map); } } finally { lock.unlock(); } } public V putIfAbsent(final K key, final V value) { lock.lock(); try { if (!delegate.containsKey(key)) { final M map = copy(); try { return map.put(key, value); } finally { set(map); } } return delegate.get(key); } finally { lock.unlock(); } } public final void putAll(final Map<? extends K, ? extends V> t) { lock.lock(); try { final M map = copy(); map.putAll(t); set(map); } finally { lock.unlock(); } } protected M copy() { lock.lock(); try { return copy(delegate); } finally { lock.unlock(); } } @GuardedBy("lock") protected void set(final M map) { delegate = map; } // // Collection views // public final Set<Map.Entry<K, V>> entrySet() { return view.entrySet(); } public final Set<K> keySet() { return view.keySet(); } public final Collection<V> values() { return view.values(); } // // delegate operations // public final boolean containsKey(final Object key) { return delegate.containsKey(key); } public final boolean containsValue(final Object value) { return delegate.containsValue(value); } public final V get(final Object key) { return delegate.get(key); } public final boolean isEmpty() { return delegate.isEmpty(); } public final int size() { return delegate.size(); } @Override public final boolean equals(final Object o) { return delegate.equals(o); } @Override public final int hashCode() { return delegate.hashCode(); } protected final M getDelegate() { return delegate; } @Override public String toString() { return delegate.toString(); } // // inner classes // private class KeySet extends CollectionView<K> implements Set<K> { @Override Collection<K> getDelegate() { return delegate.keySet(); } // // mutable operations // public void clear() { lock.lock(); try { final M map = copy(); map.keySet().clear(); set(map); } finally { lock.unlock(); } } public boolean remove(final Object o) { return AbstractCopyOnWriteMap.this.remove(o) != null; } public boolean removeAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.keySet().removeAll(c); } finally { set(map); } } finally { lock.unlock(); } } public boolean retainAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.keySet().retainAll(c); } finally { set(map); } } finally { lock.unlock(); } } } private final class Values extends CollectionView<V> { @Override Collection<V> getDelegate() { return delegate.values(); } public void clear() { lock.lock(); try { final M map = copy(); map.values().clear(); set(map); } finally { lock.unlock(); } } public boolean remove(final Object o) { lock.lock(); try { if (!contains(o)) { return false; } final M map = copy(); try { return map.values().remove(o); } finally { set(map); } } finally { lock.unlock(); } } public boolean removeAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.values().removeAll(c); } finally { set(map); } } finally { lock.unlock(); } } public boolean retainAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.values().retainAll(c); } finally { set(map); } } finally { lock.unlock(); } } } private class EntrySet extends CollectionView<Entry<K, V>> implements Set<Map.Entry<K, V>> { @Override Collection<java.util.Map.Entry<K, V>> getDelegate() { return delegate.entrySet(); } public void clear() { lock.lock(); try { final M map = copy(); map.entrySet().clear(); set(map); } finally { lock.unlock(); } } public boolean remove(final Object o) { lock.lock(); try { if (!contains(o)) { return false; } final M map = copy(); try { return map.entrySet().remove(o); } finally { set(map); } } finally { lock.unlock(); } } public boolean removeAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.entrySet().removeAll(c); } finally { set(map); } } finally { lock.unlock(); } } public boolean retainAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.entrySet().retainAll(c); } finally { set(map); } } finally { lock.unlock(); } } } private static class UnmodifiableIterator<T> implements Iterator<T> { private final Iterator<T> delegate; public UnmodifiableIterator(final Iterator<T> delegate) { this.delegate = delegate; } public boolean hasNext() { return delegate.hasNext(); } public T next() { return delegate.next(); } public void remove() { throw new UnsupportedOperationException(); } } protected static abstract class CollectionView<E> implements Collection<E> { abstract Collection<E> getDelegate(); // // delegate operations // public final boolean contains(final Object o) { return getDelegate().contains(o); } public final boolean containsAll(final Collection<?> c) { return getDelegate().containsAll(c); } public final Iterator<E> iterator() { return new UnmodifiableIterator<E>(getDelegate().iterator()); } public final boolean isEmpty() { return getDelegate().isEmpty(); } public final int size() { return getDelegate().size(); } public final Object[] toArray() { return getDelegate().toArray(); } public final <T> T[] toArray(final T[] a) { return getDelegate().toArray(a); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public boolean equals(final Object obj) { return getDelegate().equals(obj); } @Override public String toString() { return getDelegate().toString(); } // // unsupported operations // public final boolean add(final E o) { throw new UnsupportedOperationException(); } public final boolean addAll(final Collection<? extends E> c) { throw new UnsupportedOperationException(); } } private boolean equals(final Object o1, final Object o2) { if (o1 == null) { return o2 == null; } return o1.equals(o2); } /** * Provides access to the views of the underlying key, value and entry * collections. */ public static abstract class View<K, V> { View() {} abstract Set<K> keySet(); abstract Set<Entry<K, V>> entrySet(); abstract Collection<V> values(); /** * The different types of {@link View} available */ public enum Type { STABLE { @Override <K, V, M extends Map<K, V>> View<K, V> get(final AbstractCopyOnWriteMap<K, V, M> host) { return host.new Immutable(); } }, LIVE { @Override <K, V, M extends Map<K, V>> View<K, V> get(final AbstractCopyOnWriteMap<K, V, M> host) { return host.new Mutable(); } }; abstract <K, V, M extends Map<K, V>> View<K, V> get(AbstractCopyOnWriteMap<K, V, M> host); } } final class Immutable extends View<K, V> implements Serializable { private static final long serialVersionUID = -4158727180429303818L; @Override public Set<K> keySet() { return unmodifiableSet(delegate.keySet()); } @Override public Set<Entry<K, V>> entrySet() { return unmodifiableSet(delegate.entrySet()); } @Override public Collection<V> values() { return unmodifiableCollection(delegate.values()); } } final class Mutable extends View<K, V> implements Serializable { private static final long serialVersionUID = 1624520291194797634L; private final transient KeySet keySet = new KeySet(); private final transient EntrySet entrySet = new EntrySet(); private final transient Values values = new Values(); @Override public Set<K> keySet() { return keySet; } @Override public Set<Entry<K, V>> entrySet() { return entrySet; } @Override public Collection<V> values() { return values; } } }
src/main/org/bson/util/concurrent/AbstractCopyOnWriteMap.java
/** * Copyright 2008 mongodb Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bson.util.concurrent; import static org.bson.util.concurrent.Assertions.notNull; import static java.util.Collections.unmodifiableCollection; import static java.util.Collections.unmodifiableSet; import org.bson.util.concurrent.annotations.GuardedBy; import org.bson.util.concurrent.annotations.ThreadSafe; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Abstract base class for COW {@link Map} implementations that delegate to an * internal map. * * @param <K> The key type * @param <V> The value type * @param <M> the internal {@link Map} or extension for things like sorted and * navigable maps. */ @ThreadSafe public abstract class AbstractCopyOnWriteMap<K, V, M extends Map<K, V>> implements ConcurrentMap<K, V>, Serializable { private static final long serialVersionUID = 4508989182041753878L; @GuardedBy("lock") private volatile M delegate; // import edu.umd.cs.findbugs.annotations.@SuppressWarnings private final transient Lock lock = new ReentrantLock(); // private final transient EntrySet entrySet = new EntrySet(); // private final transient KeySet keySet = new KeySet(); // private final transient Values values = new Values(); // private final View.Type viewType; private final View<K, V> view; /** * Create a new {@link CopyOnWriteMap} with the supplied {@link Map} to * initialize the values. * * @param map the initial map to initialize with * @param viewType for writable or read-only key, value and entrySet views */ protected <N extends Map<? extends K, ? extends V>> AbstractCopyOnWriteMap(final N map, final View.Type viewType) { this.delegate = notNull("delegate", copy(notNull("map", map))); this.view = notNull("viewType", viewType).get(this); } /** * Copy function, implemented by sub-classes. * * @param <N> the map to copy and return. * @param map the initial values of the newly created map. * @return a new map. Will never be modified after construction. */ @GuardedBy("lock") abstract <N extends Map<? extends K, ? extends V>> M copy(N map); // // mutable operations // public final void clear() { lock.lock(); try { set(copy(Collections.<K, V> emptyMap())); } finally { lock.unlock(); } } public final V remove(final Object key) { lock.lock(); try { // short circuit if key doesn't exist if (!delegate.containsKey(key)) { return null; } final M map = copy(); try { return map.remove(key); } finally { set(map); } } finally { lock.unlock(); } } public boolean remove(final Object key, final Object value) { lock.lock(); try { if (delegate.containsKey(key) && equals(value, delegate.get(key))) { final M map = copy(); map.remove(key); set(map); return true; } else { return false; } } finally { lock.unlock(); } } public boolean replace(final K key, final V oldValue, final V newValue) { lock.lock(); try { if (!delegate.containsKey(key) || !equals(oldValue, delegate.get(key))) { return false; } final M map = copy(); map.put(key, newValue); set(map); return true; } finally { lock.unlock(); } } public V replace(final K key, final V value) { lock.lock(); try { if (!delegate.containsKey(key)) { return null; } final M map = copy(); try { return map.put(key, value); } finally { set(map); } } finally { lock.unlock(); } } public final V put(final K key, final V value) { lock.lock(); try { final M map = copy(); try { return map.put(key, value); } finally { set(map); } } finally { lock.unlock(); } } public V putIfAbsent(final K key, final V value) { lock.lock(); try { if (!delegate.containsKey(key)) { final M map = copy(); try { return map.put(key, value); } finally { set(map); } } return delegate.get(key); } finally { lock.unlock(); } } public final void putAll(final Map<? extends K, ? extends V> t) { lock.lock(); try { final M map = copy(); map.putAll(t); set(map); } finally { lock.unlock(); } } protected M copy() { lock.lock(); try { return copy(delegate); } finally { lock.unlock(); } } @GuardedBy("lock") protected void set(final M map) { delegate = map; } // // Collection views // public final Set<Map.Entry<K, V>> entrySet() { return view.entrySet(); } public final Set<K> keySet() { return view.keySet(); } public final Collection<V> values() { return view.values(); } // // delegate operations // public final boolean containsKey(final Object key) { return delegate.containsKey(key); } public final boolean containsValue(final Object value) { return delegate.containsValue(value); } public final V get(final Object key) { return delegate.get(key); } public final boolean isEmpty() { return delegate.isEmpty(); } public final int size() { return delegate.size(); } @Override public final boolean equals(final Object o) { return delegate.equals(o); } @Override public final int hashCode() { return delegate.hashCode(); } protected final M getDelegate() { return delegate; } @Override public String toString() { return delegate.toString(); } // // inner classes // private class KeySet extends CollectionView<K> implements Set<K> { @Override Collection<K> getDelegate() { return delegate.keySet(); } // // mutable operations // public void clear() { lock.lock(); try { final M map = copy(); map.keySet().clear(); set(map); } finally { lock.unlock(); } } public boolean remove(final Object o) { return AbstractCopyOnWriteMap.this.remove(o) != null; } public boolean removeAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.keySet().removeAll(c); } finally { set(map); } } finally { lock.unlock(); } } public boolean retainAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.keySet().retainAll(c); } finally { set(map); } } finally { lock.unlock(); } } } private final class Values extends CollectionView<V> { @Override Collection<V> getDelegate() { return delegate.values(); } public void clear() { lock.lock(); try { final M map = copy(); map.values().clear(); set(map); } finally { lock.unlock(); } } public boolean remove(final Object o) { lock.lock(); try { if (!contains(o)) { return false; } final M map = copy(); try { return map.values().remove(o); } finally { set(map); } } finally { lock.unlock(); } } public boolean removeAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.values().removeAll(c); } finally { set(map); } } finally { lock.unlock(); } } public boolean retainAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.values().retainAll(c); } finally { set(map); } } finally { lock.unlock(); } } } private class EntrySet extends CollectionView<Entry<K, V>> implements Set<Map.Entry<K, V>> { @Override Collection<java.util.Map.Entry<K, V>> getDelegate() { return delegate.entrySet(); } public void clear() { lock.lock(); try { final M map = copy(); map.entrySet().clear(); set(map); } finally { lock.unlock(); } } public boolean remove(final Object o) { lock.lock(); try { if (!contains(o)) { return false; } final M map = copy(); try { return map.entrySet().remove(o); } finally { set(map); } } finally { lock.unlock(); } } public boolean removeAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.entrySet().removeAll(c); } finally { set(map); } } finally { lock.unlock(); } } public boolean retainAll(final Collection<?> c) { lock.lock(); try { final M map = copy(); try { return map.entrySet().retainAll(c); } finally { set(map); } } finally { lock.unlock(); } } } private static class UnmodifiableIterator<T> implements Iterator<T> { private final Iterator<T> delegate; public UnmodifiableIterator(final Iterator<T> delegate) { this.delegate = delegate; } public boolean hasNext() { return delegate.hasNext(); } public T next() { return delegate.next(); } public void remove() { throw new UnsupportedOperationException(); } } protected static abstract class CollectionView<E> implements Collection<E> { abstract Collection<E> getDelegate(); // // delegate operations // public final boolean contains(final Object o) { return getDelegate().contains(o); } public final boolean containsAll(final Collection<?> c) { return getDelegate().containsAll(c); } public final Iterator<E> iterator() { return new UnmodifiableIterator<E>(getDelegate().iterator()); } public final boolean isEmpty() { return getDelegate().isEmpty(); } public final int size() { return getDelegate().size(); } public final Object[] toArray() { return getDelegate().toArray(); } public final <T> T[] toArray(final T[] a) { return getDelegate().toArray(a); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public boolean equals(final Object obj) { return getDelegate().equals(obj); } @Override public String toString() { return getDelegate().toString(); } // // unsupported operations // public final boolean add(final E o) { throw new UnsupportedOperationException(); } public final boolean addAll(final Collection<? extends E> c) { throw new UnsupportedOperationException(); } } private boolean equals(final Object o1, final Object o2) { if (o1 == null) { return o2 == null; } return o1.equals(o2); } /** * Provides access to the views of the underlying key, value and entry * collections. */ public static abstract class View<K, V> { View() {} abstract Set<K> keySet(); abstract Set<Entry<K, V>> entrySet(); abstract Collection<V> values(); /** * The different types of {@link View} available */ public enum Type { STABLE { @Override <K, V, M extends Map<K, V>> View<K, V> get(final AbstractCopyOnWriteMap<K, V, M> host) { return host.new Immutable(); } }, LIVE { @Override <K, V, M extends Map<K, V>> View<K, V> get(final AbstractCopyOnWriteMap<K, V, M> host) { return host.new Mutable(); } }; abstract <K, V, M extends Map<K, V>> View<K, V> get(AbstractCopyOnWriteMap<K, V, M> host); } } final class Immutable extends View<K, V> implements Serializable { private static final long serialVersionUID = -4158727180429303818L; @Override public Set<K> keySet() { return unmodifiableSet(delegate.keySet()); } @Override public Set<Entry<K, V>> entrySet() { return unmodifiableSet(delegate.entrySet()); } @Override public Collection<V> values() { return unmodifiableCollection(delegate.values()); } } final class Mutable extends View<K, V> implements Serializable { private static final long serialVersionUID = 1624520291194797634L; private final transient KeySet keySet = new KeySet(); private final transient EntrySet entrySet = new EntrySet(); private final transient Values values = new Values(); @Override public Set<K> keySet() { return keySet; } @Override public Set<Entry<K, V>> entrySet() { return entrySet; } @Override public Collection<V> values() { return values; } } }
Fix accidental conversion of copyright from Atlassian -> mongodb in a package search
src/main/org/bson/util/concurrent/AbstractCopyOnWriteMap.java
Fix accidental conversion of copyright from Atlassian -> mongodb in a package search
<ide><path>rc/main/org/bson/util/concurrent/AbstractCopyOnWriteMap.java <ide> /** <del> * Copyright 2008 mongodb Pty Ltd <add> * Copyright 2008 Atlassian Pty Ltd <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License.
Java
apache-2.0
6b218edc12473740722fc69a32a22fb0c0fcf78c
0
SlideKB/SlideBar
/** Copyright 2017 John Kester (Jack Kester) 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.slidekb.back; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.jnativehook.GlobalScreen; import org.jnativehook.NativeHookException; import com.github.slidekb.api.AlphaKeyManager; import com.github.slidekb.api.HotKeyManager; import com.github.slidekb.api.SlideBarPlugin; import com.github.slidekb.back.settings.GlobalSettings; import com.github.slidekb.back.settings.PluginSettings; import com.github.slidekb.ifc.resources.RootResource; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.jaxrs.listing.ApiListingResource; import io.swagger.jaxrs.listing.SwaggerSerializers; public class MainBack implements Runnable { // TODO decide if this and relating operations on it should be moved to a // different class. /** * The previous 20 unique executables that have been visited. TODO move this * to a different class that makes more sense. */ public static ArrayList<String> prev20List = new ArrayList<String>(); public static PluginManager PM = new PluginManager(); // TODO rename to a more meaningful name private static KeyHook x; /** * boolean that expresses whether the backend has been started or not / is * currently running. */ private static boolean started = false; static AlphaKeyManager alphaKeyManager = new AlphaKeyManagerImpl(); static HotKeyManager hotKeyManager = new HotKeyManagerImpl(); static PortManager portMan = new PortManager(); private static SliderManagerImpl slideMan = new SliderManagerImpl(); private static GlobalSettings settings; /** * For running without an Interface. creates a new thread and starts it * * @param args */ public static void main(String[] args) { Thread t = new Thread(new MainBack()); t.start(); } @Override public void run() { FirstLoad(); } /** * runs when MainBack and MainFront are first loaded. (I think, TODO double * check that) */ public static void FirstLoad() { setupKeyHook(); startIt(); startRestServer(); while (started) { try { Run(); Thread.sleep(10); } catch (Throwable e) { e.printStackTrace(); } } } public static HttpServer startRestServer() { BeanConfig beanConfig = new BeanConfig(); beanConfig.setVersion("1.0.0"); beanConfig.setTitle("SlideBar REST Interface"); beanConfig.setResourcePackage(RootResource.class.getPackage().getName()); beanConfig.setSchemes(new String[] { "http" }); beanConfig.setHost("localhost:5055"); beanConfig.setScan(true); final ResourceConfig rc = new ResourceConfig(); rc.packages(RootResource.class.getPackage().getName()); rc.register(LoggingFeature.class); rc.register(JacksonFeature.class); rc.register(ApiListingResource.class); rc.register(SwaggerSerializers.class); rc.property(ServerProperties.WADL_FEATURE_DISABLE, true); Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler"); l.setLevel(Level.FINE); l.setUseParentHandlers(false); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(Level.ALL); l.addHandler(ch); try { return GrizzlyHttpServerFactory.createHttpServer(new URI("http://localhost:5055"), rc); } catch (URISyntaxException e) { e.printStackTrace(); return null; } } // TODO move this to a class that makes more sense /** * vibrates each connected SlideBar * * @param amount */ public static void testVibrate(int amount) { getSlideMan().sliders.forEach((String, Arduino) -> Arduino.vibrate(5)); // test PM.reloadAllPluginBaseConfigs(); } /** * Is the backend running? * * @return started */ public static boolean isStarted() { return started; } // TODO rename to something more meaningful than StartIt() /** * Finds and connects to all connected SlideBarsx, adds them all to the * slider hash map, creates the defaults in the slider hash map, prints out * the number of connected SlideBars, and loads the plugins. * * @return */ public static boolean startIt() { // connect and write to arduino if (started == false) { System.out.println("Discovering Arduinos"); // find and connect to all the SlideBars portMan.findAndConnect(); // Add the SlideBars to the Hash map. getSlideMan().hashTheSlideBars(); // TODO this should be moved to the portManager class System.out.println("Number of sliders connected: " + portMan.getArduinos().size()); started = true; PM.loadProcesses(1); Gson gson = new GsonBuilder().create(); try { File settingsFile = new File("settings.json"); settingsFile.createNewFile(); // try (Writer writer = new FileWriter(settingsFile)) { // PluginSettings sObj = new PluginSettings(); // sObj.setUsedSlider("f1n1"); // sObj.getProcesses().add("explorer.exe"); // sObj.getHotkeys().add("alt"); // // GlobalSettings gObj = new GlobalSettings(); // gObj.getPlugins().put(AltProcess.class.getCanonicalName(), sObj); // gObj.getSliders().put("f1n1", new SliderSettings()); // // gson.toJson(gObj, writer); // } try (Reader reader = new FileReader(settingsFile)) { settings = gson.fromJson(reader, GlobalSettings.class); } } catch (IOException e) { e.printStackTrace(); } } return started; } // TODO can this be moved to a different class? private static void updatePrevList(String given) { if (prev20List.contains(given)) { prev20List.remove(given); } prev20List.add(given); } // TODO can this be moved to a different class? public static String[] getPrev20() { return prev20List.toArray(new String[prev20List.size()]); } public static SliderManagerImpl getSlideMan() { return slideMan; } public static GlobalSettings getSettings() { return settings; } public static void setSlideMan(SliderManagerImpl slideMan) { MainBack.slideMan = slideMan; } // TODO rename Run() to something other than Run to avoid confusion // TODO this is a cluster fuck /** * Starts the process of reading the active process and choosing which * process in the proci list to run * * @throws Throwable */ public static void Run() throws Throwable { boolean changed = false; boolean runThisPlugin = false; while (started && !PM.getProci().isEmpty()) { try { Thread.sleep(1); } catch (Exception e) { } String activeProcess = ActiveProcess.getProcess(); String hotKeys = Arrays.toString(KeyHook.getHotKeys()); String previousActiveProcess = null; String previousHotKeys = null; if ((previousActiveProcess != activeProcess) || (previousHotKeys != hotKeys)) { updatePrevList(activeProcess); getSlideMan().sliders.forEach((String, Arduino) -> Arduino.removeParts()); changed = true; } for (SlideBarPlugin plugin : PM.getProci()) { String pluginID = plugin.getClass().getCanonicalName(); if (settings.getPlugins().containsKey(pluginID)) { PluginSettings pluginSettings = settings.getPlugins().get(pluginID); runThisPlugin = pluginSettings.isAlwaysRun() || ((pluginSettings.getHotkeys().isEmpty() || pluginSettings.getHotkeys().contains(hotKeys)) && (pluginSettings.getProcesses().isEmpty() || pluginSettings.getProcesses().contains(activeProcess))); // If both lists are empty, only run when the "always run" flag is set if (!pluginSettings.isAlwaysRun() && pluginSettings.getHotkeys().isEmpty() && pluginSettings.getProcesses().isEmpty()) { runThisPlugin = false; } if (runThisPlugin) { if (changed) { plugin.runFirst(activeProcess); } else { plugin.run(activeProcess); } } } } previousActiveProcess = activeProcess; previousHotKeys = hotKeys; } } // TODO add Mac OS support /** * sets up the keyhook. */ public static void setupKeyHook() { // setup keyhook try { Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName()); logger.setLevel(Level.OFF); GlobalScreen.registerNativeHook(); } catch (NativeHookException ex) { System.err.println("There was a problem registering the native hook."); System.err.println(ex.getMessage()); System.exit(1); } x = new KeyHook(); GlobalScreen.addNativeKeyListener(x); } // TODO /** * TODO move to sliderManager class * reconnect to the sliders without reloading plugins. maybe make plugins not run while reconnecting to prevent * issues * * @return */ public static Boolean reconnect() { // TODO return true; } /** * stops the run() function disconnects arduino removes all process from the * process list. * * @return */ public static Boolean stop() { System.out.println("stopping"); getSlideMan().closeAll(); // TODO decide if this needs to move to the Move this to the SliderManager class PM.removeProci(true); started = false; return true; } }
src/main/java/com/github/slidekb/back/MainBack.java
/** Copyright 2017 John Kester (Jack Kester) 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.slidekb.back; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.jnativehook.GlobalScreen; import org.jnativehook.NativeHookException; import com.github.slidekb.api.AlphaKeyManager; import com.github.slidekb.api.HotKeyManager; import com.github.slidekb.api.SlideBarPlugin; import com.github.slidekb.api.Slider; import com.github.slidekb.ifc.resources.RootResource; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.jaxrs.listing.ApiListingResource; import io.swagger.jaxrs.listing.SwaggerSerializers; import io.swagger.jersey.listing.ApiListingResourceJSON; public class MainBack implements Runnable { // TODO decide if this and relating operations on it should be moved to a // different class. /** * The previous 20 unique executables that have been visited. TODO move this * to a different class that makes more sense. */ public static ArrayList<String> prev20List = new ArrayList<String>(); public static PluginManager PM = new PluginManager(); // TODO rename to a more meaningful name private static KeyHook x; /** * boolean that expresses whether the backend has been started or not / is * currently running. */ private static boolean started = false; static AlphaKeyManager alphaKeyManager = new AlphaKeyManagerImpl(); static HotKeyManager hotKeyManager = new HotKeyManagerImpl(); static PortManager portMan = new PortManager(); private static SliderManagerImpl slideMan = new SliderManagerImpl(); // TODO remove this public static Map<String, Slider> sliders = new HashMap<>(); /** * For running without an Interface. creates a new thread and starts it * * @param args */ public static void main(String[] args) { Thread t = new Thread(new MainBack()); t.start(); } @Override public void run() { FirstLoad(); } /** * runs when MainBack and MainFront are first loaded. (I think, TODO double * check that) */ public static void FirstLoad() { setupKeyHook(); startIt(); startRestServer(); while (started) { try { Run(); Thread.sleep(10); } catch (Throwable e) { e.printStackTrace(); } } } public static HttpServer startRestServer() { BeanConfig beanConfig = new BeanConfig(); beanConfig.setVersion("1.0.0"); beanConfig.setTitle("SlideBar REST Interface"); beanConfig.setResourcePackage(RootResource.class.getPackage().getName()); beanConfig.setSchemes(new String[] { "http" }); beanConfig.setHost("localhost:5055"); beanConfig.setScan(true); final ResourceConfig rc = new ResourceConfig(); rc.packages(RootResource.class.getPackage().getName()); rc.register(LoggingFeature.class); rc.register(JacksonFeature.class); rc.register(ApiListingResource.class); rc.register(SwaggerSerializers.class); rc.property(ServerProperties.WADL_FEATURE_DISABLE, true); Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler"); l.setLevel(Level.FINE); l.setUseParentHandlers(false); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(Level.ALL); l.addHandler(ch); try { return GrizzlyHttpServerFactory.createHttpServer(new URI("http://localhost:5055"), rc); } catch (URISyntaxException e) { e.printStackTrace(); return null; } } // TODO move this to a class that makes more sense /** * vibrates each connected SlideBar * * @param amount */ public static void testVibrate(int amount) { getSlideMan().sliders.forEach((String, Arduino) -> Arduino.vibrate(5)); // test PM.reloadAllPluginBaseConfigs(); } /** * Is the backend running? * * @return started */ public static boolean isStarted() { return started; } // TODO rename to something more meaningful than StartIt() /** * Finds and connects to all connected SlideBarsx, adds them all to the * slider hash map, creates the defaults in the slider hash map, prints out * the number of connected SlideBars, and loads the plugins. * * @return */ public static boolean startIt() { // connect and write to arduino if (started == false) { System.out.println("Discovering Arduinos"); // find and connect to all the SlideBars portMan.findAndConnect(); // Add the SlideBars to the Hash map. getSlideMan().hashTheSlideBars(); // TODO this should be moved to the portManager class System.out.println("Number of sliders connected: " + portMan.getArduinos().size()); started = true; PM.loadProcesses(1); } return started; } // TODO can this be moved to a different class? private static void updatePrevList(String given) { if (prev20List.contains(given)) { prev20List.remove(given); } prev20List.add(given); } // TODO can this be moved to a different class? public static String[] getPrev20() { return prev20List.toArray(new String[prev20List.size()]); } public static SliderManagerImpl getSlideMan() { return slideMan; } public static void setSlideMan(SliderManagerImpl slideMan) { MainBack.slideMan = slideMan; } // TODO rename Run() to something other than Run to avoid confusion // TODO this is a cluster fuck /** * Starts the process of reading the active process and choosing which * process in the proci list to run * * @throws Throwable */ public static void Run() throws Throwable { int counter = 0; String previous = ""; while (started && PM.getProci().size() != 0) { boolean exe = true; try { Thread.sleep(1); } catch (Exception e) { } String activeProcess = ActiveProcess.getProcess(); String hotKeys = Arrays.toString(KeyHook.getHotKeys()); // System.out.println(ard.read()); // System.out.println(AP); for (SlideBarPlugin p : PM.getProci()) { for (String processName : p.getProcessNames()) { if (processName.contentEquals(hotKeys)) { exe = false; } } } if (!exe) { if (!previous.equals(hotKeys)) { getSlideMan().sliders.forEach((String, Arduino) -> Arduino.removeParts()); for (SlideBarPlugin p : PM.getProci()) { for (String processName : p.getProcessNames()) { if (processName.contentEquals(hotKeys)) { System.out.println("process change"); previous = processName; p.runFirst(processName); } } } } else { for (SlideBarPlugin p : PM.getProci()) { for (String processName : p.getProcessNames()) { if (processName.contentEquals(hotKeys)) { previous = processName; p.run(processName); } } } } } else { if (!previous.equals(activeProcess)) { getSlideMan().sliders.forEach((String, Arduino) -> Arduino.removeParts()); updatePrevList(activeProcess); for (SlideBarPlugin p : PM.getProci()) { for (String processName : p.getProcessNames()) { if (processName.contentEquals(activeProcess)) { System.out.println("process change"); previous = processName; p.runFirst(processName); } } } } else { for (SlideBarPlugin p : PM.getProci()) { for (String processName : p.getProcessNames()) { if (processName.contentEquals(activeProcess)) { previous = processName; p.run(processName); } } } } } if (exe) { previous = activeProcess; } else { previous = hotKeys; } } } // TODO add Mac OS support /** * sets up the keyhook. */ public static void setupKeyHook() { // setup keyhook try { Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName()); logger.setLevel(Level.OFF); GlobalScreen.registerNativeHook(); } catch (NativeHookException ex) { System.err.println("There was a problem registering the native hook."); System.err.println(ex.getMessage()); System.exit(1); } x = new KeyHook(); GlobalScreen.addNativeKeyListener(x); } // TODO /** * TODO move to sliderManager class * reconnect to the sliders without reloading plugins. maybe make plugins not run while reconnecting to prevent * issues * * @return */ public static Boolean reconnect() { // TODO return true; } /** * stops the run() function disconnects arduino removes all process from the * process list. * * @return */ public static Boolean stop() { System.out.println("stopping"); getSlideMan().closeAll(); // TODO decide if this needs to move to the Move this to the SliderManager class PM.removeProci(true); started = false; return true; } }
Revise plugin run loop
src/main/java/com/github/slidekb/back/MainBack.java
Revise plugin run loop
<ide><path>rc/main/java/com/github/slidekb/back/MainBack.java <ide> <ide> package com.github.slidekb.back; <ide> <add>import java.io.File; <add>import java.io.FileReader; <ide> import java.io.IOException; <add>import java.io.Reader; <ide> import java.net.URI; <ide> import java.net.URISyntaxException; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.HashMap; <del>import java.util.Map; <ide> import java.util.logging.ConsoleHandler; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> <ide> import org.glassfish.grizzly.http.server.HttpServer; <del>import org.glassfish.jersey.filter.LoggingFilter; <ide> import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; <ide> import org.glassfish.jersey.jackson.JacksonFeature; <ide> import org.glassfish.jersey.logging.LoggingFeature; <ide> import com.github.slidekb.api.AlphaKeyManager; <ide> import com.github.slidekb.api.HotKeyManager; <ide> import com.github.slidekb.api.SlideBarPlugin; <del>import com.github.slidekb.api.Slider; <add>import com.github.slidekb.back.settings.GlobalSettings; <add>import com.github.slidekb.back.settings.PluginSettings; <ide> import com.github.slidekb.ifc.resources.RootResource; <add>import com.google.gson.Gson; <add>import com.google.gson.GsonBuilder; <ide> <ide> import io.swagger.jaxrs.config.BeanConfig; <ide> import io.swagger.jaxrs.listing.ApiListingResource; <ide> import io.swagger.jaxrs.listing.SwaggerSerializers; <del>import io.swagger.jersey.listing.ApiListingResourceJSON; <ide> <ide> public class MainBack implements Runnable { <ide> <ide> <ide> private static SliderManagerImpl slideMan = new SliderManagerImpl(); <ide> <del> // TODO remove this <del> public static Map<String, Slider> sliders = new HashMap<>(); <add> private static GlobalSettings settings; <ide> <ide> /** <ide> * For running without an Interface. creates a new thread and starts it <ide> System.out.println("Number of sliders connected: " + portMan.getArduinos().size()); <ide> started = true; <ide> PM.loadProcesses(1); <add> <add> Gson gson = new GsonBuilder().create(); <add> try { <add> File settingsFile = new File("settings.json"); <add> settingsFile.createNewFile(); <add> <add> // try (Writer writer = new FileWriter(settingsFile)) { <add> // PluginSettings sObj = new PluginSettings(); <add> // sObj.setUsedSlider("f1n1"); <add> // sObj.getProcesses().add("explorer.exe"); <add> // sObj.getHotkeys().add("alt"); <add> // <add> // GlobalSettings gObj = new GlobalSettings(); <add> // gObj.getPlugins().put(AltProcess.class.getCanonicalName(), sObj); <add> // gObj.getSliders().put("f1n1", new SliderSettings()); <add> // <add> // gson.toJson(gObj, writer); <add> // } <add> <add> try (Reader reader = new FileReader(settingsFile)) { <add> settings = gson.fromJson(reader, GlobalSettings.class); <add> } <add> } catch (IOException e) { <add> e.printStackTrace(); <add> } <ide> } <ide> return started; <ide> } <ide> return slideMan; <ide> } <ide> <add> public static GlobalSettings getSettings() { <add> return settings; <add> } <add> <ide> public static void setSlideMan(SliderManagerImpl slideMan) { <ide> MainBack.slideMan = slideMan; <ide> } <ide> * @throws Throwable <ide> */ <ide> public static void Run() throws Throwable { <del> int counter = 0; <del> String previous = ""; <del> while (started && PM.getProci().size() != 0) { <del> boolean exe = true; <add> boolean changed = false; <add> boolean runThisPlugin = false; <add> <add> while (started && !PM.getProci().isEmpty()) { <ide> try { <ide> Thread.sleep(1); <ide> } catch (Exception e) { <ide> } <add> <ide> String activeProcess = ActiveProcess.getProcess(); <ide> String hotKeys = Arrays.toString(KeyHook.getHotKeys()); <del> // System.out.println(ard.read()); <del> // System.out.println(AP); <del> for (SlideBarPlugin p : PM.getProci()) { <del> for (String processName : p.getProcessNames()) { <del> if (processName.contentEquals(hotKeys)) { <del> exe = false; <add> <add> String previousActiveProcess = null; <add> String previousHotKeys = null; <add> <add> if ((previousActiveProcess != activeProcess) || (previousHotKeys != hotKeys)) { <add> updatePrevList(activeProcess); <add> getSlideMan().sliders.forEach((String, Arduino) -> Arduino.removeParts()); <add> <add> changed = true; <add> } <add> <add> for (SlideBarPlugin plugin : PM.getProci()) { <add> String pluginID = plugin.getClass().getCanonicalName(); <add> <add> if (settings.getPlugins().containsKey(pluginID)) { <add> PluginSettings pluginSettings = settings.getPlugins().get(pluginID); <add> <add> runThisPlugin = pluginSettings.isAlwaysRun() || ((pluginSettings.getHotkeys().isEmpty() || pluginSettings.getHotkeys().contains(hotKeys)) && (pluginSettings.getProcesses().isEmpty() || pluginSettings.getProcesses().contains(activeProcess))); <add> <add> // If both lists are empty, only run when the "always run" flag is set <add> if (!pluginSettings.isAlwaysRun() && pluginSettings.getHotkeys().isEmpty() && pluginSettings.getProcesses().isEmpty()) { <add> runThisPlugin = false; <ide> } <del> } <del> } <del> if (!exe) { <del> if (!previous.equals(hotKeys)) { <del> getSlideMan().sliders.forEach((String, Arduino) -> Arduino.removeParts()); <del> for (SlideBarPlugin p : PM.getProci()) { <del> for (String processName : p.getProcessNames()) { <del> if (processName.contentEquals(hotKeys)) { <del> System.out.println("process change"); <del> previous = processName; <del> <del> p.runFirst(processName); <del> } <del> } <del> } <del> } else { <del> for (SlideBarPlugin p : PM.getProci()) { <del> for (String processName : p.getProcessNames()) { <del> if (processName.contentEquals(hotKeys)) { <del> previous = processName; <del> p.run(processName); <del> } <add> <add> if (runThisPlugin) { <add> if (changed) { <add> plugin.runFirst(activeProcess); <add> } else { <add> plugin.run(activeProcess); <ide> } <ide> } <ide> } <del> } else { <del> if (!previous.equals(activeProcess)) { <del> getSlideMan().sliders.forEach((String, Arduino) -> Arduino.removeParts()); <del> updatePrevList(activeProcess); <del> for (SlideBarPlugin p : PM.getProci()) { <del> for (String processName : p.getProcessNames()) { <del> if (processName.contentEquals(activeProcess)) { <del> System.out.println("process change"); <del> previous = processName; <del> <del> p.runFirst(processName); <del> } <del> } <del> } <del> } else { <del> for (SlideBarPlugin p : PM.getProci()) { <del> for (String processName : p.getProcessNames()) { <del> if (processName.contentEquals(activeProcess)) { <del> previous = processName; <del> p.run(processName); <del> <del> } <del> } <del> } <del> } <del> } <del> <del> if (exe) { <del> previous = activeProcess; <del> } else { <del> previous = hotKeys; <del> } <del> <add> } <add> <add> previousActiveProcess = activeProcess; <add> previousHotKeys = hotKeys; <ide> } <ide> } <ide>
Java
apache-2.0
8034f3d8b1723fffc7c8d9ea6217a69aed6d9cf8
0
freme-project/basic-services,freme-project/basic-services,freme-project/basic-services
package eu.freme.bservices.testhelper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.request.HttpRequest; import eu.freme.common.rest.BaseRestController; import org.apache.log4j.Logger; import org.json.JSONObject; import org.junit.Before; import org.springframework.http.HttpStatus; import static org.junit.Assert.assertTrue; /** * Created by Arne Binder ([email protected]) on 13.01.2016. */ public class AuthenticatedTestHelper extends TestHelper { Logger logger = Logger.getLogger(AuthenticatedTestHelper.class); private static String tokenWithPermission; private static String tokenWithOutPermission; private static String tokenAdmin; private static boolean authenticated = false; private final String usernameWithPermission = "userwithpermission"; private final String passwordWithPermission = "testpassword"; private final String usernameWithoutPermission = "userwithoutpermission"; private final String passwordWithoutPermission = "testpassword"; public AuthenticatedTestHelper(String packageConfigFileName) throws UnirestException { super(packageConfigFileName); authenticateUsers(); } /** * This method creates and authenticates two users, userwithpermission and userwithoutpermission. * Furthermore the admin token is created. * * @throws UnirestException */ public void authenticateUsers() throws UnirestException { if (!authenticated) { //Creates two users, one intended to have permission, the other not createUser(usernameWithPermission, passwordWithPermission); tokenWithPermission = authenticateUser(usernameWithPermission, passwordWithPermission); createUser(usernameWithoutPermission, passwordWithoutPermission); tokenWithOutPermission = authenticateUser(usernameWithoutPermission, passwordWithoutPermission); //ConfigurableApplicationContext context = IntegrationTestSetup.getApplicationContext(); tokenAdmin = authenticateUser(getAdminUsername(), getAdminPassword()); authenticated = true; } } /** * This method deletes the users created for authentication purposes. * * @throws UnirestException */ public void removeAuthenticatedUsers() throws UnirestException { if (authenticated) { deleteUser(usernameWithPermission, tokenWithPermission); deleteUser(usernameWithoutPermission, tokenWithOutPermission); authenticated = false; } } /** * Use this method to add an authentication header to the request. * If the given token is null, the request will not be modified. * * @param request The request to add the authentication * @param token The authentication Token * @param <T> * @return The modified request */ @SuppressWarnings("unchecked") private <T extends HttpRequest> T addAuthentication(T request, String token) { if (token == null) return request; return (T) request.header("X-Auth-Token", token); } /** * Add authentication for the user intended to have permission to the given request. * * @param request the request to modify * @return the modified request */ public <T extends HttpRequest> T addAuthentication(T request) { return addAuthentication(request, tokenWithPermission); } /** * Add authentication for the user intended to have no permission to the given request. * * @param request the request to modify * @return the modified request */ public <T extends HttpRequest> T addAuthenticationWithoutPermission(T request) { return addAuthentication(request, tokenWithOutPermission); } /** * Add authentication for the admin user to the given request. * * @param request the request to modify * @return the modified request */ public <T extends HttpRequest> T addAuthenticationWithAdmin(T request) { return addAuthentication(request, tokenAdmin); } public void createUser(String username, String password) throws UnirestException { logger.info("create user: " + username); HttpResponse<String> response = Unirest.post(getAPIBaseUrl() + "/user") .queryString("username", username) .queryString("password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); } public void deleteUser(String username, String token) throws UnirestException { logger.info("delete user: " + username); HttpResponse<String> response = addAuthentication(Unirest.delete(getAPIBaseUrl() + "/user/" + username), token).asString(); assertTrue(response.getStatus() == HttpStatus.NO_CONTENT.value()); } public String authenticateUser(String username, String password) throws UnirestException { HttpResponse<String> response; logger.info("login with new user / create token"); response = Unirest .post(getAPIBaseUrl() + BaseRestController.authenticationEndpoint) .header("X-Auth-Username", username) .header("X-Auth-Password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); String token = new JSONObject(response.getBody()).getString("token"); return token; } }
test-helper/src/main/java/eu/freme/bservices/testhelper/AuthenticatedTestHelper.java
package eu.freme.bservices.testhelper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.request.HttpRequest; import eu.freme.common.rest.BaseRestController; import org.apache.log4j.Logger; import org.json.JSONObject; import org.junit.Before; import org.springframework.http.HttpStatus; import static org.junit.Assert.assertTrue; /** * Created by Arne Binder ([email protected]) on 13.01.2016. */ public class AuthenticatedTestHelper extends TestHelper { Logger logger = Logger.getLogger(AuthenticatedTestHelper.class); private static String tokenWithPermission; private static String tokenWithOutPermission; private static String tokenAdmin; private static boolean authenticated = false; private static boolean authenticatedRemoved = false; private final String usernameWithPermission = "userwithpermission"; private final String passwordWithPermission = "testpassword"; private final String usernameWithoutPermission = "userwithoutpermission"; private final String passwordWithoutPermission = "testpassword"; public AuthenticatedTestHelper(String packageConfigFileName) throws UnirestException { super(packageConfigFileName); authenticateUsers(); } /** * This method creates and authenticates two users, userwithpermission and userwithoutpermission. * Furthermore the admin token is created. * * @throws UnirestException */ public void authenticateUsers() throws UnirestException { if (!authenticated) { //Creates two users, one intended to have permission, the other not createUser(usernameWithPermission, passwordWithPermission); tokenWithPermission = authenticateUser(usernameWithPermission, passwordWithPermission); createUser(usernameWithoutPermission, passwordWithoutPermission); tokenWithOutPermission = authenticateUser(usernameWithoutPermission, passwordWithoutPermission); //ConfigurableApplicationContext context = IntegrationTestSetup.getApplicationContext(); tokenAdmin = authenticateUser(getAdminUsername(), getAdminPassword()); authenticated = true; } } /** * This method deletes the users created for authentication purposes. * * @throws UnirestException */ public void removeAuthenticatedUsers() throws UnirestException { if (!authenticatedRemoved) { deleteUser(usernameWithPermission, tokenWithPermission); deleteUser(usernameWithoutPermission, tokenWithOutPermission); authenticatedRemoved = true; } } /** * Use this method to add an authentication header to the request. * If the given token is null, the request will not be modified. * * @param request The request to add the authentication * @param token The authentication Token * @param <T> * @return The modified request */ @SuppressWarnings("unchecked") private <T extends HttpRequest> T addAuthentication(T request, String token) { if (token == null) return request; return (T) request.header("X-Auth-Token", token); } /** * Add authentication for the user intended to have permission to the given request. * * @param request the request to modify * @return the modified request */ public <T extends HttpRequest> T addAuthentication(T request) { return addAuthentication(request, tokenWithPermission); } /** * Add authentication for the user intended to have no permission to the given request. * * @param request the request to modify * @return the modified request */ public <T extends HttpRequest> T addAuthenticationWithoutPermission(T request) { return addAuthentication(request, tokenWithOutPermission); } /** * Add authentication for the admin user to the given request. * * @param request the request to modify * @return the modified request */ public <T extends HttpRequest> T addAuthenticationWithAdmin(T request) { return addAuthentication(request, tokenAdmin); } public void createUser(String username, String password) throws UnirestException { logger.info("create user: " + username); HttpResponse<String> response = Unirest.post(getAPIBaseUrl() + "/user") .queryString("username", username) .queryString("password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); } public void deleteUser(String username, String token) throws UnirestException { logger.info("delete user: " + username); HttpResponse<String> response = addAuthentication(Unirest.delete(getAPIBaseUrl() + "/user/" + username), token).asString(); assertTrue(response.getStatus() == HttpStatus.NO_CONTENT.value()); } public String authenticateUser(String username, String password) throws UnirestException { HttpResponse<String> response; logger.info("login with new user / create token"); response = Unirest .post(getAPIBaseUrl() + BaseRestController.authenticationEndpoint) .header("X-Auth-Username", username) .header("X-Auth-Password", password).asString(); assertTrue(response.getStatus() == HttpStatus.OK.value()); String token = new JSONObject(response.getBody()).getString("token"); return token; } }
minor fix
test-helper/src/main/java/eu/freme/bservices/testhelper/AuthenticatedTestHelper.java
minor fix
<ide><path>est-helper/src/main/java/eu/freme/bservices/testhelper/AuthenticatedTestHelper.java <ide> private static String tokenAdmin; <ide> <ide> private static boolean authenticated = false; <del> private static boolean authenticatedRemoved = false; <ide> <ide> private final String usernameWithPermission = "userwithpermission"; <ide> private final String passwordWithPermission = "testpassword"; <ide> * @throws UnirestException <ide> */ <ide> public void removeAuthenticatedUsers() throws UnirestException { <del> if (!authenticatedRemoved) { <add> if (authenticated) { <ide> deleteUser(usernameWithPermission, tokenWithPermission); <ide> deleteUser(usernameWithoutPermission, tokenWithOutPermission); <del> authenticatedRemoved = true; <add> authenticated = false; <ide> } <ide> } <ide>
JavaScript
mit
2457f22b4135429cc1b276bb2ff29364d31adb19
0
buildkite/frontend,fotinakis/buildkite-frontend,buildkite/frontend,fotinakis/buildkite-frontend
import React from 'react'; import Relay from 'react-relay'; import PusherStore from '../../../stores/PusherStore'; import Button from '../../shared/Button'; import Spinner from '../../shared/Spinner'; import Build from './build'; class BuildsDropdown extends React.Component { static propTypes = { viewer: React.PropTypes.object, relay: React.PropTypes.object.isRequired } state = { fetching: true } componentDidMount() { PusherStore.on("user_stats:change", this.handlePusherWebsocketEvent); this.props.relay.forceFetch({ isMounted: true }, (readyState) => { // Now that we've got the data, turn off the spinner if (readyState.done) { this.setState({ fetching: false }); } }); } componentWillUnmount() { PusherStore.off("user_stats:change", this.handlePusherWebsocketEvent); } render() { if (this.state.fetching) { return this.renderSpinner(); } else if (this.props.viewer.user.builds.edges.length > 0) { return this.renderBuilds(); } else { return this.renderSetupInstructions(); } } renderBuilds() { return ( <div> <div className="px3 py2"> {this.props.viewer.user.builds.edges.map((edge) => <Build key={edge.node.id} build={edge.node} />)} </div> <div className="pb2 px3"> <Button href="/builds" theme="default" outline={true} className="center" style={{ width: "100%" }}>More Builds</Button> </div> </div> ); } renderSetupInstructions() { return ( <div className="px3 py2"> <div className="mb2">To have your builds shown here, make sure to add and verify your commit email address (e.g. <code className="border border-gray dark-gray" style={{ padding: '.1em .3em' }}>git config user.email</code>) to your list of email addresses.</div> <Button href="/user/emails" theme="default" outline={true} className="center" style={{ width: "100%" }}>Update Email Addresses</Button> </div> ); } renderSpinner() { return ( <div className="px3 py2 center"> <Spinner /> </div> ); } handlePusherWebsocketEvent = (payload) => { // Only do a relay update of the builds count changes if (this._buildsCount !== payload.buildsCount) { this.props.relay.forceFetch(); } // Save the new builds count this._buildsCount = payload.buildsCount; }; } export default Relay.createContainer(BuildsDropdown, { initialVariables: { isMounted: false }, fragments: { viewer: () => Relay.QL` fragment on Viewer { user { builds(first: 5) @include(if: $isMounted) { edges { node { id ${Build.getFragment('build')} } } } } } ` } });
app/components/user/BuildsDropdown/index.js
import React from 'react'; import Relay from 'react-relay'; import PusherStore from '../../../stores/PusherStore'; import Button from '../../shared/Button'; import Spinner from '../../shared/Spinner'; import Build from './build'; class BuildsDropdown extends React.Component { static propTypes = { viewer: React.PropTypes.object, relay: React.PropTypes.object.isRequired } state = { fetching: true } componentDidMount() { PusherStore.on("user_stats:change", this.handlePusherWebsocketEvent); this.props.relay.forceFetch({ isMounted: true }, (readyState) => { // Now that we've got the data, turn off the spinner if (readyState.done) { this.setState({ fetching: false }); } }); } componentWillUnmount() { PusherStore.off("user_stats:change", this.handlePusherWebsocketEvent); } render() { if (this.state.fetching) { return this.renderSpinner(); } else if (this.props.viewer.user.builds.edges.length > 0) { return this.renderBuilds(); } else { return this.renderSetupInstructions(); } } renderBuilds() { return ( <div> <div className="px3 py2"> {this.props.viewer.user.builds.edges.map((edge) => <Build key={edge.node.id} build={edge.node} />)} </div> <div className="pb2 px3"> <Button href="/builds" theme="default" outline={true} className="center" style={{ width: "100%" }}>More Builds</Button> </div> </div> ); } renderSetupInstructions() { return ( <div className="px3 py2"> <div className="mb3 dark-gray">To have your builds shown here, make sure to add and verify your commit email address (e.g. <code className="border border-gray black" style={{ padding: '.1em .3em' }}>git config user.email</code>) to your list of email addresses.</div> <Button href="/user/emails" theme="default" outline={true} className="center" style={{ width: "100%" }}>Update Email Addresses</Button> </div> ); } renderSpinner() { return ( <div className="px3 py2 center"> <Spinner /> </div> ); } handlePusherWebsocketEvent = (payload) => { // Only do a relay update of the builds count changes if (this._buildsCount !== payload.buildsCount) { this.props.relay.forceFetch(); } // Save the new builds count this._buildsCount = payload.buildsCount; }; } export default Relay.createContainer(BuildsDropdown, { initialVariables: { isMounted: false }, fragments: { viewer: () => Relay.QL` fragment on Viewer { user { builds(first: 5) @include(if: $isMounted) { edges { node { id ${Build.getFragment('build')} } } } } } ` } });
Update color and spacing
app/components/user/BuildsDropdown/index.js
Update color and spacing
<ide><path>pp/components/user/BuildsDropdown/index.js <ide> renderSetupInstructions() { <ide> return ( <ide> <div className="px3 py2"> <del> <div className="mb3 dark-gray">To have your builds shown here, make sure to add and verify your commit email address (e.g. <code className="border border-gray black" style={{ padding: '.1em .3em' }}>git config user.email</code>) to your list of email addresses.</div> <add> <div className="mb2">To have your builds shown here, make sure to add and verify your commit email address (e.g. <code className="border border-gray dark-gray" style={{ padding: '.1em .3em' }}>git config user.email</code>) to your list of email addresses.</div> <ide> <Button href="/user/emails" theme="default" outline={true} className="center" style={{ width: "100%" }}>Update Email Addresses</Button> <ide> </div> <ide> );
JavaScript
apache-2.0
e8f4cd55155fef8e256b81b8047799eedcc009bd
0
lato333/guacamole-client,necouchman/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,lato333/guacamole-client,mike-jumper/incubator-guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,mike-jumper/incubator-guacamole-client,lato333/guacamole-client,jmuehlner/incubator-guacamole-client,necouchman/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,glyptodon/guacamole-client,lato333/guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,glyptodon/guacamole-client,softpymesJeffer/incubator-guacamole-client,esmailpour-hosein/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,softpymesJeffer/incubator-guacamole-client,jmuehlner/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. */ var Guacamole = Guacamole || {}; /** * Guacamole protocol client. Given a {@link Guacamole.Tunnel}, * automatically handles incoming and outgoing Guacamole instructions via the * provided tunnel, updating its display using one or more canvas elements. * * @constructor * @param {Guacamole.Tunnel} tunnel The tunnel to use to send and receive * Guacamole instructions. */ Guacamole.Client = function(tunnel) { var guac_client = this; var STATE_IDLE = 0; var STATE_CONNECTING = 1; var STATE_WAITING = 2; var STATE_CONNECTED = 3; var STATE_DISCONNECTING = 4; var STATE_DISCONNECTED = 5; var currentState = STATE_IDLE; var currentTimestamp = 0; var pingInterval = null; /** * Translation from Guacamole protocol line caps to Layer line caps. * @private */ var lineCap = { 0: "butt", 1: "round", 2: "square" }; /** * Translation from Guacamole protocol line caps to Layer line caps. * @private */ var lineJoin = { 0: "bevel", 1: "miter", 2: "round" }; /** * The underlying Guacamole display. * * @private * @type {Guacamole.Display} */ var display = new Guacamole.Display(); /** * All available layers and buffers * * @private * @type {Object.<Number, (Guacamole.Display.VisibleLayer|Guacamole.Layer)>} */ var layers = {}; /** * All audio players currently in use by the client. Initially, this will * be empty, but audio players may be allocated by the server upon request. * * @private * @type {Object.<Number, Guacamole.AudioPlayer>} */ var audioPlayers = {}; /** * All video players currently in use by the client. Initially, this will * be empty, but video players may be allocated by the server upon request. * * @private * @type {Object.<Number, Guacamole.VideoPlayer>} */ var videoPlayers = {}; // No initial parsers var parsers = []; // No initial streams var streams = []; /** * All current objects. The index of each object is dictated by the * Guacamole server. * * @private * @type {Guacamole.Object[]} */ var objects = []; // Pool of available stream indices var stream_indices = new Guacamole.IntegerPool(); // Array of allocated output streams by index var output_streams = []; function setState(state) { if (state != currentState) { currentState = state; if (guac_client.onstatechange) guac_client.onstatechange(currentState); } } function isConnected() { return currentState == STATE_CONNECTED || currentState == STATE_WAITING; } /** * Produces an opaque representation of Guacamole.Client state which can be * later imported through a call to importState(). This object is * effectively an independent, compressed snapshot of protocol and display * state. Invoking this function implicitly flushes the display. * * @param {function} callback * Callback which should be invoked once the state object is ready. The * state object will be passed to the callback as the sole parameter. * This callback may be invoked immediately, or later as the display * finishes rendering and becomes ready. */ this.exportState = function exportState(callback) { // Start with empty state var state = { 'currentState' : currentState, 'currentTimestamp' : currentTimestamp, 'layers' : {} }; var layersSnapshot = {}; // Make a copy of all current layers (protocol state) for (var key in layers) { layersSnapshot[key] = layers[key]; } // Populate layers once data is available (display state, requires flush) display.flush(function populateLayers() { // Export each defined layer/buffer for (var key in layersSnapshot) { var index = parseInt(key); var layer = layersSnapshot[key]; var canvas = layer.toCanvas(); // Store layer/buffer dimensions var exportLayer = { 'width' : layer.width, 'height' : layer.height }; // Store layer/buffer image data, if it can be generated if (layer.width && layer.height) exportLayer.url = canvas.toDataURL('image/png'); // Add layer properties if not a buffer nor the default layer if (index > 0) { exportLayer.x = layer.x; exportLayer.y = layer.y; exportLayer.z = layer.z; exportLayer.alpha = layer.alpha; exportLayer.matrix = layer.matrix; exportLayer.parent = getLayerIndex(layer.parent); } // Store exported layer state.layers[key] = exportLayer; } // Invoke callback now that the state is ready callback(state); }); }; /** * Restores Guacamole.Client protocol and display state based on an opaque * object from a prior call to exportState(). The Guacamole.Client instance * used to export that state need not be the same as this instance. * * @param {Object} state * An opaque representation of Guacamole.Client state from a prior call * to exportState(). * * @param {function} [callback] * The function to invoke when state has finished being imported. This * may happen immediately, or later as images within the provided state * object are loaded. */ this.importState = function importState(state, callback) { var key; var index; currentState = state.currentState; currentTimestamp = state.currentTimestamp; // Dispose of all layers for (key in layers) { index = parseInt(key); if (index > 0) display.dispose(layers[key]); } layers = {}; // Import state of each layer/buffer for (key in state.layers) { index = parseInt(key); var importLayer = state.layers[key]; var layer = getLayer(index); // Reset layer size display.resize(layer, importLayer.width, importLayer.height); // Initialize new layer if it has associated data if (importLayer.url) { display.setChannelMask(layer, Guacamole.Layer.SRC); display.draw(layer, 0, 0, importLayer.url); } // Set layer-specific properties if not a buffer nor the default layer if (index > 0 && importLayer.parent >= 0) { // Apply layer position and set parent var parent = getLayer(importLayer.parent); display.move(layer, parent, importLayer.x, importLayer.y, importLayer.z); // Set layer transparency display.shade(layer, importLayer.alpha); // Apply matrix transform var matrix = importLayer.matrix; display.distort(layer, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } } // Flush changes to display display.flush(callback); }; /** * Returns the underlying display of this Guacamole.Client. The display * contains an Element which can be added to the DOM, causing the * display to become visible. * * @return {Guacamole.Display} The underlying display of this * Guacamole.Client. */ this.getDisplay = function() { return display; }; /** * Sends the current size of the screen. * * @param {Number} width The width of the screen. * @param {Number} height The height of the screen. */ this.sendSize = function(width, height) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("size", width, height); }; /** * Sends a key event having the given properties as if the user * pressed or released a key. * * @param {Boolean} pressed Whether the key is pressed (true) or released * (false). * @param {Number} keysym The keysym of the key being pressed or released. */ this.sendKeyEvent = function(pressed, keysym) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("key", keysym, pressed); }; /** * Sends a mouse event having the properties provided by the given mouse * state. * * @param {Guacamole.Mouse.State} mouseState The state of the mouse to send * in the mouse event. */ this.sendMouseState = function(mouseState) { // Do not send requests if not connected if (!isConnected()) return; // Update client-side cursor display.moveCursor( Math.floor(mouseState.x), Math.floor(mouseState.y) ); // Build mask var buttonMask = 0; if (mouseState.left) buttonMask |= 1; if (mouseState.middle) buttonMask |= 2; if (mouseState.right) buttonMask |= 4; if (mouseState.up) buttonMask |= 8; if (mouseState.down) buttonMask |= 16; // Send message tunnel.sendMessage("mouse", Math.floor(mouseState.x), Math.floor(mouseState.y), buttonMask); }; /** * Sets the clipboard of the remote client to the given text data. * * @deprecated Use createClipboardStream() instead. * @param {String} data The data to send as the clipboard contents. */ this.setClipboard = function(data) { // Do not send requests if not connected if (!isConnected()) return; // Open stream var stream = guac_client.createClipboardStream("text/plain"); var writer = new Guacamole.StringWriter(stream); // Send text chunks for (var i=0; i<data.length; i += 4096) writer.sendText(data.substring(i, i+4096)); // Close stream writer.sendEnd(); }; /** * Allocates an available stream index and creates a new * Guacamole.OutputStream using that index, associating the resulting * stream with this Guacamole.Client. Note that this stream will not yet * exist as far as the other end of the Guacamole connection is concerned. * Streams exist within the Guacamole protocol only when referenced by an * instruction which creates the stream, such as a "clipboard", "file", or * "pipe" instruction. * * @returns {Guacamole.OutputStream} * A new Guacamole.OutputStream with a newly-allocated index and * associated with this Guacamole.Client. */ this.createOutputStream = function createOutputStream() { // Allocate index var index = stream_indices.next(); // Return new stream var stream = output_streams[index] = new Guacamole.OutputStream(guac_client, index); return stream; }; /** * Opens a new audio stream for writing, where audio data having the give * mimetype will be sent along the returned stream. The instruction * necessary to create this stream will automatically be sent. * * @param {String} mimetype * The mimetype of the audio data that will be sent along the returned * stream. * * @return {Guacamole.OutputStream} * The created audio stream. */ this.createAudioStream = function(mimetype) { // Allocate and associate stream with audio metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("audio", stream.index, mimetype); return stream; }; /** * Opens a new file for writing, having the given index, mimetype and * filename. The instruction necessary to create this stream will * automatically be sent. * * @param {String} mimetype The mimetype of the file being sent. * @param {String} filename The filename of the file being sent. * @return {Guacamole.OutputStream} The created file stream. */ this.createFileStream = function(mimetype, filename) { // Allocate and associate stream with file metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("file", stream.index, mimetype, filename); return stream; }; /** * Opens a new pipe for writing, having the given name and mimetype. The * instruction necessary to create this stream will automatically be sent. * * @param {String} mimetype The mimetype of the data being sent. * @param {String} name The name of the pipe. * @return {Guacamole.OutputStream} The created file stream. */ this.createPipeStream = function(mimetype, name) { // Allocate and associate stream with pipe metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("pipe", stream.index, mimetype, name); return stream; }; /** * Opens a new clipboard object for writing, having the given mimetype. The * instruction necessary to create this stream will automatically be sent. * * @param {String} mimetype The mimetype of the data being sent. * @param {String} name The name of the pipe. * @return {Guacamole.OutputStream} The created file stream. */ this.createClipboardStream = function(mimetype) { // Allocate and associate stream with clipboard metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("clipboard", stream.index, mimetype); return stream; }; /** * Creates a new output stream associated with the given object and having * the given mimetype and name. The legality of a mimetype and name is * dictated by the object itself. The instruction necessary to create this * stream will automatically be sent. * * @param {Number} index * The index of the object for which the output stream is being * created. * * @param {String} mimetype * The mimetype of the data which will be sent to the output stream. * * @param {String} name * The defined name of an output stream within the given object. * * @returns {Guacamole.OutputStream} * An output stream which will write blobs to the named output stream * of the given object. */ this.createObjectOutputStream = function createObjectOutputStream(index, mimetype, name) { // Allocate and ssociate stream with object metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("put", index, stream.index, mimetype, name); return stream; }; /** * Requests read access to the input stream having the given name. If * successful, a new input stream will be created. * * @param {Number} index * The index of the object from which the input stream is being * requested. * * @param {String} name * The name of the input stream to request. */ this.requestObjectInputStream = function requestObjectInputStream(index, name) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("get", index, name); }; /** * Acknowledge receipt of a blob on the stream with the given index. * * @param {Number} index The index of the stream associated with the * received blob. * @param {String} message A human-readable message describing the error * or status. * @param {Number} code The error code, if any, or 0 for success. */ this.sendAck = function(index, message, code) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("ack", index, message, code); }; /** * Given the index of a file, writes a blob of data to that file. * * @param {Number} index The index of the file to write to. * @param {String} data Base64-encoded data to write to the file. */ this.sendBlob = function(index, data) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("blob", index, data); }; /** * Marks a currently-open stream as complete. The other end of the * Guacamole connection will be notified via an "end" instruction that the * stream is closed, and the index will be made available for reuse in * future streams. * * @param {Number} index * The index of the stream to end. */ this.endStream = function(index) { // Do not send requests if not connected if (!isConnected()) return; // Explicitly close stream by sending "end" instruction tunnel.sendMessage("end", index); // Free associated index and stream if they exist if (output_streams[index]) { stream_indices.free(index); delete output_streams[index]; } }; /** * Fired whenever the state of this Guacamole.Client changes. * * @event * @param {Number} state The new state of the client. */ this.onstatechange = null; /** * Fired when the remote client sends a name update. * * @event * @param {String} name The new name of this client. */ this.onname = null; /** * Fired when an error is reported by the remote client, and the connection * is being closed. * * @event * @param {Guacamole.Status} status A status object which describes the * error. */ this.onerror = null; /** * Fired when a audio stream is created. The stream provided to this event * handler will contain its own event handlers for received data. * * @event * @param {Guacamole.InputStream} stream * The stream that will receive audio data from the server. * * @param {String} mimetype * The mimetype of the audio data which will be received. * * @return {Guacamole.AudioPlayer} * An object which implements the Guacamole.AudioPlayer interface and * has been initialied to play the data in the provided stream, or null * if the built-in audio players of the Guacamole client should be * used. */ this.onaudio = null; /** * Fired when a video stream is created. The stream provided to this event * handler will contain its own event handlers for received data. * * @event * @param {Guacamole.InputStream} stream * The stream that will receive video data from the server. * * @param {Guacamole.Display.VisibleLayer} layer * The destination layer on which the received video data should be * played. It is the responsibility of the Guacamole.VideoPlayer * implementation to play the received data within this layer. * * @param {String} mimetype * The mimetype of the video data which will be received. * * @return {Guacamole.VideoPlayer} * An object which implements the Guacamole.VideoPlayer interface and * has been initialied to play the data in the provided stream, or null * if the built-in video players of the Guacamole client should be * used. */ this.onvideo = null; /** * Fired when the clipboard of the remote client is changing. * * @event * @param {Guacamole.InputStream} stream The stream that will receive * clipboard data from the server. * @param {String} mimetype The mimetype of the data which will be received. */ this.onclipboard = null; /** * Fired when a file stream is created. The stream provided to this event * handler will contain its own event handlers for received data. * * @event * @param {Guacamole.InputStream} stream The stream that will receive data * from the server. * @param {String} mimetype The mimetype of the file received. * @param {String} filename The name of the file received. */ this.onfile = null; /** * Fired when a filesystem object is created. The object provided to this * event handler will contain its own event handlers and functions for * requesting and handling data. * * @event * @param {Guacamole.Object} object * The created filesystem object. * * @param {String} name * The name of the filesystem. */ this.onfilesystem = null; /** * Fired when a pipe stream is created. The stream provided to this event * handler will contain its own event handlers for received data; * * @event * @param {Guacamole.InputStream} stream The stream that will receive data * from the server. * @param {String} mimetype The mimetype of the data which will be received. * @param {String} name The name of the pipe. */ this.onpipe = null; /** * Fired whenever a sync instruction is received from the server, indicating * that the server is finished processing any input from the client and * has sent any results. * * @event * @param {Number} timestamp The timestamp associated with the sync * instruction. */ this.onsync = null; /** * Returns the layer with the given index, creating it if necessary. * Positive indices refer to visible layers, an index of zero refers to * the default layer, and negative indices refer to buffers. * * @private * @param {Number} index * The index of the layer to retrieve. * * @return {Guacamole.Display.VisibleLayer|Guacamole.Layer} * The layer having the given index. */ var getLayer = function getLayer(index) { // Get layer, create if necessary var layer = layers[index]; if (!layer) { // Create layer based on index if (index === 0) layer = display.getDefaultLayer(); else if (index > 0) layer = display.createLayer(); else layer = display.createBuffer(); // Add new layer layers[index] = layer; } return layer; }; /** * Returns the index passed to getLayer() when the given layer was created. * Positive indices refer to visible layers, an index of zero refers to the * default layer, and negative indices refer to buffers. * * @param {Guacamole.Display.VisibleLayer|Guacamole.Layer} layer * The layer whose index should be determined. * * @returns {Number} * The index of the given layer, or null if no such layer is associated * with this client. */ var getLayerIndex = function getLayerIndex(layer) { // Avoid searching if there clearly is no such layer if (!layer) return null; // Search through each layer, returning the index of the given layer // once found for (var key in layers) { if (layer === layers[key]) return parseInt(key); } // Otherwise, no such index return null; }; function getParser(index) { var parser = parsers[index]; // If parser not yet created, create it, and tie to the // oninstruction handler of the tunnel. if (parser == null) { parser = parsers[index] = new Guacamole.Parser(); parser.oninstruction = tunnel.oninstruction; } return parser; } /** * Handlers for all defined layer properties. * @private */ var layerPropertyHandlers = { "miter-limit": function(layer, value) { display.setMiterLimit(layer, parseFloat(value)); } }; /** * Handlers for all instruction opcodes receivable by a Guacamole protocol * client. * @private */ var instructionHandlers = { "ack": function(parameters) { var stream_index = parseInt(parameters[0]); var reason = parameters[1]; var code = parseInt(parameters[2]); // Get stream var stream = output_streams[stream_index]; if (stream) { // Signal ack if handler defined if (stream.onack) stream.onack(new Guacamole.Status(code, reason)); // If code is an error, invalidate stream if not already // invalidated by onack handler if (code >= 0x0100 && output_streams[stream_index] === stream) { stream_indices.free(stream_index); delete output_streams[stream_index]; } } }, "arc": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); var radius = parseInt(parameters[3]); var startAngle = parseFloat(parameters[4]); var endAngle = parseFloat(parameters[5]); var negative = parseInt(parameters[6]); display.arc(layer, x, y, radius, startAngle, endAngle, negative != 0); }, "audio": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; // Create stream var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); // Get player instance via callback var audioPlayer = null; if (guac_client.onaudio) audioPlayer = guac_client.onaudio(stream, mimetype); // If unsuccessful, try to use a default implementation if (!audioPlayer) audioPlayer = Guacamole.AudioPlayer.getInstance(stream, mimetype); // If we have successfully retrieved an audio player, send success response if (audioPlayer) { audioPlayers[stream_index] = audioPlayer; guac_client.sendAck(stream_index, "OK", 0x0000); } // Otherwise, mimetype must be unsupported else guac_client.sendAck(stream_index, "BAD TYPE", 0x030F); }, "blob": function(parameters) { // Get stream var stream_index = parseInt(parameters[0]); var data = parameters[1]; var stream = streams[stream_index]; // Write data if (stream && stream.onblob) stream.onblob(data); }, "body" : function handleBody(parameters) { // Get object var objectIndex = parseInt(parameters[0]); var object = objects[objectIndex]; var streamIndex = parseInt(parameters[1]); var mimetype = parameters[2]; var name = parameters[3]; // Create stream if handler defined if (object && object.onbody) { var stream = streams[streamIndex] = new Guacamole.InputStream(guac_client, streamIndex); object.onbody(stream, mimetype, name); } // Otherwise, unsupported else guac_client.sendAck(streamIndex, "Receipt of body unsupported", 0x0100); }, "cfill": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var r = parseInt(parameters[2]); var g = parseInt(parameters[3]); var b = parseInt(parameters[4]); var a = parseInt(parameters[5]); display.setChannelMask(layer, channelMask); display.fillColor(layer, r, g, b, a); }, "clip": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.clip(layer); }, "clipboard": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; // Create stream if (guac_client.onclipboard) { var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); guac_client.onclipboard(stream, mimetype); } // Otherwise, unsupported else guac_client.sendAck(stream_index, "Clipboard unsupported", 0x0100); }, "close": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.close(layer); }, "copy": function(parameters) { var srcL = getLayer(parseInt(parameters[0])); var srcX = parseInt(parameters[1]); var srcY = parseInt(parameters[2]); var srcWidth = parseInt(parameters[3]); var srcHeight = parseInt(parameters[4]); var channelMask = parseInt(parameters[5]); var dstL = getLayer(parseInt(parameters[6])); var dstX = parseInt(parameters[7]); var dstY = parseInt(parameters[8]); display.setChannelMask(dstL, channelMask); display.copy(srcL, srcX, srcY, srcWidth, srcHeight, dstL, dstX, dstY); }, "cstroke": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var cap = lineCap[parseInt(parameters[2])]; var join = lineJoin[parseInt(parameters[3])]; var thickness = parseInt(parameters[4]); var r = parseInt(parameters[5]); var g = parseInt(parameters[6]); var b = parseInt(parameters[7]); var a = parseInt(parameters[8]); display.setChannelMask(layer, channelMask); display.strokeColor(layer, cap, join, thickness, r, g, b, a); }, "cursor": function(parameters) { var cursorHotspotX = parseInt(parameters[0]); var cursorHotspotY = parseInt(parameters[1]); var srcL = getLayer(parseInt(parameters[2])); var srcX = parseInt(parameters[3]); var srcY = parseInt(parameters[4]); var srcWidth = parseInt(parameters[5]); var srcHeight = parseInt(parameters[6]); display.setCursor(cursorHotspotX, cursorHotspotY, srcL, srcX, srcY, srcWidth, srcHeight); }, "curve": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var cp1x = parseInt(parameters[1]); var cp1y = parseInt(parameters[2]); var cp2x = parseInt(parameters[3]); var cp2y = parseInt(parameters[4]); var x = parseInt(parameters[5]); var y = parseInt(parameters[6]); display.curveTo(layer, cp1x, cp1y, cp2x, cp2y, x, y); }, "disconnect" : function handleDisconnect(parameters) { // Explicitly tear down connection guac_client.disconnect(); }, "dispose": function(parameters) { var layer_index = parseInt(parameters[0]); // If visible layer, remove from parent if (layer_index > 0) { // Remove from parent var layer = getLayer(layer_index); display.dispose(layer); // Delete reference delete layers[layer_index]; } // If buffer, just delete reference else if (layer_index < 0) delete layers[layer_index]; // Attempting to dispose the root layer currently has no effect. }, "distort": function(parameters) { var layer_index = parseInt(parameters[0]); var a = parseFloat(parameters[1]); var b = parseFloat(parameters[2]); var c = parseFloat(parameters[3]); var d = parseFloat(parameters[4]); var e = parseFloat(parameters[5]); var f = parseFloat(parameters[6]); // Only valid for visible layers (not buffers) if (layer_index >= 0) { var layer = getLayer(layer_index); display.distort(layer, a, b, c, d, e, f); } }, "error": function(parameters) { var reason = parameters[0]; var code = parseInt(parameters[1]); // Call handler if defined if (guac_client.onerror) guac_client.onerror(new Guacamole.Status(code, reason)); guac_client.disconnect(); }, "end": function(parameters) { var stream_index = parseInt(parameters[0]); // Get stream var stream = streams[stream_index]; if (stream) { // Signal end of stream if handler defined if (stream.onend) stream.onend(); // Invalidate stream delete streams[stream_index]; } }, "file": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; var filename = parameters[2]; // Create stream if (guac_client.onfile) { var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); guac_client.onfile(stream, mimetype, filename); } // Otherwise, unsupported else guac_client.sendAck(stream_index, "File transfer unsupported", 0x0100); }, "filesystem" : function handleFilesystem(parameters) { var objectIndex = parseInt(parameters[0]); var name = parameters[1]; // Create object, if supported if (guac_client.onfilesystem) { var object = objects[objectIndex] = new Guacamole.Object(guac_client, objectIndex); guac_client.onfilesystem(object, name); } // If unsupported, simply ignore the availability of the filesystem }, "identity": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.setTransform(layer, 1, 0, 0, 1, 0, 0); }, "img": function(parameters) { var stream_index = parseInt(parameters[0]); var channelMask = parseInt(parameters[1]); var layer = getLayer(parseInt(parameters[2])); var mimetype = parameters[3]; var x = parseInt(parameters[4]); var y = parseInt(parameters[5]); // Create stream var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); var reader = new Guacamole.DataURIReader(stream, mimetype); // Draw image when stream is complete reader.onend = function drawImageBlob() { display.setChannelMask(layer, channelMask); display.draw(layer, x, y, reader.getURI()); }; }, "jpeg": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var x = parseInt(parameters[2]); var y = parseInt(parameters[3]); var data = parameters[4]; display.setChannelMask(layer, channelMask); display.draw(layer, x, y, "data:image/jpeg;base64," + data); }, "lfill": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var srcLayer = getLayer(parseInt(parameters[2])); display.setChannelMask(layer, channelMask); display.fillLayer(layer, srcLayer); }, "line": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); display.lineTo(layer, x, y); }, "lstroke": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var srcLayer = getLayer(parseInt(parameters[2])); display.setChannelMask(layer, channelMask); display.strokeLayer(layer, srcLayer); }, "mouse" : function handleMouse(parameters) { var x = parseInt(parameters[0]); var y = parseInt(parameters[1]); // Display and move software cursor to received coordinates display.showCursor(true); display.moveCursor(x, y); }, "move": function(parameters) { var layer_index = parseInt(parameters[0]); var parent_index = parseInt(parameters[1]); var x = parseInt(parameters[2]); var y = parseInt(parameters[3]); var z = parseInt(parameters[4]); // Only valid for non-default layers if (layer_index > 0 && parent_index >= 0) { var layer = getLayer(layer_index); var parent = getLayer(parent_index); display.move(layer, parent, x, y, z); } }, "name": function(parameters) { if (guac_client.onname) guac_client.onname(parameters[0]); }, "nest": function(parameters) { var parser = getParser(parseInt(parameters[0])); parser.receive(parameters[1]); }, "pipe": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; var name = parameters[2]; // Create stream if (guac_client.onpipe) { var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); guac_client.onpipe(stream, mimetype, name); } // Otherwise, unsupported else guac_client.sendAck(stream_index, "Named pipes unsupported", 0x0100); }, "png": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var x = parseInt(parameters[2]); var y = parseInt(parameters[3]); var data = parameters[4]; display.setChannelMask(layer, channelMask); display.draw(layer, x, y, "data:image/png;base64," + data); }, "pop": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.pop(layer); }, "push": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.push(layer); }, "rect": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); var w = parseInt(parameters[3]); var h = parseInt(parameters[4]); display.rect(layer, x, y, w, h); }, "reset": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.reset(layer); }, "set": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var name = parameters[1]; var value = parameters[2]; // Call property handler if defined var handler = layerPropertyHandlers[name]; if (handler) handler(layer, value); }, "shade": function(parameters) { var layer_index = parseInt(parameters[0]); var a = parseInt(parameters[1]); // Only valid for visible layers (not buffers) if (layer_index >= 0) { var layer = getLayer(layer_index); display.shade(layer, a); } }, "size": function(parameters) { var layer_index = parseInt(parameters[0]); var layer = getLayer(layer_index); var width = parseInt(parameters[1]); var height = parseInt(parameters[2]); display.resize(layer, width, height); }, "start": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); display.moveTo(layer, x, y); }, "sync": function(parameters) { var timestamp = parseInt(parameters[0]); // Flush display, send sync when done display.flush(function displaySyncComplete() { // Synchronize all audio players for (var index in audioPlayers) { var audioPlayer = audioPlayers[index]; if (audioPlayer) audioPlayer.sync(); } // Send sync response to server if (timestamp !== currentTimestamp) { tunnel.sendMessage("sync", timestamp); currentTimestamp = timestamp; } }); // If received first update, no longer waiting. if (currentState === STATE_WAITING) setState(STATE_CONNECTED); // Call sync handler if defined if (guac_client.onsync) guac_client.onsync(timestamp); }, "transfer": function(parameters) { var srcL = getLayer(parseInt(parameters[0])); var srcX = parseInt(parameters[1]); var srcY = parseInt(parameters[2]); var srcWidth = parseInt(parameters[3]); var srcHeight = parseInt(parameters[4]); var function_index = parseInt(parameters[5]); var dstL = getLayer(parseInt(parameters[6])); var dstX = parseInt(parameters[7]); var dstY = parseInt(parameters[8]); /* SRC */ if (function_index === 0x3) display.put(srcL, srcX, srcY, srcWidth, srcHeight, dstL, dstX, dstY); /* Anything else that isn't a NO-OP */ else if (function_index !== 0x5) display.transfer(srcL, srcX, srcY, srcWidth, srcHeight, dstL, dstX, dstY, Guacamole.Client.DefaultTransferFunction[function_index]); }, "transform": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var a = parseFloat(parameters[1]); var b = parseFloat(parameters[2]); var c = parseFloat(parameters[3]); var d = parseFloat(parameters[4]); var e = parseFloat(parameters[5]); var f = parseFloat(parameters[6]); display.transform(layer, a, b, c, d, e, f); }, "undefine" : function handleUndefine(parameters) { // Get object var objectIndex = parseInt(parameters[0]); var object = objects[objectIndex]; // Signal end of object definition if (object && object.onundefine) object.onundefine(); }, "video": function(parameters) { var stream_index = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var mimetype = parameters[2]; // Create stream var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); // Get player instance via callback var videoPlayer = null; if (guac_client.onvideo) videoPlayer = guac_client.onvideo(stream, layer, mimetype); // If unsuccessful, try to use a default implementation if (!videoPlayer) videoPlayer = Guacamole.VideoPlayer.getInstance(stream, layer, mimetype); // If we have successfully retrieved an video player, send success response if (videoPlayer) { videoPlayers[stream_index] = videoPlayer; guac_client.sendAck(stream_index, "OK", 0x0000); } // Otherwise, mimetype must be unsupported else guac_client.sendAck(stream_index, "BAD TYPE", 0x030F); } }; tunnel.oninstruction = function(opcode, parameters) { var handler = instructionHandlers[opcode]; if (handler) handler(parameters); }; /** * Sends a disconnect instruction to the server and closes the tunnel. */ this.disconnect = function() { // Only attempt disconnection not disconnected. if (currentState != STATE_DISCONNECTED && currentState != STATE_DISCONNECTING) { setState(STATE_DISCONNECTING); // Stop ping if (pingInterval) window.clearInterval(pingInterval); // Send disconnect message and disconnect tunnel.sendMessage("disconnect"); tunnel.disconnect(); setState(STATE_DISCONNECTED); } }; /** * Connects the underlying tunnel of this Guacamole.Client, passing the * given arbitrary data to the tunnel during the connection process. * * @param data Arbitrary connection data to be sent to the underlying * tunnel during the connection process. * @throws {Guacamole.Status} If an error occurs during connection. */ this.connect = function(data) { setState(STATE_CONNECTING); try { tunnel.connect(data); } catch (status) { setState(STATE_IDLE); throw status; } // Ping every 5 seconds (ensure connection alive) pingInterval = window.setInterval(function() { tunnel.sendMessage("nop"); }, 5000); setState(STATE_WAITING); }; }; /** * Map of all Guacamole binary raster operations to transfer functions. * @private */ Guacamole.Client.DefaultTransferFunction = { /* BLACK */ 0x0: function (src, dst) { dst.red = dst.green = dst.blue = 0x00; }, /* WHITE */ 0xF: function (src, dst) { dst.red = dst.green = dst.blue = 0xFF; }, /* SRC */ 0x3: function (src, dst) { dst.red = src.red; dst.green = src.green; dst.blue = src.blue; dst.alpha = src.alpha; }, /* DEST (no-op) */ 0x5: function (src, dst) { // Do nothing }, /* Invert SRC */ 0xC: function (src, dst) { dst.red = 0xFF & ~src.red; dst.green = 0xFF & ~src.green; dst.blue = 0xFF & ~src.blue; dst.alpha = src.alpha; }, /* Invert DEST */ 0xA: function (src, dst) { dst.red = 0xFF & ~dst.red; dst.green = 0xFF & ~dst.green; dst.blue = 0xFF & ~dst.blue; }, /* AND */ 0x1: function (src, dst) { dst.red = ( src.red & dst.red); dst.green = ( src.green & dst.green); dst.blue = ( src.blue & dst.blue); }, /* NAND */ 0xE: function (src, dst) { dst.red = 0xFF & ~( src.red & dst.red); dst.green = 0xFF & ~( src.green & dst.green); dst.blue = 0xFF & ~( src.blue & dst.blue); }, /* OR */ 0x7: function (src, dst) { dst.red = ( src.red | dst.red); dst.green = ( src.green | dst.green); dst.blue = ( src.blue | dst.blue); }, /* NOR */ 0x8: function (src, dst) { dst.red = 0xFF & ~( src.red | dst.red); dst.green = 0xFF & ~( src.green | dst.green); dst.blue = 0xFF & ~( src.blue | dst.blue); }, /* XOR */ 0x6: function (src, dst) { dst.red = ( src.red ^ dst.red); dst.green = ( src.green ^ dst.green); dst.blue = ( src.blue ^ dst.blue); }, /* XNOR */ 0x9: function (src, dst) { dst.red = 0xFF & ~( src.red ^ dst.red); dst.green = 0xFF & ~( src.green ^ dst.green); dst.blue = 0xFF & ~( src.blue ^ dst.blue); }, /* AND inverted source */ 0x4: function (src, dst) { dst.red = 0xFF & (~src.red & dst.red); dst.green = 0xFF & (~src.green & dst.green); dst.blue = 0xFF & (~src.blue & dst.blue); }, /* OR inverted source */ 0xD: function (src, dst) { dst.red = 0xFF & (~src.red | dst.red); dst.green = 0xFF & (~src.green | dst.green); dst.blue = 0xFF & (~src.blue | dst.blue); }, /* AND inverted destination */ 0x2: function (src, dst) { dst.red = 0xFF & ( src.red & ~dst.red); dst.green = 0xFF & ( src.green & ~dst.green); dst.blue = 0xFF & ( src.blue & ~dst.blue); }, /* OR inverted destination */ 0xB: function (src, dst) { dst.red = 0xFF & ( src.red | ~dst.red); dst.green = 0xFF & ( src.green | ~dst.green); dst.blue = 0xFF & ( src.blue | ~dst.blue); } };
guacamole-common-js/src/main/webapp/modules/Client.js
/* * 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. */ var Guacamole = Guacamole || {}; /** * Guacamole protocol client. Given a {@link Guacamole.Tunnel}, * automatically handles incoming and outgoing Guacamole instructions via the * provided tunnel, updating its display using one or more canvas elements. * * @constructor * @param {Guacamole.Tunnel} tunnel The tunnel to use to send and receive * Guacamole instructions. */ Guacamole.Client = function(tunnel) { var guac_client = this; var STATE_IDLE = 0; var STATE_CONNECTING = 1; var STATE_WAITING = 2; var STATE_CONNECTED = 3; var STATE_DISCONNECTING = 4; var STATE_DISCONNECTED = 5; var currentState = STATE_IDLE; var currentTimestamp = 0; var pingInterval = null; /** * Translation from Guacamole protocol line caps to Layer line caps. * @private */ var lineCap = { 0: "butt", 1: "round", 2: "square" }; /** * Translation from Guacamole protocol line caps to Layer line caps. * @private */ var lineJoin = { 0: "bevel", 1: "miter", 2: "round" }; /** * The underlying Guacamole display. * * @private * @type {Guacamole.Display} */ var display = new Guacamole.Display(); /** * All available layers and buffers * * @private * @type {Object.<Number, (Guacamole.Display.VisibleLayer|Guacamole.Layer)>} */ var layers = {}; /** * All audio players currently in use by the client. Initially, this will * be empty, but audio players may be allocated by the server upon request. * * @private * @type {Object.<Number, Guacamole.AudioPlayer>} */ var audioPlayers = {}; /** * All video players currently in use by the client. Initially, this will * be empty, but video players may be allocated by the server upon request. * * @private * @type {Object.<Number, Guacamole.VideoPlayer>} */ var videoPlayers = {}; // No initial parsers var parsers = []; // No initial streams var streams = []; /** * All current objects. The index of each object is dictated by the * Guacamole server. * * @private * @type {Guacamole.Object[]} */ var objects = []; // Pool of available stream indices var stream_indices = new Guacamole.IntegerPool(); // Array of allocated output streams by index var output_streams = []; function setState(state) { if (state != currentState) { currentState = state; if (guac_client.onstatechange) guac_client.onstatechange(currentState); } } function isConnected() { return currentState == STATE_CONNECTED || currentState == STATE_WAITING; } /** * Returns an opaque representation of Guacamole.Client state which can be * later imported through a call to importState(). This object is * effectively an independent, compressed snapshot of protocol and display * state. * * @returns {Object} * An opaque representation of Guacamole.Client state which can be * imported through a call to importState(). */ this.exportState = function exportState() { // Start with empty state var state = { 'currentState' : currentState, 'currentTimestamp' : currentTimestamp, 'layers' : {} }; // Export each defined layer/buffer for (var key in layers) { var index = parseInt(key); var layer = layers[key]; var canvas = layer.toCanvas(); // Store layer/buffer dimensions var exportLayer = { 'width' : layer.width, 'height' : layer.height }; // Store layer/buffer image data, if it can be generated if (layer.width && layer.height) exportLayer.url = canvas.toDataURL('image/png'); // Add layer properties if not a buffer nor the default layer if (index > 0) { exportLayer.x = layer.x; exportLayer.y = layer.y; exportLayer.z = layer.z; exportLayer.alpha = layer.alpha; exportLayer.matrix = layer.matrix; exportLayer.parent = getLayerIndex(layer.parent); } // Store exported layer state.layers[key] = exportLayer; } return state; }; /** * Restores Guacamole.Client protocol and display state based on an opaque * object from a prior call to exportState(). The Guacamole.Client instance * used to export that state need not be the same as this instance. * * @param {Object} state * An opaque representation of Guacamole.Client state from a prior call * to exportState(). * * @param {function} [callback] * The function to invoke when state has finished being imported. This * may happen immediately, or later as images within the provided state * object are loaded. */ this.importState = function importState(state, callback) { var key; var index; currentState = state.currentState; currentTimestamp = state.currentTimestamp; // Dispose of all layers for (key in layers) { index = parseInt(key); if (index > 0) display.dispose(layers[key]); } layers = {}; // Import state of each layer/buffer for (key in state.layers) { index = parseInt(key); var importLayer = state.layers[key]; var layer = getLayer(index); // Reset layer size display.resize(layer, importLayer.width, importLayer.height); // Initialize new layer if it has associated data if (importLayer.url) { display.setChannelMask(layer, Guacamole.Layer.SRC); display.draw(layer, 0, 0, importLayer.url); } // Set layer-specific properties if not a buffer nor the default layer if (index > 0 && importLayer.parent >= 0) { // Apply layer position and set parent var parent = getLayer(importLayer.parent); display.move(layer, parent, importLayer.x, importLayer.y, importLayer.z); // Set layer transparency display.shade(layer, importLayer.alpha); // Apply matrix transform var matrix = importLayer.matrix; display.distort(layer, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } } // Flush changes to display display.flush(callback); }; /** * Returns the underlying display of this Guacamole.Client. The display * contains an Element which can be added to the DOM, causing the * display to become visible. * * @return {Guacamole.Display} The underlying display of this * Guacamole.Client. */ this.getDisplay = function() { return display; }; /** * Sends the current size of the screen. * * @param {Number} width The width of the screen. * @param {Number} height The height of the screen. */ this.sendSize = function(width, height) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("size", width, height); }; /** * Sends a key event having the given properties as if the user * pressed or released a key. * * @param {Boolean} pressed Whether the key is pressed (true) or released * (false). * @param {Number} keysym The keysym of the key being pressed or released. */ this.sendKeyEvent = function(pressed, keysym) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("key", keysym, pressed); }; /** * Sends a mouse event having the properties provided by the given mouse * state. * * @param {Guacamole.Mouse.State} mouseState The state of the mouse to send * in the mouse event. */ this.sendMouseState = function(mouseState) { // Do not send requests if not connected if (!isConnected()) return; // Update client-side cursor display.moveCursor( Math.floor(mouseState.x), Math.floor(mouseState.y) ); // Build mask var buttonMask = 0; if (mouseState.left) buttonMask |= 1; if (mouseState.middle) buttonMask |= 2; if (mouseState.right) buttonMask |= 4; if (mouseState.up) buttonMask |= 8; if (mouseState.down) buttonMask |= 16; // Send message tunnel.sendMessage("mouse", Math.floor(mouseState.x), Math.floor(mouseState.y), buttonMask); }; /** * Sets the clipboard of the remote client to the given text data. * * @deprecated Use createClipboardStream() instead. * @param {String} data The data to send as the clipboard contents. */ this.setClipboard = function(data) { // Do not send requests if not connected if (!isConnected()) return; // Open stream var stream = guac_client.createClipboardStream("text/plain"); var writer = new Guacamole.StringWriter(stream); // Send text chunks for (var i=0; i<data.length; i += 4096) writer.sendText(data.substring(i, i+4096)); // Close stream writer.sendEnd(); }; /** * Allocates an available stream index and creates a new * Guacamole.OutputStream using that index, associating the resulting * stream with this Guacamole.Client. Note that this stream will not yet * exist as far as the other end of the Guacamole connection is concerned. * Streams exist within the Guacamole protocol only when referenced by an * instruction which creates the stream, such as a "clipboard", "file", or * "pipe" instruction. * * @returns {Guacamole.OutputStream} * A new Guacamole.OutputStream with a newly-allocated index and * associated with this Guacamole.Client. */ this.createOutputStream = function createOutputStream() { // Allocate index var index = stream_indices.next(); // Return new stream var stream = output_streams[index] = new Guacamole.OutputStream(guac_client, index); return stream; }; /** * Opens a new audio stream for writing, where audio data having the give * mimetype will be sent along the returned stream. The instruction * necessary to create this stream will automatically be sent. * * @param {String} mimetype * The mimetype of the audio data that will be sent along the returned * stream. * * @return {Guacamole.OutputStream} * The created audio stream. */ this.createAudioStream = function(mimetype) { // Allocate and associate stream with audio metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("audio", stream.index, mimetype); return stream; }; /** * Opens a new file for writing, having the given index, mimetype and * filename. The instruction necessary to create this stream will * automatically be sent. * * @param {String} mimetype The mimetype of the file being sent. * @param {String} filename The filename of the file being sent. * @return {Guacamole.OutputStream} The created file stream. */ this.createFileStream = function(mimetype, filename) { // Allocate and associate stream with file metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("file", stream.index, mimetype, filename); return stream; }; /** * Opens a new pipe for writing, having the given name and mimetype. The * instruction necessary to create this stream will automatically be sent. * * @param {String} mimetype The mimetype of the data being sent. * @param {String} name The name of the pipe. * @return {Guacamole.OutputStream} The created file stream. */ this.createPipeStream = function(mimetype, name) { // Allocate and associate stream with pipe metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("pipe", stream.index, mimetype, name); return stream; }; /** * Opens a new clipboard object for writing, having the given mimetype. The * instruction necessary to create this stream will automatically be sent. * * @param {String} mimetype The mimetype of the data being sent. * @param {String} name The name of the pipe. * @return {Guacamole.OutputStream} The created file stream. */ this.createClipboardStream = function(mimetype) { // Allocate and associate stream with clipboard metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("clipboard", stream.index, mimetype); return stream; }; /** * Creates a new output stream associated with the given object and having * the given mimetype and name. The legality of a mimetype and name is * dictated by the object itself. The instruction necessary to create this * stream will automatically be sent. * * @param {Number} index * The index of the object for which the output stream is being * created. * * @param {String} mimetype * The mimetype of the data which will be sent to the output stream. * * @param {String} name * The defined name of an output stream within the given object. * * @returns {Guacamole.OutputStream} * An output stream which will write blobs to the named output stream * of the given object. */ this.createObjectOutputStream = function createObjectOutputStream(index, mimetype, name) { // Allocate and ssociate stream with object metadata var stream = guac_client.createOutputStream(); tunnel.sendMessage("put", index, stream.index, mimetype, name); return stream; }; /** * Requests read access to the input stream having the given name. If * successful, a new input stream will be created. * * @param {Number} index * The index of the object from which the input stream is being * requested. * * @param {String} name * The name of the input stream to request. */ this.requestObjectInputStream = function requestObjectInputStream(index, name) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("get", index, name); }; /** * Acknowledge receipt of a blob on the stream with the given index. * * @param {Number} index The index of the stream associated with the * received blob. * @param {String} message A human-readable message describing the error * or status. * @param {Number} code The error code, if any, or 0 for success. */ this.sendAck = function(index, message, code) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("ack", index, message, code); }; /** * Given the index of a file, writes a blob of data to that file. * * @param {Number} index The index of the file to write to. * @param {String} data Base64-encoded data to write to the file. */ this.sendBlob = function(index, data) { // Do not send requests if not connected if (!isConnected()) return; tunnel.sendMessage("blob", index, data); }; /** * Marks a currently-open stream as complete. The other end of the * Guacamole connection will be notified via an "end" instruction that the * stream is closed, and the index will be made available for reuse in * future streams. * * @param {Number} index * The index of the stream to end. */ this.endStream = function(index) { // Do not send requests if not connected if (!isConnected()) return; // Explicitly close stream by sending "end" instruction tunnel.sendMessage("end", index); // Free associated index and stream if they exist if (output_streams[index]) { stream_indices.free(index); delete output_streams[index]; } }; /** * Fired whenever the state of this Guacamole.Client changes. * * @event * @param {Number} state The new state of the client. */ this.onstatechange = null; /** * Fired when the remote client sends a name update. * * @event * @param {String} name The new name of this client. */ this.onname = null; /** * Fired when an error is reported by the remote client, and the connection * is being closed. * * @event * @param {Guacamole.Status} status A status object which describes the * error. */ this.onerror = null; /** * Fired when a audio stream is created. The stream provided to this event * handler will contain its own event handlers for received data. * * @event * @param {Guacamole.InputStream} stream * The stream that will receive audio data from the server. * * @param {String} mimetype * The mimetype of the audio data which will be received. * * @return {Guacamole.AudioPlayer} * An object which implements the Guacamole.AudioPlayer interface and * has been initialied to play the data in the provided stream, or null * if the built-in audio players of the Guacamole client should be * used. */ this.onaudio = null; /** * Fired when a video stream is created. The stream provided to this event * handler will contain its own event handlers for received data. * * @event * @param {Guacamole.InputStream} stream * The stream that will receive video data from the server. * * @param {Guacamole.Display.VisibleLayer} layer * The destination layer on which the received video data should be * played. It is the responsibility of the Guacamole.VideoPlayer * implementation to play the received data within this layer. * * @param {String} mimetype * The mimetype of the video data which will be received. * * @return {Guacamole.VideoPlayer} * An object which implements the Guacamole.VideoPlayer interface and * has been initialied to play the data in the provided stream, or null * if the built-in video players of the Guacamole client should be * used. */ this.onvideo = null; /** * Fired when the clipboard of the remote client is changing. * * @event * @param {Guacamole.InputStream} stream The stream that will receive * clipboard data from the server. * @param {String} mimetype The mimetype of the data which will be received. */ this.onclipboard = null; /** * Fired when a file stream is created. The stream provided to this event * handler will contain its own event handlers for received data. * * @event * @param {Guacamole.InputStream} stream The stream that will receive data * from the server. * @param {String} mimetype The mimetype of the file received. * @param {String} filename The name of the file received. */ this.onfile = null; /** * Fired when a filesystem object is created. The object provided to this * event handler will contain its own event handlers and functions for * requesting and handling data. * * @event * @param {Guacamole.Object} object * The created filesystem object. * * @param {String} name * The name of the filesystem. */ this.onfilesystem = null; /** * Fired when a pipe stream is created. The stream provided to this event * handler will contain its own event handlers for received data; * * @event * @param {Guacamole.InputStream} stream The stream that will receive data * from the server. * @param {String} mimetype The mimetype of the data which will be received. * @param {String} name The name of the pipe. */ this.onpipe = null; /** * Fired whenever a sync instruction is received from the server, indicating * that the server is finished processing any input from the client and * has sent any results. * * @event * @param {Number} timestamp The timestamp associated with the sync * instruction. */ this.onsync = null; /** * Returns the layer with the given index, creating it if necessary. * Positive indices refer to visible layers, an index of zero refers to * the default layer, and negative indices refer to buffers. * * @private * @param {Number} index * The index of the layer to retrieve. * * @return {Guacamole.Display.VisibleLayer|Guacamole.Layer} * The layer having the given index. */ var getLayer = function getLayer(index) { // Get layer, create if necessary var layer = layers[index]; if (!layer) { // Create layer based on index if (index === 0) layer = display.getDefaultLayer(); else if (index > 0) layer = display.createLayer(); else layer = display.createBuffer(); // Add new layer layers[index] = layer; } return layer; }; /** * Returns the index passed to getLayer() when the given layer was created. * Positive indices refer to visible layers, an index of zero refers to the * default layer, and negative indices refer to buffers. * * @param {Guacamole.Display.VisibleLayer|Guacamole.Layer} layer * The layer whose index should be determined. * * @returns {Number} * The index of the given layer, or null if no such layer is associated * with this client. */ var getLayerIndex = function getLayerIndex(layer) { // Avoid searching if there clearly is no such layer if (!layer) return null; // Search through each layer, returning the index of the given layer // once found for (var key in layers) { if (layer === layers[key]) return parseInt(key); } // Otherwise, no such index return null; }; function getParser(index) { var parser = parsers[index]; // If parser not yet created, create it, and tie to the // oninstruction handler of the tunnel. if (parser == null) { parser = parsers[index] = new Guacamole.Parser(); parser.oninstruction = tunnel.oninstruction; } return parser; } /** * Handlers for all defined layer properties. * @private */ var layerPropertyHandlers = { "miter-limit": function(layer, value) { display.setMiterLimit(layer, parseFloat(value)); } }; /** * Handlers for all instruction opcodes receivable by a Guacamole protocol * client. * @private */ var instructionHandlers = { "ack": function(parameters) { var stream_index = parseInt(parameters[0]); var reason = parameters[1]; var code = parseInt(parameters[2]); // Get stream var stream = output_streams[stream_index]; if (stream) { // Signal ack if handler defined if (stream.onack) stream.onack(new Guacamole.Status(code, reason)); // If code is an error, invalidate stream if not already // invalidated by onack handler if (code >= 0x0100 && output_streams[stream_index] === stream) { stream_indices.free(stream_index); delete output_streams[stream_index]; } } }, "arc": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); var radius = parseInt(parameters[3]); var startAngle = parseFloat(parameters[4]); var endAngle = parseFloat(parameters[5]); var negative = parseInt(parameters[6]); display.arc(layer, x, y, radius, startAngle, endAngle, negative != 0); }, "audio": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; // Create stream var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); // Get player instance via callback var audioPlayer = null; if (guac_client.onaudio) audioPlayer = guac_client.onaudio(stream, mimetype); // If unsuccessful, try to use a default implementation if (!audioPlayer) audioPlayer = Guacamole.AudioPlayer.getInstance(stream, mimetype); // If we have successfully retrieved an audio player, send success response if (audioPlayer) { audioPlayers[stream_index] = audioPlayer; guac_client.sendAck(stream_index, "OK", 0x0000); } // Otherwise, mimetype must be unsupported else guac_client.sendAck(stream_index, "BAD TYPE", 0x030F); }, "blob": function(parameters) { // Get stream var stream_index = parseInt(parameters[0]); var data = parameters[1]; var stream = streams[stream_index]; // Write data if (stream && stream.onblob) stream.onblob(data); }, "body" : function handleBody(parameters) { // Get object var objectIndex = parseInt(parameters[0]); var object = objects[objectIndex]; var streamIndex = parseInt(parameters[1]); var mimetype = parameters[2]; var name = parameters[3]; // Create stream if handler defined if (object && object.onbody) { var stream = streams[streamIndex] = new Guacamole.InputStream(guac_client, streamIndex); object.onbody(stream, mimetype, name); } // Otherwise, unsupported else guac_client.sendAck(streamIndex, "Receipt of body unsupported", 0x0100); }, "cfill": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var r = parseInt(parameters[2]); var g = parseInt(parameters[3]); var b = parseInt(parameters[4]); var a = parseInt(parameters[5]); display.setChannelMask(layer, channelMask); display.fillColor(layer, r, g, b, a); }, "clip": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.clip(layer); }, "clipboard": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; // Create stream if (guac_client.onclipboard) { var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); guac_client.onclipboard(stream, mimetype); } // Otherwise, unsupported else guac_client.sendAck(stream_index, "Clipboard unsupported", 0x0100); }, "close": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.close(layer); }, "copy": function(parameters) { var srcL = getLayer(parseInt(parameters[0])); var srcX = parseInt(parameters[1]); var srcY = parseInt(parameters[2]); var srcWidth = parseInt(parameters[3]); var srcHeight = parseInt(parameters[4]); var channelMask = parseInt(parameters[5]); var dstL = getLayer(parseInt(parameters[6])); var dstX = parseInt(parameters[7]); var dstY = parseInt(parameters[8]); display.setChannelMask(dstL, channelMask); display.copy(srcL, srcX, srcY, srcWidth, srcHeight, dstL, dstX, dstY); }, "cstroke": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var cap = lineCap[parseInt(parameters[2])]; var join = lineJoin[parseInt(parameters[3])]; var thickness = parseInt(parameters[4]); var r = parseInt(parameters[5]); var g = parseInt(parameters[6]); var b = parseInt(parameters[7]); var a = parseInt(parameters[8]); display.setChannelMask(layer, channelMask); display.strokeColor(layer, cap, join, thickness, r, g, b, a); }, "cursor": function(parameters) { var cursorHotspotX = parseInt(parameters[0]); var cursorHotspotY = parseInt(parameters[1]); var srcL = getLayer(parseInt(parameters[2])); var srcX = parseInt(parameters[3]); var srcY = parseInt(parameters[4]); var srcWidth = parseInt(parameters[5]); var srcHeight = parseInt(parameters[6]); display.setCursor(cursorHotspotX, cursorHotspotY, srcL, srcX, srcY, srcWidth, srcHeight); }, "curve": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var cp1x = parseInt(parameters[1]); var cp1y = parseInt(parameters[2]); var cp2x = parseInt(parameters[3]); var cp2y = parseInt(parameters[4]); var x = parseInt(parameters[5]); var y = parseInt(parameters[6]); display.curveTo(layer, cp1x, cp1y, cp2x, cp2y, x, y); }, "disconnect" : function handleDisconnect(parameters) { // Explicitly tear down connection guac_client.disconnect(); }, "dispose": function(parameters) { var layer_index = parseInt(parameters[0]); // If visible layer, remove from parent if (layer_index > 0) { // Remove from parent var layer = getLayer(layer_index); display.dispose(layer); // Delete reference delete layers[layer_index]; } // If buffer, just delete reference else if (layer_index < 0) delete layers[layer_index]; // Attempting to dispose the root layer currently has no effect. }, "distort": function(parameters) { var layer_index = parseInt(parameters[0]); var a = parseFloat(parameters[1]); var b = parseFloat(parameters[2]); var c = parseFloat(parameters[3]); var d = parseFloat(parameters[4]); var e = parseFloat(parameters[5]); var f = parseFloat(parameters[6]); // Only valid for visible layers (not buffers) if (layer_index >= 0) { var layer = getLayer(layer_index); display.distort(layer, a, b, c, d, e, f); } }, "error": function(parameters) { var reason = parameters[0]; var code = parseInt(parameters[1]); // Call handler if defined if (guac_client.onerror) guac_client.onerror(new Guacamole.Status(code, reason)); guac_client.disconnect(); }, "end": function(parameters) { var stream_index = parseInt(parameters[0]); // Get stream var stream = streams[stream_index]; if (stream) { // Signal end of stream if handler defined if (stream.onend) stream.onend(); // Invalidate stream delete streams[stream_index]; } }, "file": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; var filename = parameters[2]; // Create stream if (guac_client.onfile) { var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); guac_client.onfile(stream, mimetype, filename); } // Otherwise, unsupported else guac_client.sendAck(stream_index, "File transfer unsupported", 0x0100); }, "filesystem" : function handleFilesystem(parameters) { var objectIndex = parseInt(parameters[0]); var name = parameters[1]; // Create object, if supported if (guac_client.onfilesystem) { var object = objects[objectIndex] = new Guacamole.Object(guac_client, objectIndex); guac_client.onfilesystem(object, name); } // If unsupported, simply ignore the availability of the filesystem }, "identity": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.setTransform(layer, 1, 0, 0, 1, 0, 0); }, "img": function(parameters) { var stream_index = parseInt(parameters[0]); var channelMask = parseInt(parameters[1]); var layer = getLayer(parseInt(parameters[2])); var mimetype = parameters[3]; var x = parseInt(parameters[4]); var y = parseInt(parameters[5]); // Create stream var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); var reader = new Guacamole.DataURIReader(stream, mimetype); // Draw image when stream is complete reader.onend = function drawImageBlob() { display.setChannelMask(layer, channelMask); display.draw(layer, x, y, reader.getURI()); }; }, "jpeg": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var x = parseInt(parameters[2]); var y = parseInt(parameters[3]); var data = parameters[4]; display.setChannelMask(layer, channelMask); display.draw(layer, x, y, "data:image/jpeg;base64," + data); }, "lfill": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var srcLayer = getLayer(parseInt(parameters[2])); display.setChannelMask(layer, channelMask); display.fillLayer(layer, srcLayer); }, "line": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); display.lineTo(layer, x, y); }, "lstroke": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var srcLayer = getLayer(parseInt(parameters[2])); display.setChannelMask(layer, channelMask); display.strokeLayer(layer, srcLayer); }, "mouse" : function handleMouse(parameters) { var x = parseInt(parameters[0]); var y = parseInt(parameters[1]); // Display and move software cursor to received coordinates display.showCursor(true); display.moveCursor(x, y); }, "move": function(parameters) { var layer_index = parseInt(parameters[0]); var parent_index = parseInt(parameters[1]); var x = parseInt(parameters[2]); var y = parseInt(parameters[3]); var z = parseInt(parameters[4]); // Only valid for non-default layers if (layer_index > 0 && parent_index >= 0) { var layer = getLayer(layer_index); var parent = getLayer(parent_index); display.move(layer, parent, x, y, z); } }, "name": function(parameters) { if (guac_client.onname) guac_client.onname(parameters[0]); }, "nest": function(parameters) { var parser = getParser(parseInt(parameters[0])); parser.receive(parameters[1]); }, "pipe": function(parameters) { var stream_index = parseInt(parameters[0]); var mimetype = parameters[1]; var name = parameters[2]; // Create stream if (guac_client.onpipe) { var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); guac_client.onpipe(stream, mimetype, name); } // Otherwise, unsupported else guac_client.sendAck(stream_index, "Named pipes unsupported", 0x0100); }, "png": function(parameters) { var channelMask = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var x = parseInt(parameters[2]); var y = parseInt(parameters[3]); var data = parameters[4]; display.setChannelMask(layer, channelMask); display.draw(layer, x, y, "data:image/png;base64," + data); }, "pop": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.pop(layer); }, "push": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.push(layer); }, "rect": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); var w = parseInt(parameters[3]); var h = parseInt(parameters[4]); display.rect(layer, x, y, w, h); }, "reset": function(parameters) { var layer = getLayer(parseInt(parameters[0])); display.reset(layer); }, "set": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var name = parameters[1]; var value = parameters[2]; // Call property handler if defined var handler = layerPropertyHandlers[name]; if (handler) handler(layer, value); }, "shade": function(parameters) { var layer_index = parseInt(parameters[0]); var a = parseInt(parameters[1]); // Only valid for visible layers (not buffers) if (layer_index >= 0) { var layer = getLayer(layer_index); display.shade(layer, a); } }, "size": function(parameters) { var layer_index = parseInt(parameters[0]); var layer = getLayer(layer_index); var width = parseInt(parameters[1]); var height = parseInt(parameters[2]); display.resize(layer, width, height); }, "start": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var x = parseInt(parameters[1]); var y = parseInt(parameters[2]); display.moveTo(layer, x, y); }, "sync": function(parameters) { var timestamp = parseInt(parameters[0]); // Flush display, send sync when done display.flush(function displaySyncComplete() { // Synchronize all audio players for (var index in audioPlayers) { var audioPlayer = audioPlayers[index]; if (audioPlayer) audioPlayer.sync(); } // Send sync response to server if (timestamp !== currentTimestamp) { tunnel.sendMessage("sync", timestamp); currentTimestamp = timestamp; } }); // If received first update, no longer waiting. if (currentState === STATE_WAITING) setState(STATE_CONNECTED); // Call sync handler if defined if (guac_client.onsync) guac_client.onsync(timestamp); }, "transfer": function(parameters) { var srcL = getLayer(parseInt(parameters[0])); var srcX = parseInt(parameters[1]); var srcY = parseInt(parameters[2]); var srcWidth = parseInt(parameters[3]); var srcHeight = parseInt(parameters[4]); var function_index = parseInt(parameters[5]); var dstL = getLayer(parseInt(parameters[6])); var dstX = parseInt(parameters[7]); var dstY = parseInt(parameters[8]); /* SRC */ if (function_index === 0x3) display.put(srcL, srcX, srcY, srcWidth, srcHeight, dstL, dstX, dstY); /* Anything else that isn't a NO-OP */ else if (function_index !== 0x5) display.transfer(srcL, srcX, srcY, srcWidth, srcHeight, dstL, dstX, dstY, Guacamole.Client.DefaultTransferFunction[function_index]); }, "transform": function(parameters) { var layer = getLayer(parseInt(parameters[0])); var a = parseFloat(parameters[1]); var b = parseFloat(parameters[2]); var c = parseFloat(parameters[3]); var d = parseFloat(parameters[4]); var e = parseFloat(parameters[5]); var f = parseFloat(parameters[6]); display.transform(layer, a, b, c, d, e, f); }, "undefine" : function handleUndefine(parameters) { // Get object var objectIndex = parseInt(parameters[0]); var object = objects[objectIndex]; // Signal end of object definition if (object && object.onundefine) object.onundefine(); }, "video": function(parameters) { var stream_index = parseInt(parameters[0]); var layer = getLayer(parseInt(parameters[1])); var mimetype = parameters[2]; // Create stream var stream = streams[stream_index] = new Guacamole.InputStream(guac_client, stream_index); // Get player instance via callback var videoPlayer = null; if (guac_client.onvideo) videoPlayer = guac_client.onvideo(stream, layer, mimetype); // If unsuccessful, try to use a default implementation if (!videoPlayer) videoPlayer = Guacamole.VideoPlayer.getInstance(stream, layer, mimetype); // If we have successfully retrieved an video player, send success response if (videoPlayer) { videoPlayers[stream_index] = videoPlayer; guac_client.sendAck(stream_index, "OK", 0x0000); } // Otherwise, mimetype must be unsupported else guac_client.sendAck(stream_index, "BAD TYPE", 0x030F); } }; tunnel.oninstruction = function(opcode, parameters) { var handler = instructionHandlers[opcode]; if (handler) handler(parameters); }; /** * Sends a disconnect instruction to the server and closes the tunnel. */ this.disconnect = function() { // Only attempt disconnection not disconnected. if (currentState != STATE_DISCONNECTED && currentState != STATE_DISCONNECTING) { setState(STATE_DISCONNECTING); // Stop ping if (pingInterval) window.clearInterval(pingInterval); // Send disconnect message and disconnect tunnel.sendMessage("disconnect"); tunnel.disconnect(); setState(STATE_DISCONNECTED); } }; /** * Connects the underlying tunnel of this Guacamole.Client, passing the * given arbitrary data to the tunnel during the connection process. * * @param data Arbitrary connection data to be sent to the underlying * tunnel during the connection process. * @throws {Guacamole.Status} If an error occurs during connection. */ this.connect = function(data) { setState(STATE_CONNECTING); try { tunnel.connect(data); } catch (status) { setState(STATE_IDLE); throw status; } // Ping every 5 seconds (ensure connection alive) pingInterval = window.setInterval(function() { tunnel.sendMessage("nop"); }, 5000); setState(STATE_WAITING); }; }; /** * Map of all Guacamole binary raster operations to transfer functions. * @private */ Guacamole.Client.DefaultTransferFunction = { /* BLACK */ 0x0: function (src, dst) { dst.red = dst.green = dst.blue = 0x00; }, /* WHITE */ 0xF: function (src, dst) { dst.red = dst.green = dst.blue = 0xFF; }, /* SRC */ 0x3: function (src, dst) { dst.red = src.red; dst.green = src.green; dst.blue = src.blue; dst.alpha = src.alpha; }, /* DEST (no-op) */ 0x5: function (src, dst) { // Do nothing }, /* Invert SRC */ 0xC: function (src, dst) { dst.red = 0xFF & ~src.red; dst.green = 0xFF & ~src.green; dst.blue = 0xFF & ~src.blue; dst.alpha = src.alpha; }, /* Invert DEST */ 0xA: function (src, dst) { dst.red = 0xFF & ~dst.red; dst.green = 0xFF & ~dst.green; dst.blue = 0xFF & ~dst.blue; }, /* AND */ 0x1: function (src, dst) { dst.red = ( src.red & dst.red); dst.green = ( src.green & dst.green); dst.blue = ( src.blue & dst.blue); }, /* NAND */ 0xE: function (src, dst) { dst.red = 0xFF & ~( src.red & dst.red); dst.green = 0xFF & ~( src.green & dst.green); dst.blue = 0xFF & ~( src.blue & dst.blue); }, /* OR */ 0x7: function (src, dst) { dst.red = ( src.red | dst.red); dst.green = ( src.green | dst.green); dst.blue = ( src.blue | dst.blue); }, /* NOR */ 0x8: function (src, dst) { dst.red = 0xFF & ~( src.red | dst.red); dst.green = 0xFF & ~( src.green | dst.green); dst.blue = 0xFF & ~( src.blue | dst.blue); }, /* XOR */ 0x6: function (src, dst) { dst.red = ( src.red ^ dst.red); dst.green = ( src.green ^ dst.green); dst.blue = ( src.blue ^ dst.blue); }, /* XNOR */ 0x9: function (src, dst) { dst.red = 0xFF & ~( src.red ^ dst.red); dst.green = 0xFF & ~( src.green ^ dst.green); dst.blue = 0xFF & ~( src.blue ^ dst.blue); }, /* AND inverted source */ 0x4: function (src, dst) { dst.red = 0xFF & (~src.red & dst.red); dst.green = 0xFF & (~src.green & dst.green); dst.blue = 0xFF & (~src.blue & dst.blue); }, /* OR inverted source */ 0xD: function (src, dst) { dst.red = 0xFF & (~src.red | dst.red); dst.green = 0xFF & (~src.green | dst.green); dst.blue = 0xFF & (~src.blue | dst.blue); }, /* AND inverted destination */ 0x2: function (src, dst) { dst.red = 0xFF & ( src.red & ~dst.red); dst.green = 0xFF & ( src.green & ~dst.green); dst.blue = 0xFF & ( src.blue & ~dst.blue); }, /* OR inverted destination */ 0xB: function (src, dst) { dst.red = 0xFF & ( src.red | ~dst.red); dst.green = 0xFF & ( src.green | ~dst.green); dst.blue = 0xFF & ( src.blue | ~dst.blue); } };
GUACAMOLE-250: Merge asynchronous client state export.
guacamole-common-js/src/main/webapp/modules/Client.js
GUACAMOLE-250: Merge asynchronous client state export.
<ide><path>uacamole-common-js/src/main/webapp/modules/Client.js <ide> } <ide> <ide> /** <del> * Returns an opaque representation of Guacamole.Client state which can be <add> * Produces an opaque representation of Guacamole.Client state which can be <ide> * later imported through a call to importState(). This object is <ide> * effectively an independent, compressed snapshot of protocol and display <del> * state. <del> * <del> * @returns {Object} <del> * An opaque representation of Guacamole.Client state which can be <del> * imported through a call to importState(). <del> */ <del> this.exportState = function exportState() { <add> * state. Invoking this function implicitly flushes the display. <add> * <add> * @param {function} callback <add> * Callback which should be invoked once the state object is ready. The <add> * state object will be passed to the callback as the sole parameter. <add> * This callback may be invoked immediately, or later as the display <add> * finishes rendering and becomes ready. <add> */ <add> this.exportState = function exportState(callback) { <ide> <ide> // Start with empty state <ide> var state = { <ide> 'layers' : {} <ide> }; <ide> <del> // Export each defined layer/buffer <add> var layersSnapshot = {}; <add> <add> // Make a copy of all current layers (protocol state) <ide> for (var key in layers) { <del> <del> var index = parseInt(key); <del> var layer = layers[key]; <del> var canvas = layer.toCanvas(); <del> <del> // Store layer/buffer dimensions <del> var exportLayer = { <del> 'width' : layer.width, <del> 'height' : layer.height <del> }; <del> <del> // Store layer/buffer image data, if it can be generated <del> if (layer.width && layer.height) <del> exportLayer.url = canvas.toDataURL('image/png'); <del> <del> // Add layer properties if not a buffer nor the default layer <del> if (index > 0) { <del> exportLayer.x = layer.x; <del> exportLayer.y = layer.y; <del> exportLayer.z = layer.z; <del> exportLayer.alpha = layer.alpha; <del> exportLayer.matrix = layer.matrix; <del> exportLayer.parent = getLayerIndex(layer.parent); <add> layersSnapshot[key] = layers[key]; <add> } <add> <add> // Populate layers once data is available (display state, requires flush) <add> display.flush(function populateLayers() { <add> <add> // Export each defined layer/buffer <add> for (var key in layersSnapshot) { <add> <add> var index = parseInt(key); <add> var layer = layersSnapshot[key]; <add> var canvas = layer.toCanvas(); <add> <add> // Store layer/buffer dimensions <add> var exportLayer = { <add> 'width' : layer.width, <add> 'height' : layer.height <add> }; <add> <add> // Store layer/buffer image data, if it can be generated <add> if (layer.width && layer.height) <add> exportLayer.url = canvas.toDataURL('image/png'); <add> <add> // Add layer properties if not a buffer nor the default layer <add> if (index > 0) { <add> exportLayer.x = layer.x; <add> exportLayer.y = layer.y; <add> exportLayer.z = layer.z; <add> exportLayer.alpha = layer.alpha; <add> exportLayer.matrix = layer.matrix; <add> exportLayer.parent = getLayerIndex(layer.parent); <add> } <add> <add> // Store exported layer <add> state.layers[key] = exportLayer; <add> <ide> } <ide> <del> // Store exported layer <del> state.layers[key] = exportLayer; <del> <del> } <del> <del> return state; <add> // Invoke callback now that the state is ready <add> callback(state); <add> <add> }); <ide> <ide> }; <ide>
JavaScript
mit
a7a1af5e26abcbc67d18603080ea606c3b7fb8d9
0
anyWareSculpture/anyware,anyWareSculpture/anyware
import PanelsActionCreator from '../actions/panels-action-creator'; import SculptureActionCreator from '../actions/sculpture-action-creator'; import SimonGameActionCreator from '../actions/simon-game-action-creator'; import PanelAnimation from '../animation/panel-animation'; import NormalizeStripFrame from '../animation/normalize-strip-frame'; import Frame from '../animation/frame'; import COLORS from '../constants/colors'; /** * Handles both the Colour State (transitions) and the Simon Game Logic */ export default class SimonGameLogic { static STATE_NONE = 'none'; // Initial state static STATE_INTRO = 'intro'; // Intro: Turn on colors and play intro sound static STATE_OFF = 'off'; // In art state, but not playing static STATE_PLAYING = 'playing'; // Normal game play logic static STATE_CALLING = 'calling'; // Call pattern is playing static STATE_FAILING = 'failing'; // Failure state: Sad sound static STATE_WINNING = 'winning'; // Pause before winning game or level static STATE_LEVELWON = 'levelwon'; // Level won: Happy sound static STATE_GAMEWON = 'gamewon'; // Game won: Very happy sound static STATE_COMPLETE = 'complete'; // End of game state: projector color static STATE_DONE = 'done'; // Game done, turn off lights and play exit sound // These are automatically added to the sculpture store static trackedProperties = { level: 0, pattern: 0, targetPanel: null, state: SimonGameLogic.STATE_NONE, user: '', strip0Color: COLORS.BLACK, strip0Intensity: 0, strip1Color: COLORS.BLACK, strip1Intensity: 0, strip2Color: COLORS.BLACK, strip2Intensity: 0, }; /* * The constructor manages transition _into_ the Colour State */ constructor(store, config) { this.store = store; this.config = config; this.gameConfig = this.config.SIMON_GAME; this.initTrackedProperties(); this.simonGameActionCreator = new SimonGameActionCreator(this.store.dispatcher); this.sculptureActionCreator = new SculptureActionCreator(this.store.dispatcher); this._targetSequenceIndex = 0; // Our current position in the sequence this._receivedInput = false; this._inputTimeout = null; this._replayTimeout = null; this._replayCount = 0; } initTrackedProperties() { this.data.set('level', 0); this.data.set('pattern', 0); this.data.set('targetPanel', null); this.data.set('state', SimonGameLogic.STATE_NONE); this.data.set('user', ''); this.data.set('strip0Color', COLORS.BLACK); this.data.set('strip0Intensity', 0); this.data.set('strip1Color', COLORS.BLACK); this.data.set('strip1Intensity', 0); this.data.set('strip2Color', COLORS.BLACK); this.data.set('strip2Intensity', 0); } get data() { return this.store.data.get('simon'); } get lights() { return this.store.data.get('lights'); } /** * Transitions into this game. Calls callback when done. */ transition(callback) { const initFrames = [ new Frame(() => { this.data.set('state', SimonGameLogic.STATE_INTRO); // Activate RGB Strips if (this.gameConfig.RGB_STRIP) { this.lights.setIntensity(this.gameConfig.RGB_STRIP, '0', 100); this.lights.setColor(this.gameConfig.RGB_STRIP, '0', 'rgb0'); this.lights.setIntensity(this.gameConfig.RGB_STRIP, '1', 100); this.lights.setColor(this.gameConfig.RGB_STRIP, '1', 'rgb1'); } }, 0), new Frame(() => { this.data.set('state', SimonGameLogic.STATE_OFF); }, this.config.ART_STATE_SPACE_SECONDS * 1000), ]; this.store.playAnimation(new PanelAnimation(initFrames, callback)); } /** * Start game - only run by master */ start() { this.initTrackedProperties(); this._playCurrentSequence(); } /** * Reset game. Will reset the game to the beginning, without starting the game. * Only master should call this function. */ reset() { console.log(`simon.reset()`); const lights = this.store.data.get('lights'); this._discardInput(); lights.deactivateAll(); this.config.GAME_STRIPS.forEach((id) => lights.setIntensity(id, null, 0)); this.data.set('state', SimonGameLogic.STATE_OFF); this.store.cancelAnimations(); } /** * End game - only run by master */ end() { } /** * Turn off all lights */ turnOffEverything() { this.lights.deactivateAll(); this.config.GAME_STRIPS.forEach((stripId) => this.lights.setIntensity(stripId, null, 0)); if (this.gameConfig.RGB_STRIP) { this.lights.setIntensity(this.gameConfig.RGB_STRIP, null, 0); } } isFreePlayAllowed() { const state = this.data.get('state'); return state === SimonGameLogic.STATE_COMPLETE; } isPlaying() { return this.data.get('state') === SimonGameLogic.STATE_PLAYING; } isWinning() { return this.data.get('state') === SimonGameLogic.STATE_WINNING; } didWinLevel() { return this.data.get('state') === SimonGameLogic.STATE_LEVELWON; } didWinGame() { return this.data.get('state') === SimonGameLogic.STATE_GAMEWON; } // Returns the current strip, or undefined if there isn't a current level getCurrentStrip() { const {stripId} = this.getCurrentLevelData() || {}; return stripId; } handleActionPayload(payload) { const actionHandlers = { [PanelsActionCreator.PANEL_PRESSED]: this._actionPanelPressed.bind(this), [SimonGameActionCreator.REPLAY_SIMON_PATTERN]: this._actionReplaySimonPattern.bind(this), [SimonGameActionCreator.LEVEL_WON]: this._actionLevelWon.bind(this), [SculptureActionCreator.MERGE_STATE]: this._actionMergeState.bind(this), }; const actionHandler = actionHandlers[payload.actionType]; if (actionHandler) { actionHandler(payload); } } // master only _actionReplaySimonPattern() { this._playCurrentSequence(); } _actionPanelPressed(payload) { if (this.store.iAmAlone() || !this.store.isReady) return; console.log(`_actionPanelPressed(${JSON.stringify(payload)})`); const {stripId, panelId, pressed} = payload; this.lights.setActive(stripId, panelId, pressed); // // Handle free play // if (this.isFreePlayAllowed()) { if (pressed) { this.lights.setColor(stripId, panelId, this.store.locationColor); this.lights.setIntensity(stripId, panelId, this.config.PANEL_DEFAULTS.ACTIVE_INTENSITY); } else { this.lights.setColor(stripId, panelId, this.data.get(`strip${stripId}Color`)); this.lights.setIntensity(stripId, panelId, this.data.get(`strip${stripId}Intensity`)); } } // From here on only handle the PLAYING state if (!this.isPlaying()) return; // // Handle current strip actions // if (stripId !== this.getCurrentStrip()) return; // Ignore non-owner interactions if (this.hasUser() && this.getUser() !== this.store.me) return; // Ignore one-off touches if (!this.hasUser() || this.getUser() === this.store.me) { if (panelId !== this.getTargetPanel() && this._shouldBeIgnored(panelId)) { return; } } if (pressed) { // Owner presses on current strip -> use location color this.lights.setColor(stripId, panelId, this.store.locationColor); this.lights.setIntensity(stripId, panelId, this.config.PANEL_DEFAULTS.ACTIVE_INTENSITY); // Master owns the 'user' field only if it has been set if (!this.hasUser()) { this.setUser(this.store.me); this._setOwnerColor(stripId); } // Master owns all other fields if (this.store.isMaster()) this._handlePanelPress(stripId, panelId); } } _resetColor(stripId, panelId) { const {stripId: targetStripId, panelSequences} = this.getCurrentLevelData(); const panelSequence = panelSequences[this.getPattern()]; const panelIdx = panelSequence.indexOf(panelId); if (panelIdx < 0) { if (this.hasUser()) { this.lights.setColor(stripId, panelId, this.config.getLocationColor(this.getUser())); this.lights.setIntensity(stripId, panelId, this.gameConfig.INDICATOR_PANEL_INTENSITY); } else { this.lights.setColor(stripId, panelId, this.gameConfig.DEFAULT_SIMON_PANEL_COLOR); this.lights.setIntensity(stripId, panelId, 0); } } else { const targetSequenceIndex = panelSequence.indexOf(this.getTargetPanel()); let color; if (panelIdx >= targetSequenceIndex) { color = this.gameConfig.DEFAULT_SIMON_PANEL_COLOR; } else { color = this.config.getLocationColor(this.getUser()); } this.lights.setColor(stripId, panelId, color); this.lights.setIntensity(stripId, panelId, this.gameConfig.TARGET_PANEL_INTENSITY); } } /** * This is a bit of a hack; it checks if the given panel has a color corresponding to the location color * of the owner of this strip. */ _isOwner(stripId, panelId) { const user = this.getUser(); const color = this.lights.getColor(stripId, panelId); const intensity = this.lights.getIntensity(stripId, panelId); return color === this.config.getLocationColor(user) && intensity === this.config.PANEL_DEFAULTS.ACTIVE_INTENSITY; } /** * Handle panel press (locally or through merge) - master only */ _handlePanelPress(stripId, panelId) { console.log(`_handlePanelPress(${stripId}, ${panelId})`); const {stripId: targetStripId, panelSequences} = this.getCurrentLevelData(); // Only handle current game strips from here on if (targetStripId !== stripId) return; // If the press was not performed by the owner, this is a no-op if (!this._isOwner(stripId, panelId)) return; if (!this._receivedInput) { this._replayCount = 0; this._receivedInput = true; clearTimeout(this._replayTimeout); this._replayTimeout = null; } const panelSequence = panelSequences[this.getPattern()]; if (this.getTargetPanel() !== panelId) { // Ignore touches on already solved panels if ([...Array(this._targetSequenceIndex).keys()].some((idx) => panelId === panelSequence[idx])) { return; } // Ignore one-off touches if (this._shouldBeIgnored(panelId)) { return; } return this._handleFailure(); } this._resetInputTimer(); this._targetSequenceIndex += 1; if (this._targetSequenceIndex >= panelSequence.length) { // FIXME: If we hit the last panel multiple times before the first animation frame is triggered, // we may call trigger _actionLevelWinning() multiple times, restarting the animation. // This may be harmless, but would be nice to fix. this._actionLevelWinning(); } else { this.setTargetPanel(panelSequence[this._targetSequenceIndex]); } } _handleFailure() { console.log(`_handleFailure()`); clearTimeout(this._replayTimeout); this._replayTimeout = null; clearTimeout(this._inputTimeout); this._inputTimeout = null; const failureFrames = [ new Frame(() => { this.data.set('state', SimonGameLogic.STATE_FAILING); }, 0), new Frame(() => { this._playCurrentSequence(); }, 2000), ]; const failureAnimation = new PanelAnimation(failureFrames); this.store.playAnimation(failureAnimation); } /*! * Remote action */ _actionMergeState(payload) { if (payload.simon) this._mergeSimon(payload.simon, payload.metadata.props.simon); if (payload.lights) this._mergeLights(payload.lights, payload.metadata.props.lights); } _mergeFields(fieldNames, changes, props) { for (const fieldName of fieldNames) { if (changes.hasOwnProperty(fieldName)) { this.data.set(fieldName, changes[fieldName], props[fieldName]); } } } _mergeSimon(simonChanges, props) { // Master owns all local fields, except user if it hasn't been set if (!this.store.isMaster()) { this._mergeFields([ 'level', 'pattern', 'targetPanel', 'state', 'strip0Color', 'strip0Intensity', 'strip1Color', 'strip1Intensity', 'strip2Color', 'strip2Intensity'], simonChanges, props); } if (simonChanges.hasOwnProperty('user')) { if (!this.store.isMaster() || !this.hasUser()) { this.setUser(simonChanges.user, props.user); } } } _mergeLights(lightsChanges, props) { // Master is responsible for merging panel actions if (!this.store.isMaster()) return; for (const stripId of Object.keys(lightsChanges)) { const changedPanels = lightsChanges[stripId].panels; for (const panelId of Object.keys(changedPanels)) { const changedPanel = changedPanels[panelId]; const panelProps = props[stripId].panels[panelId]; const panel = this.lights.getPanel(stripId, panelId); // Note: Checking for existing active state allows touches while an opponent // is holding a panel, so an owner doesn't get locked out if (this.lights.isActive(stripId, panelId)) { console.log(changedPanel); console.log(panel._changes); // Simon-specific merge on panel activity changes console.log(`should handlePanelPress(${stripId}, ${panelId})`); if (!this.isPlaying() || !this.store.isReady) return; this._handlePanelPress(stripId, panelId); } } } } _resetInputTimer() { clearTimeout(this._inputTimeout); const level = this.getLevel(); this._inputTimeout = setTimeout(() => { if (this.isPlaying() && this.getLevel() === level) { this._handleFailure(); } }, this.gameConfig.INPUT_TIMEOUT); } // master only _discardInput() { this._targetSequenceIndex = 0; this.setTargetPanel(null); this._receivedInput = false; clearTimeout(this._inputTimeout); this._inputTimeout = null; } /** * Add a short timeout between hitting the last panel and the success sound * Master only. */ _actionLevelWinning() { this.data.set('state', SimonGameLogic.STATE_WINNING); setTimeout(() => this.simonGameActionCreator.sendLevelWon(), 1000); } /** * Master only */ _actionLevelWon() { const stripId = this.getCurrentLevelData().stripId; // Set UI indicators to location color const winningUser = this.getUser(); const winningColor = this.config.getLocationColor(winningUser); console.log(`_actionLevelWon(): stripId=${stripId}, winningUser=${winningUser}`); this.lights.deactivateAll(stripId); this.lights.setIntensity(stripId, null, 50); this.lights.setColor(stripId, null, winningColor); this.data.set(`strip${stripId}Color`, winningColor); this.data.set(`strip${stripId}Intensity`, 50); this.clearUser(); const level = this.getLevel() + 1; if (level >= this.getNumLevels()) { this.data.set('state', SimonGameLogic.STATE_GAMEWON); } else { this.data.set('state', SimonGameLogic.STATE_LEVELWON); } this.setLevel(level); this.setPattern(0); // Make sure changes are merged by all slaves this.store.reassertChanges(); this._playTransition(); } _playTransition() { const successFrames = [ new Frame(() => { this._playCurrentSequence(); }, 3000), ]; const transitionFrames = [ new Frame(() => { this.data.set('state', SimonGameLogic.STATE_COMPLETE); }, 3000), new Frame(() => { this.turnOffEverything(); this.data.set('state', SimonGameLogic.STATE_DONE); setTimeout(() => this.sculptureActionCreator.sendStartNextGame(), this.config.SPACE_BETWEEN_GAMES_SECONDS * 1000); }, this.gameConfig.FREEPLAY_TIMEOUT), ]; this.store.playAnimation(new PanelAnimation(this.didWinGame() ? transitionFrames : successFrames)); } // master only _playCurrentSequence() { this.clearUser(); this._replayCount += 1; if (this._replayCount > 3) { this.setPattern((this.getPattern() + 1) % this.getNumPatterns()); this._replayCount = 0; } const {stripId, panelSequences, frameDelay} = this.getCurrentLevelData(); const panelSequence = panelSequences[this.getPattern()]; this.data.set('state', SimonGameLogic.STATE_CALLING); this._playSequence(stripId, panelSequence, frameDelay); this.setTargetPanel(panelSequence[this._targetSequenceIndex]); } // master only _playSequence(stripId, panelSequence, frameDelay) { this._discardInput(); const delay = frameDelay !== undefined ? frameDelay : this.gameConfig.SEQUENCE_ANIMATION_FRAME_DELAY; const sequenceFrames = [].concat(...panelSequence.map((panelId) => { return [ new Frame(() => { this.lights.setIntensity(stripId, panelId, this.gameConfig.TARGET_PANEL_INTENSITY); this.lights.setColor(stripId, panelId, this.gameConfig.DEFAULT_SIMON_PANEL_COLOR); }, delay-500), new Frame(() => { this.lights.setIntensity(stripId, panelId, 0); }, 500) ]; })); const frames = [ new NormalizeStripFrame(this.lights, stripId, this.gameConfig.DEFAULT_SIMON_PANEL_COLOR, 0), ...sequenceFrames, new Frame(() => { panelSequence.forEach((panelId) => { this.lights.setIntensity(stripId, panelId, this.gameConfig.TARGET_PANEL_INTENSITY - 1); }); }, 2 * delay), ]; const animation = new PanelAnimation(frames, this._finishPlaySequence.bind(this)); this.store.playAnimation(animation); } // master only _finishPlaySequence() { clearTimeout(this._replayTimeout); this.data.set('state', SimonGameLogic.STATE_PLAYING); const level = this.getLevel(); this._replayTimeout = setTimeout(() => { if (this.isPlaying() && this.getLevel() === level) { this.simonGameActionCreator.sendReplaySimonPattern(); } }, this.gameConfig.DELAY_BETWEEN_PLAYS); } getCurrentLevelData() { return this.gameConfig.PATTERN_LEVELS[this.getLevel()]; } getNumLevels() { return this.gameConfig.PATTERN_LEVELS.length; } getLevel() { return this.data.get('level'); } setLevel(value) { this.store.reassertChanges(); // Make sure changes are merged by all slaves return this.data.set('level', value); } getNumPatterns() { return this.gameConfig.PATTERN_LEVELS[this.getLevel()].panelSequences.length; } // Get the pattern index (index into the panelSequences array) getPattern() { return this.data.get('pattern'); } // Set the pattern index (index into the panelSequences array) setPattern(pattern) { this.store.reassertChanges(); // Make sure changes are merged by all slaves return this.data.set('pattern', pattern); } getTargetPanel() { return this.data.get('targetPanel'); } setTargetPanel(value) { this.store.reassertChanges(); // Make sure changes are merged by all slaves return this.data.set('targetPanel', value); } /** * Make all "off" panels the owner color */ _setOwnerColor(stripId) { for (let panelId=0;panelId<10;panelId++) { if (this.lights.getIntensity(stripId, `${panelId}`) === 0) { this.lights.setColor(stripId, `${panelId}`, this.store.locationColor); this.lights.setIntensity(stripId, `${panelId}`, this.gameConfig.INDICATOR_PANEL_INTENSITY); } } } _shouldBeIgnored(panelId) { if (this.isWinning() || this.didWinLevel() || this.didWinGame()) return true; const {panelSequences} = this.getCurrentLevelData(); const panelSequence = panelSequences[this.getPattern()]; const targetSequenceIndex = panelSequence.indexOf(this.getTargetPanel()); const ignores = [this.getTargetPanel()]; if (targetSequenceIndex > 0) ignores.push(panelSequence[targetSequenceIndex-1]); if (ignores.some((ignoredPanelId) => Math.abs(panelId - ignoredPanelId) === 1)) return true; return false; } setUser(user, props) { return this.data.set('user', user, props); } getUser() { return this.data.get('user'); } hasUser() { return this.getUser() !== ''; } clearUser() { return this.setUser(''); } }
src/game-logic/logic/simon-game-logic.js
import PanelsActionCreator from '../actions/panels-action-creator'; import SculptureActionCreator from '../actions/sculpture-action-creator'; import SimonGameActionCreator from '../actions/simon-game-action-creator'; import PanelAnimation from '../animation/panel-animation'; import NormalizeStripFrame from '../animation/normalize-strip-frame'; import Frame from '../animation/frame'; import COLORS from '../constants/colors'; /** * Handles both the Colour State (transitions) and the Simon Game Logic */ export default class SimonGameLogic { static STATE_NONE = 'none'; // Initial state static STATE_INTRO = 'intro'; // Intro: Turn on colors and play intro sound static STATE_OFF = 'off'; // In art state, but not playing static STATE_PLAYING = 'playing'; // Normal game play logic static STATE_CALLING = 'calling'; // Call pattern is playing static STATE_FAILING = 'failing'; // Failure state: Sad sound static STATE_WINNING = 'winning'; // Pause before winning game or level static STATE_LEVELWON = 'levelwon'; // Level won: Happy sound static STATE_GAMEWON = 'gamewon'; // Game won: Very happy sound static STATE_COMPLETE = 'complete'; // End of game state: projector color static STATE_DONE = 'done'; // Game done, turn off lights and play exit sound // These are automatically added to the sculpture store static trackedProperties = { level: 0, pattern: 0, targetPanel: null, state: SimonGameLogic.STATE_NONE, user: '', strip0Color: COLORS.BLACK, strip0Intensity: 0, strip1Color: COLORS.BLACK, strip1Intensity: 0, strip2Color: COLORS.BLACK, strip2Intensity: 0, }; /* * The constructor manages transition _into_ the Colour State */ constructor(store, config) { this.store = store; this.config = config; this.gameConfig = this.config.SIMON_GAME; this.initTrackedProperties(); this.simonGameActionCreator = new SimonGameActionCreator(this.store.dispatcher); this.sculptureActionCreator = new SculptureActionCreator(this.store.dispatcher); this._targetSequenceIndex = 0; // Our current position in the sequence this._receivedInput = false; this._inputTimeout = null; this._replayTimeout = null; this._replayCount = 0; } initTrackedProperties() { this.data.set('level', 0); this.data.set('pattern', 0); this.data.set('targetPanel', null); this.data.set('state', SimonGameLogic.STATE_NONE); this.data.set('user', ''); this.data.set('strip0Color', COLORS.BLACK); this.data.set('strip0Intensity', 0); this.data.set('strip1Color', COLORS.BLACK); this.data.set('strip1Intensity', 0); this.data.set('strip2Color', COLORS.BLACK); this.data.set('strip2Intensity', 0); } get data() { return this.store.data.get('simon'); } get lights() { return this.store.data.get('lights'); } /** * Transitions into this game. Calls callback when done. */ transition(callback) { const initFrames = [ new Frame(() => { this.data.set('state', SimonGameLogic.STATE_INTRO); // Activate RGB Strips if (this.gameConfig.RGB_STRIP) { this.lights.setIntensity(this.gameConfig.RGB_STRIP, '0', 100); this.lights.setColor(this.gameConfig.RGB_STRIP, '0', 'rgb0'); this.lights.setIntensity(this.gameConfig.RGB_STRIP, '1', 100); this.lights.setColor(this.gameConfig.RGB_STRIP, '1', 'rgb1'); } }, 0), new Frame(() => { this.data.set('state', SimonGameLogic.STATE_OFF); }, this.config.ART_STATE_SPACE_SECONDS * 1000), ]; this.store.playAnimation(new PanelAnimation(initFrames, callback)); } /** * Start game - only run by master */ start() { this.initTrackedProperties(); this._playCurrentSequence(); } /** * Reset game. Will reset the game to the beginning, without starting the game. * Only master should call this function. */ reset() { console.log(`simon.reset()`); const lights = this.store.data.get('lights'); this._discardInput(); lights.deactivateAll(); this.config.GAME_STRIPS.forEach((id) => lights.setIntensity(id, null, 0)); this.data.set('state', SimonGameLogic.STATE_OFF); this.store.cancelAnimations(); } /** * End game - only run by master */ end() { } /** * Turn off all lights */ turnOffEverything() { this.lights.deactivateAll(); this.config.GAME_STRIPS.forEach((stripId) => this.lights.setIntensity(stripId, null, 0)); if (this.gameConfig.RGB_STRIP) { this.lights.setIntensity(this.gameConfig.RGB_STRIP, null, 0); } } isFreePlayAllowed() { const state = this.data.get('state'); return state === SimonGameLogic.STATE_COMPLETE; } isPlaying() { return this.data.get('state') === SimonGameLogic.STATE_PLAYING; } isWinning() { return this.data.get('state') === SimonGameLogic.STATE_WINNING; } didWinLevel() { return this.data.get('state') === SimonGameLogic.STATE_LEVELWON; } didWinGame() { return this.data.get('state') === SimonGameLogic.STATE_GAMEWON; } // Returns the current strip, or undefined if there isn't a current level getCurrentStrip() { const {stripId} = this.getCurrentLevelData() || {}; return stripId; } handleActionPayload(payload) { const actionHandlers = { [PanelsActionCreator.PANEL_PRESSED]: this._actionPanelPressed.bind(this), [SimonGameActionCreator.REPLAY_SIMON_PATTERN]: this._actionReplaySimonPattern.bind(this), [SimonGameActionCreator.LEVEL_WON]: this._actionLevelWon.bind(this), [SculptureActionCreator.MERGE_STATE]: this._actionMergeState.bind(this), }; const actionHandler = actionHandlers[payload.actionType]; if (actionHandler) { actionHandler(payload); } } // master only _actionReplaySimonPattern() { this._playCurrentSequence(); } _actionPanelPressed(payload) { if (this.store.iAmAlone() || !this.store.isReady) return; console.log(`_actionPanelPressed(${JSON.stringify(payload)})`); const {stripId, panelId, pressed} = payload; this.lights.setActive(stripId, panelId, pressed); // // Handle free play // if (this.isFreePlayAllowed()) { if (pressed) { this.lights.setColor(stripId, panelId, this.store.locationColor); this.lights.setIntensity(stripId, panelId, this.config.PANEL_DEFAULTS.ACTIVE_INTENSITY); } else { this.lights.setColor(stripId, panelId, this.data.get(`strip${stripId}Color`)); this.lights.setIntensity(stripId, panelId, this.data.get(`strip${stripId}Intensity`)); } } // From here on only handle the PLAYING state if (!this.isPlaying()) return; // // Handle current strip actions // if (stripId !== this.getCurrentStrip()) return; // Ignore non-owner interactions if (this.hasUser() && this.getUser() !== this.store.me) return; // Ignore one-off touches if (!this.hasUser() || this.getUser() === this.store.me) { if (panelId !== this.getTargetPanel() && this._shouldBeIgnored(panelId)) { return; } } if (pressed) { // Owner presses on current strip -> use location color this.lights.setColor(stripId, panelId, this.store.locationColor); this.lights.setIntensity(stripId, panelId, this.config.PANEL_DEFAULTS.ACTIVE_INTENSITY); // Master owns the 'user' field only if it has been set if (!this.hasUser()) { this.setUser(this.store.me); this._setOwnerColor(stripId); } // Master owns all other fields if (this.store.isMaster()) this._handlePanelPress(stripId, panelId); } } _resetColor(stripId, panelId) { const {stripId: targetStripId, panelSequences} = this.getCurrentLevelData(); const panelSequence = panelSequences[this.getPattern()]; const panelIdx = panelSequence.indexOf(panelId); if (panelIdx < 0) { if (this.hasUser()) { this.lights.setColor(stripId, panelId, this.config.getLocationColor(this.getUser())); this.lights.setIntensity(stripId, panelId, this.gameConfig.INDICATOR_PANEL_INTENSITY); } else { this.lights.setColor(stripId, panelId, this.gameConfig.DEFAULT_SIMON_PANEL_COLOR); this.lights.setIntensity(stripId, panelId, 0); } } else { const targetSequenceIndex = panelSequence.indexOf(this.getTargetPanel()); let color; if (panelIdx >= targetSequenceIndex) { color = this.gameConfig.DEFAULT_SIMON_PANEL_COLOR; } else { color = this.config.getLocationColor(this.getUser()); } this.lights.setColor(stripId, panelId, color); this.lights.setIntensity(stripId, panelId, this.gameConfig.TARGET_PANEL_INTENSITY); } } /** * This is a bit of a hack; it checks if the given panel has a color corresponding to the location color * of the owner of this strip. */ _isOwner(stripId, panelId) { const user = this.getUser(); const color = this.lights.getColor(stripId, panelId); const intensity = this.lights.getIntensity(stripId, panelId); return color === this.config.getLocationColor(user) && intensity === this.config.PANEL_DEFAULTS.ACTIVE_INTENSITY; } /** * Handle panel press (locally or through merge) - master only */ _handlePanelPress(stripId, panelId) { console.log(`_handlePanelPress(${stripId}, ${panelId})`); const {stripId: targetStripId, panelSequences} = this.getCurrentLevelData(); // Only handle current game strips from here on if (targetStripId !== stripId) return; // If the press was not performed by the owner, this is a no-op if (!this._isOwner(stripId, panelId)) return; if (!this._receivedInput) { this._replayCount = 0; this._receivedInput = true; clearTimeout(this._replayTimeout); this._replayTimeout = null; } const panelSequence = panelSequences[this.getPattern()]; if (this.getTargetPanel() !== panelId) { // Ignore touches on already solved panels if ([...Array(this._targetSequenceIndex).keys()].some((idx) => panelId === panelSequence[idx])) { return; } // Ignore one-off touches if (this._shouldBeIgnored(panelId)) { return; } return this._handleFailure(); } this._resetInputTimer(); this._targetSequenceIndex += 1; if (this._targetSequenceIndex >= panelSequence.length) { // FIXME: If we hit the last panel multiple times before the first animation frame is triggered, // we may call trigger _actionLevelWinning() multiple times, restarting the animation. // This may be harmless, but would be nice to fix. this._actionLevelWinning(); } else { this.setTargetPanel(panelSequence[this._targetSequenceIndex]); } } _handleFailure() { console.log(`_handleFailure()`); clearTimeout(this._replayTimeout); this._replayTimeout = null; clearTimeout(this._inputTimeout); this._inputTimeout = null; const failureFrames = [ new Frame(() => { this.data.set('state', SimonGameLogic.STATE_FAILING); }, 0), new Frame(() => { this._playCurrentSequence(); }, 2000), ]; const failureAnimation = new PanelAnimation(failureFrames); this.store.playAnimation(failureAnimation); } /*! * Remote action */ _actionMergeState(payload) { if (payload.simon) this._mergeSimon(payload.simon, payload.metadata.props.simon); if (payload.lights) this._mergeLights(payload.lights, payload.metadata.props.lights); } _mergeFields(fieldNames, changes, props) { for (const fieldName of fieldNames) { if (changes.hasOwnProperty(fieldName)) { this.data.set(fieldName, changes[fieldName], props[fieldName]); } } } _mergeSimon(simonChanges, props) { // Master owns all local fields, except user if it hasn't been set if (!this.store.isMaster()) { this._mergeFields([ 'level', 'pattern', 'targetPanel', 'state', 'strip0Color', 'strip0Intensity', 'strip1Color', 'strip1Intensity', 'strip2Color', 'strip2Intensity'], simonChanges, props); } if (simonChanges.hasOwnProperty('user')) { if (!this.store.isMaster() || !this.hasUser()) { this.setUser(simonChanges.user, props.user); } } } _mergeLights(lightsChanges, props) { // Master is responsible for merging panel actions if (!this.store.isMaster()) return; for (const stripId of Object.keys(lightsChanges)) { const changedPanels = lightsChanges[stripId].panels; for (const panelId of Object.keys(changedPanels)) { const changedPanel = changedPanels[panelId]; const panelProps = props[stripId].panels[panelId]; const panel = this.lights.getPanel(stripId, panelId); // Note: Checking for existing active state allows touches while an opponent // is holding a panel, so an owner doesn't get locked out if (this.lights.isActive(stripId, panelId)) { console.log(changedPanel); console.log(panel._changes); // Simon-specific merge on panel activity changes console.log(`should handlePanelPress(${stripId}, ${panelId})`); if (!this.isPlaying() || !this.store.isReady) return; this._handlePanelPress(stripId, panelId); } } } } _resetInputTimer() { clearTimeout(this._inputTimeout); const level = this.getLevel(); this._inputTimeout = setTimeout(() => { if (this.isPlaying() && this.getLevel() === level) { this._handleFailure(); } }, this.gameConfig.INPUT_TIMEOUT); } // master only _discardInput() { this._targetSequenceIndex = 0; this.setTargetPanel(null); this._receivedInput = false; clearTimeout(this._inputTimeout); this._inputTimeout = null; } /** * Add a short timeout between hitting the last panel and the success sound * Master only. */ _actionLevelWinning() { this.data.set('state', SimonGameLogic.STATE_WINNING); setTimeout(() => this.simonGameActionCreator.sendLevelWon(), 1000); } /** * Master only */ _actionLevelWon() { const stripId = this.getCurrentLevelData().stripId; // Set UI indicators to location color const winningUser = this.getUser(); const winningColor = this.config.getLocationColor(winningUser); console.log(`_actionLevelWon(): stripId=${stripId}, winningUser=${winningUser}`); this.lights.deactivateAll(stripId); this.lights.setIntensity(stripId, null, 50); this.lights.setColor(stripId, null, winningColor); this.data.set(`strip${stripId}Color`, winningColor); this.data.set(`strip${stripId}Intensity`, 50); this.clearUser(); const level = this.getLevel() + 1; if (level >= this.getNumLevels()) { this.data.set('state', SimonGameLogic.STATE_GAMEWON); } else { this.data.set('state', SimonGameLogic.STATE_LEVELWON); } this.setLevel(level); this.setPattern(0); // Make sure changes are merged by all slaves this.store.reassertChanges(); this._playTransition(); } _playTransition() { const successFrames = [ new Frame(() => { this._playCurrentSequence(); }, 3000), ]; const transitionFrames = [ new Frame(() => { this.data.set('state', SimonGameLogic.STATE_COMPLETE); }, 3000), new Frame(() => { this.turnOffEverything(); this.data.set('state', SimonGameLogic.STATE_DONE); setTimeout(() => this.sculptureActionCreator.sendStartNextGame(), this.config.SPACE_BETWEEN_GAMES_SECONDS * 1000); }, this.gameConfig.FREEPLAY_TIMEOUT), ]; this.store.playAnimation(new PanelAnimation(this.didWinGame() ? transitionFrames : successFrames)); } // master only _playCurrentSequence() { this.clearUser(); const {stripId, panelSequences, frameDelay} = this.getCurrentLevelData(); const panelSequence = panelSequences[this.getPattern()]; this.data.set('state', SimonGameLogic.STATE_CALLING); this._playSequence(stripId, panelSequence, frameDelay); this.setTargetPanel(panelSequence[this._targetSequenceIndex]); } // master only _playSequence(stripId, panelSequence, frameDelay) { this._discardInput(); const delay = frameDelay !== undefined ? frameDelay : this.gameConfig.SEQUENCE_ANIMATION_FRAME_DELAY; const sequenceFrames = [].concat(...panelSequence.map((panelId) => { return [ new Frame(() => { this.lights.setIntensity(stripId, panelId, this.gameConfig.TARGET_PANEL_INTENSITY); this.lights.setColor(stripId, panelId, this.gameConfig.DEFAULT_SIMON_PANEL_COLOR); }, delay-500), new Frame(() => { this.lights.setIntensity(stripId, panelId, 0); }, 500) ]; })); const frames = [ new NormalizeStripFrame(this.lights, stripId, this.gameConfig.DEFAULT_SIMON_PANEL_COLOR, 0), ...sequenceFrames, new Frame(() => { panelSequence.forEach((panelId) => { this.lights.setIntensity(stripId, panelId, this.gameConfig.TARGET_PANEL_INTENSITY - 1); }); }, 2 * delay), ]; const animation = new PanelAnimation(frames, this._finishPlaySequence.bind(this)); this.store.playAnimation(animation); } // master only _finishPlaySequence() { clearTimeout(this._replayTimeout); this._replayCount += 1; if (this._replayCount >= 3) { this.setPattern((this.getPattern() + 1) % this.getNumPatterns()); this._replayCount = 0; } this.data.set('state', SimonGameLogic.STATE_PLAYING); const level = this.getLevel(); this._replayTimeout = setTimeout(() => { if (this.isPlaying() && this.getLevel() === level) { this.simonGameActionCreator.sendReplaySimonPattern(); } }, this.gameConfig.DELAY_BETWEEN_PLAYS); } getCurrentLevelData() { return this.gameConfig.PATTERN_LEVELS[this.getLevel()]; } getNumLevels() { return this.gameConfig.PATTERN_LEVELS.length; } getLevel() { return this.data.get('level'); } setLevel(value) { this.store.reassertChanges(); // Make sure changes are merged by all slaves return this.data.set('level', value); } getNumPatterns() { return this.gameConfig.PATTERN_LEVELS[this.getLevel()].panelSequences.length; } // Get the pattern index (index into the panelSequences array) getPattern() { return this.data.get('pattern'); } // Set the pattern index (index into the panelSequences array) setPattern(pattern) { this.store.reassertChanges(); // Make sure changes are merged by all slaves return this.data.set('pattern', pattern); } getTargetPanel() { return this.data.get('targetPanel'); } setTargetPanel(value) { this.store.reassertChanges(); // Make sure changes are merged by all slaves return this.data.set('targetPanel', value); } /** * Make all "off" panels the owner color */ _setOwnerColor(stripId) { for (let panelId=0;panelId<10;panelId++) { if (this.lights.getIntensity(stripId, `${panelId}`) === 0) { this.lights.setColor(stripId, `${panelId}`, this.store.locationColor); this.lights.setIntensity(stripId, `${panelId}`, this.gameConfig.INDICATOR_PANEL_INTENSITY); } } } _shouldBeIgnored(panelId) { if (this.isWinning() || this.didWinLevel() || this.didWinGame()) return true; const {panelSequences} = this.getCurrentLevelData(); const panelSequence = panelSequences[this.getPattern()]; const targetSequenceIndex = panelSequence.indexOf(this.getTargetPanel()); const ignores = [this.getTargetPanel()]; if (targetSequenceIndex > 0) ignores.push(panelSequence[targetSequenceIndex-1]); if (ignores.some((ignoredPanelId) => Math.abs(panelId - ignoredPanelId) === 1)) return true; return false; } setUser(user, props) { return this.data.set('user', user, props); } getUser() { return this.data.get('user'); } hasUser() { return this.getUser() !== ''; } clearUser() { return this.setUser(''); } }
Bugfix: Correct simon game play failed on the 3rd pattern repetition
src/game-logic/logic/simon-game-logic.js
Bugfix: Correct simon game play failed on the 3rd pattern repetition
<ide><path>rc/game-logic/logic/simon-game-logic.js <ide> // master only <ide> _playCurrentSequence() { <ide> this.clearUser(); <add> <add> this._replayCount += 1; <add> if (this._replayCount > 3) { <add> this.setPattern((this.getPattern() + 1) % this.getNumPatterns()); <add> this._replayCount = 0; <add> } <add> <ide> const {stripId, panelSequences, frameDelay} = this.getCurrentLevelData(); <ide> const panelSequence = panelSequences[this.getPattern()]; <ide> <ide> // master only <ide> _finishPlaySequence() { <ide> clearTimeout(this._replayTimeout); <del> this._replayCount += 1; <del> if (this._replayCount >= 3) { <del> this.setPattern((this.getPattern() + 1) % this.getNumPatterns()); <del> this._replayCount = 0; <del> } <ide> <ide> this.data.set('state', SimonGameLogic.STATE_PLAYING); <ide> const level = this.getLevel();
Java
apache-2.0
01230139d3606ddc79d7d7c68996ce38a282648d
0
ham1/jmeter,ham1/jmeter,etnetera/jmeter,ham1/jmeter,apache/jmeter,ham1/jmeter,etnetera/jmeter,ham1/jmeter,benbenw/jmeter,apache/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,etnetera/jmeter,benbenw/jmeter,apache/jmeter,benbenw/jmeter,apache/jmeter,etnetera/jmeter
/* * 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.jmeter.gui.util; import java.awt.AWTEvent; import java.awt.Component; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.Serializable; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.JCheckBox; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.metal.MetalLookAndFeel; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.NullProperty; /** * derived from: http://www.javaspecialists.eu/archive/Issue145.html */ public final class TristateCheckBox extends JCheckBox { private static final long serialVersionUID = 1L; // Listener on model changes to maintain correct focusability private final class TSCBChangeListener implements ChangeListener, Serializable { /** * */ private static final long serialVersionUID = -3718373200229708535L; @Override public void stateChanged(ChangeEvent e) { TristateCheckBox.this.setFocusable( getModel().isEnabled()); } } private final ChangeListener enableListener = new TSCBChangeListener(); public TristateCheckBox() { this(null, null, TristateState.DESELECTED); } public TristateCheckBox(String text) { this(text, null, TristateState.DESELECTED); } public TristateCheckBox(String text, boolean selected) { this(text, null, selected ? TristateState.SELECTED : TristateState.DESELECTED); } public TristateCheckBox(String text, Icon icon, TristateState initial) { this(text, icon, initial, false); } // For testing only at present TristateCheckBox(String text, Icon icon, TristateState initial, boolean original) { super(text, icon); //Set default single model setModel(new TristateButtonModel(initial, this, original)); // override action behaviour super.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { TristateCheckBox.this.iterateState(); } }); ActionMap actions = new ActionMapUIResource(); actions.put("pressed", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { TristateCheckBox.this.iterateState(); } }); actions.put("released", null); SwingUtilities.replaceUIActionMap(this, actions); } /** * Set state depending on property * @param element TestElement * @param propName String property name */ public void setTristateFromProperty(TestElement element,String propName) { JMeterProperty jmp = element.getProperty(propName); if (jmp instanceof NullProperty) { this.setIndeterminate(); } else { this.setSelected(jmp.getBooleanValue()); } } /** * Sets a boolean property from a tristate checkbox. * * @param element the test element * @param propName the property name */ public void setPropertyFromTristate(TestElement element, String propName) { if (isIndeterminate()) { element.removeProperty(propName); } else { element.setProperty(propName, isSelected()); } } // Next two methods implement new API by delegation to model public void setIndeterminate() { getTristateModel().setIndeterminate(); } public boolean isIndeterminate() { return getTristateModel().isIndeterminate(); } public TristateState getState() { return getTristateModel().getState(); } //Overrides superclass method @Override public void setModel(ButtonModel newModel) { super.setModel(newModel); //Listen for enable changes if (model instanceof TristateButtonModel) { model.addChangeListener(enableListener); } } //Empty override of superclass method @Override public synchronized void addMouseListener(MouseListener l) { } // Mostly delegates to model private void iterateState() { //Maybe do nothing at all? if (!getModel().isEnabled()) { return; } grabFocus(); // Iterate state getTristateModel().iterateState(); // Fire ActionEvent int modifiers = 0; AWTEvent currentEvent = EventQueue.getCurrentEvent(); if (currentEvent instanceof InputEvent) { modifiers = ((InputEvent) currentEvent).getModifiers(); } else if (currentEvent instanceof ActionEvent) { modifiers = ((ActionEvent) currentEvent).getModifiers(); } fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getText(), System.currentTimeMillis(), modifiers)); } //Convenience cast public TristateButtonModel getTristateModel() { return (TristateButtonModel) super.getModel(); } private static class TristateButtonModel extends ToggleButtonModel { private static final long serialVersionUID = 1L; private TristateState state = TristateState.DESELECTED; private final TristateCheckBox tristateCheckBox; private final Icon icon; private final boolean original; public TristateButtonModel(TristateState initial, TristateCheckBox tristateCheckBox, boolean original) { setState(TristateState.DESELECTED); this.tristateCheckBox = tristateCheckBox; icon = new TristateCheckBoxIcon(); this.original = original; } public void setIndeterminate() { setState(TristateState.INDETERMINATE); } public boolean isIndeterminate() { return state == TristateState.INDETERMINATE; } // Overrides of superclass methods @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); // Restore state display displayState(); } @Override public void setSelected(boolean selected) { setState(selected ? TristateState.SELECTED : TristateState.DESELECTED); } // Empty overrides of superclass methods @Override public void setArmed(boolean b) { } @Override public void setPressed(boolean b) { } void iterateState() { setState(state.next()); } private void setState(TristateState state) { //Set internal state this.state = state; displayState(); if (state == TristateState.INDETERMINATE && isEnabled()) { // force the events to fire // Send ChangeEvent fireStateChanged(); // Send ItemEvent int indeterminate = 3; fireItemStateChanged(new ItemEvent( this, ItemEvent.ITEM_STATE_CHANGED, this, indeterminate)); } } private void displayState() { super.setSelected(state != TristateState.DESELECTED); if (original) { super.setArmed(state == TristateState.INDETERMINATE); } else { if (state == TristateState.INDETERMINATE) { tristateCheckBox.setIcon(icon); // Needed for all but Nimbus tristateCheckBox.setSelectedIcon(icon); // Nimbus works - after a fashion - with this tristateCheckBox.setDisabledSelectedIcon(icon); // Nimbus works - after a fashion - with this } else { // reset if (tristateCheckBox!= null){ tristateCheckBox.setIcon(null); tristateCheckBox.setSelectedIcon(null); tristateCheckBox.setDisabledSelectedIcon(null); // Nimbus works - after a fashion - with this } } } super.setPressed(state == TristateState.INDETERMINATE); } public TristateState getState() { return state; } } /** * derived from: http://www.coderanch.com/t/342563/GUI/java/TriState-CheckBox */ private static class TristateCheckBoxIcon implements Icon, UIResource, Serializable { private static final long serialVersionUID = 290L; private final int iconHeight; private final int iconWidth; public TristateCheckBoxIcon() { // Assume that the UI has not changed since the checkbox was created UIDefaults defaults = UIManager.getLookAndFeelDefaults(); Icon icon = defaults.getIcon("CheckBox.icon"); if (icon == null) { icon = defaults.getIcon("CheckBox.selected.icon"); } iconHeight = icon == null ? 19 : icon.getIconHeight(); iconWidth = icon == null ? 19 : icon.getIconWidth(); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { JCheckBox cb = (JCheckBox) c; ButtonModel model = cb.getModel(); // TODO fix up for Nimbus LAF if (model.isEnabled()) { if (model.isPressed() && model.isArmed()) { g.setColor(MetalLookAndFeel.getControlShadow()); g.fillRect(x, y, iconWidth - 1, iconHeight - 1); drawPressed3DBorder(g, x, y, iconWidth, iconHeight); } else { drawFlush3DBorder(g, x, y, iconWidth, iconHeight); } g.setColor(MetalLookAndFeel.getControlInfo()); } else { g.setColor(MetalLookAndFeel.getControlShadow()); g.drawRect(x, y, iconWidth - 1, iconHeight - 1); } drawLine(g, x, y); }// paintIcon private void drawLine(Graphics g, int x, int y) { final int left = x + 2; final int right = x + (iconWidth - 4); int height = y + iconHeight/2; g.drawLine(left, height, right, height); g.drawLine(left, height - 1, right, height - 1); } private void drawFlush3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawRect(1, 1, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControl()); g.drawLine(0, h - 1, 1, h - 2); g.drawLine(w - 1, 0, w - 2, 1); g.translate(-x, -y); } private void drawPressed3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); drawFlush3DBorder(g, 0, 0, w, h); g.setColor(MetalLookAndFeel.getControlShadow()); g.drawLine(1, 1, 1, h - 2); g.drawLine(1, 1, w - 2, 1); g.translate(-x, -y); } @Override public int getIconWidth() { return iconWidth; } @Override public int getIconHeight() { return iconHeight; } } }
src/core/src/main/java/org/apache/jmeter/gui/util/TristateCheckBox.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.jmeter.gui.util; import java.awt.AWTEvent; import java.awt.Component; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.Serializable; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.JCheckBox; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ActionMapUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.metal.MetalLookAndFeel; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.NullProperty; /** * derived from: http://www.javaspecialists.eu/archive/Issue145.html */ public final class TristateCheckBox extends JCheckBox { private static final long serialVersionUID = 1L; // Listener on model changes to maintain correct focusability private final class TSCBChangeListener implements ChangeListener, Serializable { /** * */ private static final long serialVersionUID = -3718373200229708535L; @Override public void stateChanged(ChangeEvent e) { TristateCheckBox.this.setFocusable( getModel().isEnabled()); } } private final ChangeListener enableListener = new TSCBChangeListener(); public TristateCheckBox() { this(null, null, TristateState.DESELECTED); } public TristateCheckBox(String text) { this(text, null, TristateState.DESELECTED); } public TristateCheckBox(String text, boolean selected) { this(text, null, selected ? TristateState.SELECTED : TristateState.DESELECTED); } public TristateCheckBox(String text, Icon icon, TristateState initial) { this(text, icon, initial, false); } // For testing only at present TristateCheckBox(String text, Icon icon, TristateState initial, boolean original) { super(text, icon); //Set default single model setModel(new TristateButtonModel(initial, this, original)); // override action behaviour super.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { TristateCheckBox.this.iterateState(); } }); ActionMap actions = new ActionMapUIResource(); actions.put("pressed", new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { TristateCheckBox.this.iterateState(); } }); actions.put("released", null); SwingUtilities.replaceUIActionMap(this, actions); } /** * Set state depending on property * @param element TestElement * @param propName String property name */ public void setTristateFromProperty(TestElement element,String propName) { JMeterProperty jmp = element.getProperty(propName); if (jmp instanceof NullProperty) { this.setIndeterminate(); } else { this.setSelected(jmp.getBooleanValue()); } } /** * Sets a boolean property from a tristate checkbox. * * @param element the test element * @param propName the property name */ public void setPropertyFromTristate(TestElement element, String propName) { if (isIndeterminate()) { element.removeProperty(propName); } else { element.setProperty(propName, isSelected()); } } // Next two methods implement new API by delegation to model public void setIndeterminate() { getTristateModel().setIndeterminate(); } public boolean isIndeterminate() { return getTristateModel().isIndeterminate(); } public TristateState getState() { return getTristateModel().getState(); } //Overrides superclass method @Override public void setModel(ButtonModel newModel) { super.setModel(newModel); //Listen for enable changes if (model instanceof TristateButtonModel) { model.addChangeListener(enableListener); } } //Empty override of superclass method @Override public synchronized void addMouseListener(MouseListener l) { } // Mostly delegates to model private void iterateState() { //Maybe do nothing at all? if (!getModel().isEnabled()) { return; } grabFocus(); // Iterate state getTristateModel().iterateState(); // Fire ActionEvent int modifiers = 0; AWTEvent currentEvent = EventQueue.getCurrentEvent(); if (currentEvent instanceof InputEvent) { modifiers = ((InputEvent) currentEvent).getModifiers(); } else if (currentEvent instanceof ActionEvent) { modifiers = ((ActionEvent) currentEvent).getModifiers(); } fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getText(), System.currentTimeMillis(), modifiers)); } //Convenience cast public TristateButtonModel getTristateModel() { return (TristateButtonModel) super.getModel(); } private static class TristateButtonModel extends ToggleButtonModel { private static final long serialVersionUID = 1L; private TristateState state = TristateState.DESELECTED; private final TristateCheckBox tristateCheckBox; private final Icon icon; private final boolean original; public TristateButtonModel(TristateState initial, TristateCheckBox tristateCheckBox, boolean original) { setState(TristateState.DESELECTED); this.tristateCheckBox = tristateCheckBox; icon = new TristateCheckBoxIcon(); this.original = original; } public void setIndeterminate() { setState(TristateState.INDETERMINATE); } public boolean isIndeterminate() { return state == TristateState.INDETERMINATE; } // Overrides of superclass methods @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); // Restore state display displayState(); } @Override public void setSelected(boolean selected) { setState(selected ? TristateState.SELECTED : TristateState.DESELECTED); } // Empty overrides of superclass methods @Override public void setArmed(boolean b) { } @Override public void setPressed(boolean b) { } void iterateState() { setState(state.next()); } private void setState(TristateState state) { //Set internal state this.state = state; displayState(); if (state == TristateState.INDETERMINATE && isEnabled()) { // force the events to fire // Send ChangeEvent fireStateChanged(); // Send ItemEvent int indeterminate = 3; fireItemStateChanged(new ItemEvent( this, ItemEvent.ITEM_STATE_CHANGED, this, indeterminate)); } } private void displayState() { super.setSelected(state != TristateState.DESELECTED); if (original) { super.setArmed(state == TristateState.INDETERMINATE); } else { if (state == TristateState.INDETERMINATE) { tristateCheckBox.setIcon(icon); // Needed for all but Nimbus tristateCheckBox.setSelectedIcon(icon); // Nimbus works - after a fashion - with this tristateCheckBox.setDisabledSelectedIcon(icon); // Nimbus works - after a fashion - with this } else { // reset if (tristateCheckBox!= null){ tristateCheckBox.setIcon(null); tristateCheckBox.setSelectedIcon(null); tristateCheckBox.setDisabledSelectedIcon(null); // Nimbus works - after a fashion - with this } } } super.setPressed(state == TristateState.INDETERMINATE); } public TristateState getState() { return state; } } /** * derived from: http://www.coderanch.com/t/342563/GUI/java/TriState-CheckBox */ private static class TristateCheckBoxIcon implements Icon, UIResource, Serializable { private static final long serialVersionUID = 290L; private final int iconHeight; private final int iconWidth; public TristateCheckBoxIcon() { // Assume that the UI has not changed since the checkbox was created UIDefaults defaults = UIManager.getLookAndFeelDefaults(); final Icon icon = (Icon) defaults.get("CheckBox.icon"); iconHeight = icon.getIconHeight(); iconWidth = icon.getIconWidth(); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { JCheckBox cb = (JCheckBox) c; ButtonModel model = cb.getModel(); // TODO fix up for Nimbus LAF if (model.isEnabled()) { if (model.isPressed() && model.isArmed()) { g.setColor(MetalLookAndFeel.getControlShadow()); g.fillRect(x, y, iconWidth - 1, iconHeight - 1); drawPressed3DBorder(g, x, y, iconWidth, iconHeight); } else { drawFlush3DBorder(g, x, y, iconWidth, iconHeight); } g.setColor(MetalLookAndFeel.getControlInfo()); } else { g.setColor(MetalLookAndFeel.getControlShadow()); g.drawRect(x, y, iconWidth - 1, iconHeight - 1); } drawLine(g, x, y); }// paintIcon private void drawLine(Graphics g, int x, int y) { final int left = x + 2; final int right = x + (iconWidth - 4); int height = y + iconHeight/2; g.drawLine(left, height, right, height); g.drawLine(left, height - 1, right, height - 1); } private void drawFlush3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawRect(1, 1, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControl()); g.drawLine(0, h - 1, 1, h - 2); g.drawLine(w - 1, 0, w - 2, 1); g.translate(-x, -y); } private void drawPressed3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); drawFlush3DBorder(g, 0, 0, w, h); g.setColor(MetalLookAndFeel.getControlShadow()); g.drawLine(1, 1, 1, h - 2); g.drawLine(1, 1, w - 2, 1); g.translate(-x, -y); } @Override public int getIconWidth() { return iconWidth; } @Override public int getIconHeight() { return iconHeight; } } }
Avoid NPE in TCP Sampler when Darklaf look and feel is used The NPE is caused because LaF does not have CheckBox.icon property
src/core/src/main/java/org/apache/jmeter/gui/util/TristateCheckBox.java
Avoid NPE in TCP Sampler when Darklaf look and feel is used
<ide><path>rc/core/src/main/java/org/apache/jmeter/gui/util/TristateCheckBox.java <ide> public TristateCheckBoxIcon() { <ide> // Assume that the UI has not changed since the checkbox was created <ide> UIDefaults defaults = UIManager.getLookAndFeelDefaults(); <del> final Icon icon = (Icon) defaults.get("CheckBox.icon"); <del> iconHeight = icon.getIconHeight(); <del> iconWidth = icon.getIconWidth(); <add> Icon icon = defaults.getIcon("CheckBox.icon"); <add> if (icon == null) { <add> icon = defaults.getIcon("CheckBox.selected.icon"); <add> } <add> iconHeight = icon == null ? 19 : icon.getIconHeight(); <add> iconWidth = icon == null ? 19 : icon.getIconWidth(); <ide> } <ide> <ide> @Override
Java
apache-2.0
5647f4bd1c7d4df2b6ae0186bf317afb4114a229
0
maduhu/head,AArhin/head,AArhin/head,maduhu/head,AArhin/head,maduhu/head,maduhu/head,maduhu/head,AArhin/head,AArhin/head
package org.mifos.framework.components.batchjobs.helpers; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.mifos.application.servicefacade.ApplicationContextHolder; import org.mifos.framework.components.batchjobs.TaskHelper; import org.mifos.framework.components.batchjobs.exceptions.BatchJobException; import org.mifos.framework.util.ConfigurationLocator; import org.springframework.context.ApplicationContext; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class ETLReportDWHelper extends TaskHelper { private final String FILENAME = "DataWarehouseInitialLoad.kjb"; private static final Logger LOGGER = Logger.getLogger(ETLReportDWHelper.class); @Override public void execute(final long timeInMillis) throws BatchJobException { new ApplicationContextHolder(); ArrayList<String> errors = new ArrayList<String>(); ApplicationContext ach = ApplicationContextHolder.getApplicationContext(); DriverManagerDataSource ds = (DriverManagerDataSource) ach.getBean("dataSource"); DriverManagerDataSource dsDW = (DriverManagerDataSource) ach.getBean("dataSourcePentahoDW"); Pattern pat = Pattern.compile("(jdbc:mysql://)(.*)(:)([0-9]+)(/)([a-zA-Z]*)(?)(.*)"); Matcher m = pat.matcher(dsDW.getUrl()); String nameOfDataBase = null; if (m.find()) { nameOfDataBase = m.group(6); } if (!nameOfDataBase.equals("")) { try { dsDW.getConnection(); } catch (SQLException ex) { errors.add("Data Warehouse is not configured"); throw new BatchJobException("Data warehouse database", errors); } ConfigurationLocator configurationLocator = new ConfigurationLocator(); String configPath = configurationLocator.getConfigurationDirectory(); createPropertiesFileForPentahoDWReports(ds, dsDW); String path = configPath + "/ETL/MifosDataWarehouseETL/" + FILENAME; String jarPath = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar"; String javaHome = System.getProperty("java.home") + "/bin/java"; String pathToLog = configPath + "/ETL/log"; if (File.separatorChar == '\\') { // windows platform javaHome=javaHome.replaceAll("/", "\\\\"); javaHome='"'+javaHome+'"'; jarPath = jarPath.replaceAll("/", "\\\\"); path = path.replaceAll("/", "\\\\"); pathToLog = pathToLog.replaceAll("/", "\\\\"); } PrintWriter fw = null; try { boolean hasErrors = false; boolean notRun = true; ProcessBuilder processBuilder = new ProcessBuilder(javaHome, "-jar", jarPath, path, "false", dsDW.getUsername(), dsDW.getPassword(), dsDW.getUrl()); processBuilder.redirectErrorStream(true); Process p = processBuilder.start(); BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream())); String line =null; if (new File(pathToLog).exists()) { new File(pathToLog).delete(); } File file = new File(pathToLog); fw = new PrintWriter(file); while ((line = reader.readLine()) != null) { fw.println(line); if (line.matches("^ERROR.*")) { hasErrors = true; } notRun=false; } if (notRun) { errors.add("Data Warehouse is not configured properly"); throw new BatchJobException("Data warehouse database", errors); } if (hasErrors) { errors.add("ETL error, for more details see log file: "+pathToLog); throw new BatchJobException("ETL error", errors); } } catch (IOException ex) { throw new BatchJobException(ex.getCause()); } finally { if (fw != null) { fw.close(); } } } else { errors.add("Data Warehouse is not configured"); throw new BatchJobException("Data warehouse database", errors); } } private void createPropertiesFileForPentahoDWReports(DriverManagerDataSource ds, DriverManagerDataSource dsDW) { try { String pathToJNDIDirectory = System.getProperty("user.dir") + "/simple-jndi"; String pathToJNDIPropertiesFile = System.getProperty("user.dir") + "/simple-jndi/jdbc.properties"; if (File.separatorChar == '\\') { pathToJNDIDirectory = pathToJNDIDirectory.replaceAll("/", "\\\\"); pathToJNDIPropertiesFile = pathToJNDIPropertiesFile.replaceAll("/", "\\\\"); } if(!new File(pathToJNDIDirectory).exists()){ new File(pathToJNDIDirectory).mkdir(); } File file = new File(pathToJNDIPropertiesFile); PrintWriter fw = new PrintWriter(file); fw.println("SourceDB/type=javax.sql.DataSource"); fw.println("SourceDB/driver=com.mysql.jdbc.Driver"); fw.println("SourceDB/url=" + ds.getUrl()); fw.println("SourceDB/user=" + ds.getUsername()); fw.println("SourceDB/password=" + ds.getPassword()); fw.println("DestinationDB/type=javax.sql.DataSource"); fw.println("DestinationDB/driver=com.mysql.jdbc.Driver"); fw.println("DestinationDB/url=" + dsDW.getUrl()); fw.println("DestinationDB/user=" + dsDW.getUsername()); fw.println("DestinationDB/password=" + dsDW.getUsername()); fw.close(); } catch (Exception e) { e.printStackTrace(); } } }
application/src/main/java/org/mifos/framework/components/batchjobs/helpers/ETLReportDWHelper.java
package org.mifos.framework.components.batchjobs.helpers; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.mifos.application.servicefacade.ApplicationContextHolder; import org.mifos.framework.components.batchjobs.TaskHelper; import org.mifos.framework.components.batchjobs.exceptions.BatchJobException; import org.mifos.framework.util.ConfigurationLocator; import org.springframework.context.ApplicationContext; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class ETLReportDWHelper extends TaskHelper { private final String FILENAME = "DataWarehouseInitialLoad.kjb"; private static final Logger LOGGER = Logger.getLogger(ETLReportDWHelper.class); @Override public void execute(final long timeInMillis) throws BatchJobException { new ApplicationContextHolder(); ArrayList<String> errors = new ArrayList<String>(); ApplicationContext ach = ApplicationContextHolder.getApplicationContext(); DriverManagerDataSource ds = (DriverManagerDataSource) ach.getBean("dataSource"); DriverManagerDataSource dsDW = (DriverManagerDataSource) ach.getBean("dataSourcePentahoDW"); Pattern pat = Pattern.compile("(jdbc:mysql://)(.*)(:)([0-9]+)(/)([a-zA-Z]*)(?)(.*)"); Matcher m = pat.matcher(dsDW.getUrl()); String nameOfDataBase = null; if (m.find()) { nameOfDataBase = m.group(6); } if (!nameOfDataBase.equals("")) { try { dsDW.getConnection(); } catch (SQLException ex) { errors.add("Data Warehouse is not configured"); throw new BatchJobException("Data warehouse database", errors); } ConfigurationLocator configurationLocator = new ConfigurationLocator(); String configPath = configurationLocator.getConfigurationDirectory(); createPropertiesFileForPentahoDWReports(ds, dsDW); String path = configPath + "/ETL/MifosDataWarehouseETL/" + FILENAME; String jarPath = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar"; String javaHome = System.getProperty("java.home") + "/bin/java"; String pathToLog = configPath + "/ETL/log"; String cmd = "-jar " + jarPath + " " + path + " false"; if (File.separatorChar == '\\') { // windows platform javaHome=javaHome.replaceAll("/", "\\\\"); javaHome='"'+javaHome+'"'; cmd = cmd.replaceAll("/", "\\\\"); } try { boolean hasErrors = false; boolean notRun = true; cmd = javaHome +" "+ cmd +" "+ dsDW.getUsername() + " " + dsDW.getPassword() + " " + dsDW.getUrl(); Process p = Runtime.getRuntime().exec(cmd); BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream())); String line =null; if (new File(pathToLog).exists()) { new File(pathToLog).delete(); } File file = new File(pathToLog); PrintWriter fw = new PrintWriter(file); while ((line = reader.readLine()) != null) { fw.println(line); if (line.matches("^ERROR.*")) { hasErrors = true; } notRun=false; } fw.close(); if (notRun) { errors.add("Data Warehouse is not configured properly"); throw new BatchJobException("Data warehouse database", errors); } if (hasErrors) { errors.add("ETL error, for more details see log file: "+pathToLog); throw new BatchJobException("ETL error", errors); } } catch (IOException ex) { throw new BatchJobException(ex.getCause()); } } else { errors.add("Data Warehouse is not configured"); throw new BatchJobException("Data warehouse database", errors); } } private void createPropertiesFileForPentahoDWReports(DriverManagerDataSource ds, DriverManagerDataSource dsDW) { try { String pathToJNDIDirectory = System.getProperty("user.dir") + "/simple-jndi"; String pathToJNDIPropertiesFile = System.getProperty("user.dir") + "/simple-jndi/jdbc.properties"; if (File.separatorChar == '\\') { pathToJNDIDirectory = pathToJNDIDirectory.replaceAll("/", "\\\\"); pathToJNDIPropertiesFile = pathToJNDIPropertiesFile.replaceAll("/", "\\\\"); } if(!new File(pathToJNDIDirectory).exists()){ new File(pathToJNDIDirectory).mkdir(); } File file = new File(pathToJNDIPropertiesFile); PrintWriter fw = new PrintWriter(file); fw.println("SourceDB/type=javax.sql.DataSource"); fw.println("SourceDB/driver=com.mysql.jdbc.Driver"); fw.println("SourceDB/url=" + ds.getUrl()); fw.println("SourceDB/user=" + ds.getUsername()); fw.println("SourceDB/password=" + ds.getPassword()); fw.println("DestinationDB/type=javax.sql.DataSource"); fw.println("DestinationDB/driver=com.mysql.jdbc.Driver"); fw.println("DestinationDB/url=" + dsDW.getUrl()); fw.println("DestinationDB/user=" + dsDW.getUsername()); fw.println("DestinationDB/password=" + dsDW.getUsername()); fw.close(); } catch (Exception e) { e.printStackTrace(); } } }
MIFOS-5876 Fixed batch job freezing when started on some databases
application/src/main/java/org/mifos/framework/components/batchjobs/helpers/ETLReportDWHelper.java
MIFOS-5876 Fixed batch job freezing when started on some databases
<ide><path>pplication/src/main/java/org/mifos/framework/components/batchjobs/helpers/ETLReportDWHelper.java <ide> String jarPath = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar"; <ide> String javaHome = System.getProperty("java.home") + "/bin/java"; <ide> String pathToLog = configPath + "/ETL/log"; <del> String cmd = "-jar " + jarPath + " " + path + " false"; <add> <ide> if (File.separatorChar == '\\') { // windows platform <ide> javaHome=javaHome.replaceAll("/", "\\\\"); <ide> javaHome='"'+javaHome+'"'; <del> cmd = cmd.replaceAll("/", "\\\\"); <add> jarPath = jarPath.replaceAll("/", "\\\\"); <add> path = path.replaceAll("/", "\\\\"); <add> pathToLog = pathToLog.replaceAll("/", "\\\\"); <ide> } <add> PrintWriter fw = null; <ide> try { <ide> boolean hasErrors = false; <ide> boolean notRun = true; <del> cmd = javaHome +" "+ cmd +" "+ dsDW.getUsername() + " " + dsDW.getPassword() + " " + dsDW.getUrl(); <del> Process p = Runtime.getRuntime().exec(cmd); <add> ProcessBuilder processBuilder = new ProcessBuilder(javaHome, "-jar", jarPath, path, "false", <add> dsDW.getUsername(), dsDW.getPassword(), dsDW.getUrl()); <add> processBuilder.redirectErrorStream(true); <add> Process p = processBuilder.start(); <ide> BufferedReader reader = new BufferedReader (new InputStreamReader(p.getInputStream())); <ide> String line =null; <ide> if (new File(pathToLog).exists()) { <ide> new File(pathToLog).delete(); <ide> } <ide> File file = new File(pathToLog); <del> PrintWriter fw = new PrintWriter(file); <add> fw = new PrintWriter(file); <ide> while ((line = reader.readLine()) != null) { <ide> fw.println(line); <ide> if (line.matches("^ERROR.*")) { <ide> } <ide> notRun=false; <ide> } <del> fw.close(); <ide> if (notRun) { <ide> errors.add("Data Warehouse is not configured properly"); <ide> throw new BatchJobException("Data warehouse database", errors); <ide> } <ide> } catch (IOException ex) { <ide> throw new BatchJobException(ex.getCause()); <add> } finally { <add> if (fw != null) { <add> fw.close(); <add> } <ide> } <ide> } else { <ide> errors.add("Data Warehouse is not configured");
Java
apache-2.0
55de2f0dfa9ef127a8b30b59bba86b15fbe1e6f1
0
googlegsa/documentum.v3,googlegsa/documentum.v3
// Copyright 2007 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.enterprise.connector.dctm; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.google.enterprise.connector.dctm.dfcwrap.IAttr; import com.google.enterprise.connector.dctm.dfcwrap.ICollection; import com.google.enterprise.connector.dctm.dfcwrap.IFormat; import com.google.enterprise.connector.dctm.dfcwrap.IId; import com.google.enterprise.connector.dctm.dfcwrap.IQuery; import com.google.enterprise.connector.dctm.dfcwrap.ISession; import com.google.enterprise.connector.dctm.dfcwrap.ISysObject; import com.google.enterprise.connector.dctm.dfcwrap.ITime; import com.google.enterprise.connector.dctm.dfcwrap.IType; import com.google.enterprise.connector.dctm.dfcwrap.IValue; import com.google.enterprise.connector.spi.Document; import com.google.enterprise.connector.spi.Property; import com.google.enterprise.connector.spi.RepositoryDocumentException; import com.google.enterprise.connector.spi.RepositoryException; import com.google.enterprise.connector.spi.RepositoryLoginException; import com.google.enterprise.connector.spi.SkippedDocumentException; import com.google.enterprise.connector.spi.SimpleProperty; import com.google.enterprise.connector.spi.SpiConstants; import com.google.enterprise.connector.spi.SpiConstants.ActionType; import com.google.enterprise.connector.spi.TraversalContext; import com.google.enterprise.connector.spi.Value; public class DctmSysobjectDocument implements Document { private static final Logger logger = Logger.getLogger(DctmSysobjectDocument.class.getName()); /** The maximum content size that will be allowed. */ private static final long MAX_CONTENT_SIZE = 30L * 1024 * 1024; private static final String OBJECT_ID_NAME = "r_object_id"; /** A regexp that matches the defined SPI property names. */ /* * Package access for the unit tests. * TODO: Remove in favor of SpiConstants.RESERVED_PROPNAME_PREFIX in CM 3.0. */ static final String PROPNAME_REGEXP = "google:.+"; /** * Identifies an optional, multi-valued property that specifies the * folder path of the document. */ /* TODO: Remove in favor of SpiConstants.PROPNAME_FOLDER in CM 3.0. */ private static final String PROPNAME_FOLDER = "google:folder"; /** * A record of logged requests for unsupported SPI properties so we * don't spam the logs. */ /* Package access for the unit tests. */ static Set<String> UNSUPPORTED_PROPNAMES = new HashSet<String>(); private final DctmTraversalManager traversalManager; private final ISession session; private final String docId; private String versionId; private ITime timeStamp; private final ActionType action; private final Checkpoint checkpoint; private ISysObject object; public DctmSysobjectDocument(DctmTraversalManager traversalManager, ISession session, String docid, String commonVersionID, ITime timeStamp, ActionType action, Checkpoint checkpoint) { this.traversalManager = traversalManager; this.session = session; this.docId = docid; this.versionId = commonVersionID; this.timeStamp = timeStamp; this.action = action; this.checkpoint = checkpoint; } private void fetch() throws RepositoryDocumentException, RepositoryLoginException, RepositoryException { if (object != null || !ActionType.ADD.equals(action)) { return; } try { IId id = traversalManager.getClientX().getId(docId); object = session.getObject(id); if (versionId == null || versionId.length() == 0) { versionId = object.getId("i_chronicle_id").getId(); } logger.fine("i_chronicle_id of the fetched object is " + versionId); if (timeStamp == null) { timeStamp = object.getTime("r_modify_date"); } } catch (RepositoryDocumentException rde) { // Propagate unmolested. throw rde; } catch (RepositoryException re) { if (checkpoint != null && lostConnection(session)) { // We have lost connectivity with the server. // Rollback the checkpoint and retry this document later. checkpoint.restore(); } throw re; } } /** * Test connectivity to server. If we have a session and * can verify that session isConnected(), return false. * If we cannot verify the session is connected return true. */ private boolean lostConnection(ISession session) { try { return !session.isConnected(); } catch (Exception e) { logger.warning("Lost connectivity to server: " + e); return true; } } /** * {@inheritDoc} * * <p>This implementation looks up the properties when this method * is called. */ public Property findProperty(String name) throws RepositoryDocumentException, RepositoryLoginException, RepositoryException { if (name == null || name.length() == 0) return null; List<Value> values = new LinkedList<Value>(); if (logger.isLoggable(Level.FINEST)) logger.finest("In findProperty; name: " + name); if (ActionType.ADD.equals(action)) { fetch(); boolean found = findCoreProperty(name, values); if (!found) found = findAddProperty(name, values); if (!found) return null; } else { boolean found = findCoreProperty(name, values); if (!found) return null; } if (logger.isLoggable(Level.FINE)) { logger.fine("property " + name + " has the values " + values); } return values.isEmpty() ? null : new SimpleProperty(values); } /** * Adds the values for the named property to the list. The * properties handled by this method are always available, for both * add and delete actions. * * @param name a property name * @param values the empty list to add values to * @return true if values were added to the list * @throws RepositoryException if an unexpected error occurs */ private boolean findCoreProperty(String name, List<Value> values) throws RepositoryException { if (SpiConstants.PROPNAME_ACTION.equals(name)) { values.add(Value.getStringValue(action.toString())); } else if (name.equals(SpiConstants.PROPNAME_DOCID)) { values.add(Value.getStringValue(versionId)); } else if (name.equals(SpiConstants.PROPNAME_LASTMODIFIED)) { if (timeStamp == null) { return false; } values.add(Value.getDateValue( getCalendarFromDate(timeStamp.getDate()))); } else { // No property by that name found. return false; } return true; } /** * Adds the values for the named property to the list. The * properties handled by this method are available only for the add * action. A fetched SysObject is used to obtain the values. * * @param name a property name * @param values the empty list to add values to * @return true if values were added to the list * @throws RepositoryException if an unexpected error occurs */ /* TODO: Should we unify the RepositoryDocumentException handling? */ private boolean findAddProperty(String name, List<Value> values) throws RepositoryException { if (SpiConstants.PROPNAME_CONTENT.equals(name)) { try { if (canIndex(true)) { values.add(Value.getBinaryValue(object.getContent())); } } catch (RepositoryDocumentException e) { // FIXME: In the unlikely event the user only has BROWSE // permission for a document, we'll end up here. That's // fine, but the google:mimetype property will not be reset // to "text/plain" in that case. logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_DISPLAYURL.equals(name)) { String displayUrl = traversalManager.getServerUrl() + docId; values.add(Value.getStringValue(displayUrl)); } else if (PROPNAME_FOLDER.equals(name)) { // TODO: SpiConstants.PROPNAME_FOLDER in CM 3.0. return findFolderProperty(name, values); } else if (SpiConstants.PROPNAME_SECURITYTOKEN.equals(name)) { try { values.add(Value.getStringValue(object.getACLDomain() + " " + object.getACLName())); } catch (RepositoryDocumentException e) { logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_ISPUBLIC.equals(name)) { values.add(Value.getBooleanValue(traversalManager.isPublic())); } else if (SpiConstants.PROPNAME_MIMETYPE.equals(name)) { try { IFormat dctmForm = object.getFormat(); String mimetype = dctmForm.getMIMEType(); logger.fine("mimetype of the document " + versionId + ": " + mimetype); // The GSA will not index empty documents with binary content types, // so omit the content type if the document cannot be indexed. if (canIndex(false)) { values.add(Value.getStringValue(mimetype)); } } catch (RepositoryDocumentException e) { logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_TITLE.equals(name)) { values.add(Value.getStringValue(object.getObjectName())); } else if (name.matches(PROPNAME_REGEXP)) { if (UNSUPPORTED_PROPNAMES.add(name)) { logger.finest("Ignoring unsupported SPI property " + name); } return false; } else { return findDctmAttribute(name, values); } return true; } /** * Adds the values for the folder paths to the list. * * @param name a property name * @param values the empty list to add values to * @return true if values were added to the list * @throws RepositoryException if an unexpected error occurs */ private boolean findFolderProperty(String name, List<Value> values) throws RepositoryException { // We have already done a fetch of this object, so we read // i_folder_id directly rather than doing a subquery or join // on the object ID. int count = object.getValueCount("i_folder_id"); if (count == 0) return false; StringBuilder dql = new StringBuilder(); dql.append("select r_folder_path from dm_folder "); dql.append("where r_folder_path is not null and r_object_id in ("); for (int i = 0; i < count; i++) { dql.append('\''); dql.append(object.getRepeatingValue("i_folder_id", i).asString()); dql.append("',"); } dql.setCharAt(dql.length() - 1, ')'); dql.append(" ENABLE (row_based)"); IQuery query = traversalManager.getClientX().getQuery(); query.setDQL(dql.toString()); try { ICollection collec = query.execute(session, IQuery.READ_QUERY); try { while (collec.next()) { values.add( Value.getStringValue(collec.getString("r_folder_path"))); } } finally { collec.close(); } } catch (RepositoryDocumentException e) { logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } return true; } /** * Adds the values for a Documentum attribute to the list. * * @param name a attribute name * @param values the empty list to add values to * @return true if values were added to the list * @throws RepositoryException if an unexpected error occurs */ private boolean findDctmAttribute(String name, List<Value> values) throws RepositoryException { if (OBJECT_ID_NAME.equals(name)) { values.add(Value.getStringValue(docId)); } else if (name.equals("r_object_type")) { // Retrieves object type and its super type(s). for (IType value = object.getType(); value != null; value = getSuperType(value)) { String typeName = value.getName(); values.add(Value.getStringValue(typeName)); } } else { // TODO: We could store the data types for each attribute in // the type attributes cache, and save about 2% of the // traversal time here by avoiding the calls to findAttrIndex // and getAttr. int attrIndex = object.findAttrIndex(name); if (attrIndex != -1) { IAttr attr = object.getAttr(attrIndex); getDctmAttribute(name, attr.getDataType(), values); } else { // No property by that name found. return false; } } return true; } /** * Helper method that values for a Documentum attribute to the list. * * @param name an attribute name * @param dataType the data type of the attribute * @param values the empty list to add values to * @throws RepositoryException if an unexpected error occurs */ private void getDctmAttribute(String name, int dataType, List<Value> values) throws RepositoryException { for (int i = 0, n = object.getValueCount(name); i < n; i++) { IValue val = object.getRepeatingValue(name, i); try { switch (dataType) { case IAttr.DM_BOOLEAN: values.add(Value.getBooleanValue(val.asBoolean())); break; case IAttr.DM_DOUBLE: values.add(Value.getDoubleValue(val.asDouble())); break; case IAttr.DM_ID: // TODO: Should we check for null here? values.add(Value.getStringValue(val.asId().getId())); break; case IAttr.DM_INTEGER: values.add(Value.getLongValue(val.asInteger())); break; case IAttr.DM_STRING: values.add(Value.getStringValue(val.asString())); break; case IAttr.DM_TIME: Date date = val.asTime().getDate(); if (date != null) { values.add(Value.getDateValue(getCalendarFromDate(date))); } break; default: // TODO: Should this be an exception, or just logged // directly as a warning? throw new AssertionError(String.valueOf(dataType)); } } catch (Exception e) { logger.log(Level.WARNING, "error getting the value of index " + i + " of the attribute " + name, e); } } } /** * Return the supertype for the supplied type. Caches result to * avoid frequent round-trips to server. * * @return superType for supplied type, or null if type is root type. */ private IType getSuperType(IType type) throws RepositoryException { if (type == null) return null; Map<String, IType> superTypes = traversalManager.getSuperTypeCache(); String typeName = type.getName(); if (superTypes.containsKey(typeName)) return superTypes.get(typeName); else { IType superType = type.getSuperType(); superTypes.put(typeName, superType); return superType; } } /** * Return true if the obect's content should be supplied for indexing. */ private boolean canIndex(boolean logging) throws RepositoryException { // Don't send content that is too big or too small. long contentSize = object.getContentSize(); TraversalContext traversalContext = traversalManager.getTraversalContext(); // Don't send content whose mimetype is not supported. IFormat format = object.getFormat(); String mimetype = format.getMIMEType(); if (traversalContext != null) { int supportLevel = traversalContext.mimeTypeSupportLevel(mimetype); if (supportLevel < 0) { if (logging) { logger.fine("excluded content format: " + format.getName()); } throw new SkippedDocumentException("Excluded by content type: " + mimetype); } if (supportLevel == 0) { if (logging) { logger.fine("unindexable content format: " + format.getName()); } return false; } if (contentSize > traversalContext.maxDocumentSize()) { if (logging) { logger.fine("content is too large: " + contentSize); } return false; } } else { if (!format.canIndex()) { if (logging) { logger.fine("unindexable content format: " + format.getName()); } return false; } if (contentSize > MAX_CONTENT_SIZE) { if (logging) { logger.fine("content is too large: " + contentSize); } return false; } } if (contentSize <= 0) { if (logging) { logger.fine("this object has no content"); } return false; } return true; } private Calendar getCalendarFromDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar; } /** * Return the attributes for the supplied type. Caches result to * avoid frequent round-trips to server. * * @param type the object type to get attributes for * @return type attributes for the supplied type * @throws RepositoryException if an error occurs retrieving the attributes */ private List<String> getTypeAttributes(IType type) throws RepositoryException { Map<String, List<String>> cache = traversalManager.getTypeAttributesCache(); String typeName = type.getName(); if (cache.containsKey(typeName)) { return cache.get(typeName); } else { if (logger.isLoggable(Level.FINER)) { logger.finer("Processing attributes for type " + typeName); } int count = type.getTypeAttrCount(); ArrayList<String> typeAttributes = new ArrayList<String>(count); Set<String> includedMeta = traversalManager.getIncludedMeta(); Set<String> excludedMeta = traversalManager.getExcludedMeta(); try { for (int i = 0; i < count; i++) { IAttr curAttr = type.getTypeAttr(i); String name = curAttr.getName(); if ((includedMeta.isEmpty() || includedMeta.contains(name)) && !excludedMeta.contains(name)) { typeAttributes.add(name); if (logger.isLoggable(Level.FINEST)) { logger.finest("attribute " + name + " added to the properties"); } } else { if (logger.isLoggable(Level.FINEST)) { logger.finest("attribute " + name + " excluded from the properties"); } } } } catch (RepositoryDocumentException e) { logger.log(Level.WARNING, "Error fetching property names", e); } cache.put(typeName, typeAttributes); return typeAttributes; } } public Set<String> getPropertyNames() throws RepositoryException { Set<String> properties; if (ActionType.ADD.equals(action)) { fetch(); properties = new HashSet<String>(); properties.add(SpiConstants.PROPNAME_DISPLAYURL); // TODO: SpiConstants.PROPNAME_FOLDER in CM 3.0. properties.add(PROPNAME_FOLDER); properties.add(SpiConstants.PROPNAME_ISPUBLIC); properties.add(SpiConstants.PROPNAME_LASTMODIFIED); properties.add(SpiConstants.PROPNAME_MIMETYPE); properties.add(SpiConstants.PROPNAME_TITLE); List<String> typeAttributes = getTypeAttributes(object.getType()); properties.addAll(typeAttributes); } else { // XXX: This is dead code. The CM never asks for the property // names for delete actions. Does it matter? properties = new HashSet<String>(); properties.add(SpiConstants.PROPNAME_ACTION); properties.add(SpiConstants.PROPNAME_DOCID); properties.add(SpiConstants.PROPNAME_LASTMODIFIED); } return properties; } }
projects/google-enterprise-connector-dctm/source/java/com/google/enterprise/connector/dctm/DctmSysobjectDocument.java
// Copyright 2007 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.enterprise.connector.dctm; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.google.enterprise.connector.dctm.dfcwrap.IAttr; import com.google.enterprise.connector.dctm.dfcwrap.ICollection; import com.google.enterprise.connector.dctm.dfcwrap.IFormat; import com.google.enterprise.connector.dctm.dfcwrap.IId; import com.google.enterprise.connector.dctm.dfcwrap.IQuery; import com.google.enterprise.connector.dctm.dfcwrap.ISession; import com.google.enterprise.connector.dctm.dfcwrap.ISysObject; import com.google.enterprise.connector.dctm.dfcwrap.ITime; import com.google.enterprise.connector.dctm.dfcwrap.IType; import com.google.enterprise.connector.dctm.dfcwrap.IValue; import com.google.enterprise.connector.spi.Document; import com.google.enterprise.connector.spi.Property; import com.google.enterprise.connector.spi.RepositoryDocumentException; import com.google.enterprise.connector.spi.RepositoryException; import com.google.enterprise.connector.spi.RepositoryLoginException; import com.google.enterprise.connector.spi.SkippedDocumentException; import com.google.enterprise.connector.spi.SimpleProperty; import com.google.enterprise.connector.spi.SpiConstants; import com.google.enterprise.connector.spi.SpiConstants.ActionType; import com.google.enterprise.connector.spi.TraversalContext; import com.google.enterprise.connector.spi.Value; public class DctmSysobjectDocument implements Document { private static final Logger logger = Logger.getLogger(DctmSysobjectDocument.class.getName()); /** The maximum content size that will be allowed. */ private static final long MAX_CONTENT_SIZE = 30L * 1024 * 1024; private static final String OBJECT_ID_NAME = "r_object_id"; /** A regexp that matches the defined SPI property names. */ /* * Package access for the unit tests. * TODO: Remove in favor of SpiConstants.RESERVED_PROPNAME_PREFIX in CM 3.0. */ static final String PROPNAME_REGEXP = "google:.+"; /** * Identifies an optional, multi-valued property that specifies the * folder path of the document. */ /* TODO: Remove in favor of SpiConstants.PROPNAME_FOLDER in CM 3.0. */ private static final String PROPNAME_FOLDER = "google:folder"; /** * A record of logged requests for unsupported SPI properties so we * don't spam the logs. */ /* Package access for the unit tests. */ static Set<String> UNSUPPORTED_PROPNAMES = new HashSet<String>(); private final DctmTraversalManager traversalManager; private final ISession session; private final String docId; private String versionId; private ITime timeStamp; private final ActionType action; private final Checkpoint checkpoint; private ISysObject object; public DctmSysobjectDocument(DctmTraversalManager traversalManager, ISession session, String docid, String commonVersionID, ITime timeStamp, ActionType action, Checkpoint checkpoint) { this.traversalManager = traversalManager; this.session = session; this.docId = docid; this.versionId = commonVersionID; this.timeStamp = timeStamp; this.action = action; this.checkpoint = checkpoint; } private void fetch() throws RepositoryDocumentException, RepositoryLoginException, RepositoryException { if (object != null || !ActionType.ADD.equals(action)) { return; } try { IId id = traversalManager.getClientX().getId(docId); object = session.getObject(id); if (versionId == null || versionId.length() == 0) { versionId = object.getId("i_chronicle_id").getId(); } logger.fine("i_chronicle_id of the fetched object is " + versionId); if (timeStamp == null) { timeStamp = object.getTime("r_modify_date"); } } catch (RepositoryDocumentException rde) { // Propagate unmolested. throw rde; } catch (RepositoryException re) { if (checkpoint != null && lostConnection(session)) { // We have lost connectivity with the server. // Rollback the checkpoint and retry this document later. checkpoint.restore(); } throw re; } } /** * Test connectivity to server. If we have a session and * can verify that session isConnected(), return false. * If we cannot verify the session is connected return true. */ private boolean lostConnection(ISession session) { try { return !session.isConnected(); } catch (Exception e) { logger.warning("Lost connectivity to server: " + e); return true; } } public Property findProperty(String name) throws RepositoryDocumentException, RepositoryLoginException, RepositoryException { if (name == null || name.length() == 0) return null; LinkedList<Value> values = new LinkedList<Value>(); if (logger.isLoggable(Level.FINEST)) logger.finest("In findProperty; name: " + name); if (ActionType.ADD.equals(action)) { fetch(); if (SpiConstants.PROPNAME_ACTION.equals(name)) { values.add(Value.getStringValue(action.toString())); } else if (name.equals(SpiConstants.PROPNAME_DOCID)) { values.add(Value.getStringValue(versionId)); } else if (SpiConstants.PROPNAME_CONTENT.equals(name)) { try { if (canIndex(true)) { values.add(Value.getBinaryValue(object.getContent())); } } catch (RepositoryDocumentException e) { // FIXME: In the unlikely event the user only has BROWSE // permission for a document, we'll end up here. That's // fine, but the google:mimetype property will not be reset // to "text/plain" in that case. logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_DISPLAYURL.equals(name)) { String displayUrl = traversalManager.getServerUrl() + docId; values.add(Value.getStringValue(displayUrl)); } else if (PROPNAME_FOLDER.equals(name)) { // TODO: SpiConstants.PROPNAME_FOLDER in CM 3.0. int count = object.getValueCount("i_folder_id"); if (count == 0) return null; // We have already done a fetch of this object, so we read // i_folder_id directly rather than doing a subquery or join // on the object ID. StringBuilder dql = new StringBuilder(); dql.append("select r_folder_path from dm_folder "); dql.append("where r_folder_path is not null and r_object_id in ("); for (int i = 0; i < count; i++) { dql.append('\''); dql.append(object.getRepeatingValue("i_folder_id", i).asString()); dql.append("',"); } dql.setCharAt(dql.length() - 1, ')'); dql.append(" ENABLE (row_based)"); IQuery query = traversalManager.getClientX().getQuery(); query.setDQL(dql.toString()); try { ICollection collec = query.execute(session, IQuery.READ_QUERY); try { while (collec.next()) { values.add( Value.getStringValue(collec.getString("r_folder_path"))); } } finally { collec.close(); } } catch (RepositoryDocumentException e) { logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_SECURITYTOKEN.equals(name)) { try { values.add(Value.getStringValue(object.getACLDomain() + " " + object.getACLName())); } catch (RepositoryDocumentException e) { logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_ISPUBLIC.equals(name)) { values.add(Value.getBooleanValue(traversalManager.isPublic())); } else if (SpiConstants.PROPNAME_LASTMODIFIED.equals(name)) { if (timeStamp != null) { values.add(Value.getDateValue(getCalendarFromDate(timeStamp.getDate()))); } } else if (SpiConstants.PROPNAME_MIMETYPE.equals(name)) { try { IFormat dctmForm = object.getFormat(); String mimetype = dctmForm.getMIMEType(); logger.fine("mimetype of the document " + versionId + ": " + mimetype); // Modification in order to index empty documents. if (canIndex(false)) { values.add(Value.getStringValue(mimetype)); } } catch (RepositoryDocumentException e) { logger.warning("RepositoryDocumentException thrown: " + e + " on getting property: " + name); } } else if (SpiConstants.PROPNAME_TITLE.equals(name)) { values.add(Value.getStringValue(object.getObjectName())); } else if (name.matches(PROPNAME_REGEXP)) { if (UNSUPPORTED_PROPNAMES.add(name)) { logger.finest("Ignoring unsupported SPI property " + name); } return null; } else if (OBJECT_ID_NAME.equals(name)) { values.add(Value.getStringValue(docId)); } else if (name.equals("r_object_type")) { // Retrieves object type and its super type(s). for (IType value = object.getType(); value != null; value = getSuperType(value)) { String typeName = value.getName(); values.add(Value.getStringValue(typeName)); } } else { // TODO: We could store the data types for each attribute in // the type attributes cache, and save about 2% of the // traversal time here by avoiding the calls to findAttrIndex // and getAttr. int attrIndex = object.findAttrIndex(name); if (attrIndex != -1) { IAttr attr = object.getAttr(attrIndex); for (int i = 0, n = object.getValueCount(name); i < n; i++) { IValue val = object.getRepeatingValue(name, i); try { switch (attr.getDataType()) { case IAttr.DM_BOOLEAN: values.add(Value.getBooleanValue(val.asBoolean())); break; case IAttr.DM_DOUBLE: values.add(Value.getDoubleValue(val.asDouble())); break; case IAttr.DM_ID: // TODO: Should we check for null here? values.add(Value.getStringValue(val.asId().getId())); break; case IAttr.DM_INTEGER: values.add(Value.getLongValue(val.asInteger())); break; case IAttr.DM_STRING: values.add(Value.getStringValue(val.asString())); break; case IAttr.DM_TIME: Date date = val.asTime().getDate(); if (date != null) { values.add(Value.getDateValue(getCalendarFromDate(date))); } break; default: // TODO: Should this be an exception, or just logged // directly as a warning? throw new AssertionError(String.valueOf(attr.getDataType())); } } catch (Exception e) { logger.log(Level.WARNING, "error getting the value of index " + i + " of the attribute " + name, e); } } } else { // No property by that name found. return null; } } } else { if (SpiConstants.PROPNAME_ACTION.equals(name)) { values.add(Value.getStringValue(action.toString())); } else if (name.equals(SpiConstants.PROPNAME_DOCID)) { values.add(Value.getStringValue(versionId)); } else if (name.equals(SpiConstants.PROPNAME_LASTMODIFIED)) { if (timeStamp != null) { values.add(Value.getDateValue(getCalendarFromDate(timeStamp.getDate()))); } } else if (OBJECT_ID_NAME.equals(name)) { values.add(Value.getStringValue(docId)); } else { // No property by that name found. return null; } } if (logger.isLoggable(Level.FINE)) { logger.fine("property " + name + " has the values " + values); } return new SimpleProperty(values); } /** * Return the supertype for the supplied type. Caches result to * avoid frequent round-trips to server. * * @return superType for supplied type, or null if type is root type. */ private IType getSuperType(IType type) throws RepositoryException { if (type == null) return null; Map<String, IType> superTypes = traversalManager.getSuperTypeCache(); String typeName = type.getName(); if (superTypes.containsKey(typeName)) return superTypes.get(typeName); IType superType = type.getSuperType(); superTypes.put(typeName, superType); return superType; } /** * Return true if the obect's content should be supplied for indexing. */ private boolean canIndex(boolean logging) throws RepositoryException { // Don't send content that is too big or too small. long contentSize = object.getContentSize(); TraversalContext traversalContext = traversalManager.getTraversalContext(); // Don't send content whose mimetype is not supported. IFormat format = object.getFormat(); String mimetype = format.getMIMEType(); if (traversalContext != null) { int supportLevel = traversalContext.mimeTypeSupportLevel(mimetype); if (supportLevel < 0) { if (logging) { logger.fine("excluded content format: " + format.getName()); } throw new SkippedDocumentException("Excluded by content type: " + mimetype); } if (supportLevel == 0) { if (logging) { logger.fine("unindexable content format: " + format.getName()); } return false; } if (contentSize > traversalContext.maxDocumentSize()) { if (logging) { logger.fine("content is too large: " + contentSize); } return false; } } else { if (!format.canIndex()) { if (logging) { logger.fine("unindexable content format: " + format.getName()); } return false; } if (contentSize > MAX_CONTENT_SIZE) { if (logging) { logger.fine("content is too large: " + contentSize); } return false; } } if (contentSize <= 0) { if (logging) { logger.fine("this object has no content"); } return false; } return true; } private Calendar getCalendarFromDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar; } /** * Return the attributes for the supplied type. Caches result to * avoid frequent round-trips to server. * * @param type the object type to get attributes for * @return type attributes for the supplied type * @throws RepositoryException if an error occurs retrieving the attributes */ private List<String> getTypeAttributes(IType type) throws RepositoryException { Map<String, List<String>> cache = traversalManager.getTypeAttributesCache(); String typeName = type.getName(); if (cache.containsKey(typeName)) { return cache.get(typeName); } else { if (logger.isLoggable(Level.FINER)) { logger.finer("Processing attributes for type " + typeName); } int count = type.getTypeAttrCount(); ArrayList<String> typeAttributes = new ArrayList<String>(count); Set<String> includedMeta = traversalManager.getIncludedMeta(); Set<String> excludedMeta = traversalManager.getExcludedMeta(); try { for (int i = 0; i < count; i++) { IAttr curAttr = type.getTypeAttr(i); String name = curAttr.getName(); if ((includedMeta.isEmpty() || includedMeta.contains(name)) && !excludedMeta.contains(name)) { typeAttributes.add(name); if (logger.isLoggable(Level.FINEST)) { logger.finest("attribute " + name + " added to the properties"); } } else { if (logger.isLoggable(Level.FINEST)) { logger.finest("attribute " + name + " excluded from the properties"); } } } } catch (RepositoryDocumentException e) { logger.log(Level.WARNING, "Error fetching property names", e); } cache.put(typeName, typeAttributes); return typeAttributes; } } public Set<String> getPropertyNames() throws RepositoryException { Set<String> properties = null; if (ActionType.ADD.equals(action)) { fetch(); properties = new HashSet<String>(); properties.add(SpiConstants.PROPNAME_DISPLAYURL); // TODO: SpiConstants.PROPNAME_FOLDER in CM 3.0. properties.add(PROPNAME_FOLDER); properties.add(SpiConstants.PROPNAME_ISPUBLIC); properties.add(SpiConstants.PROPNAME_LASTMODIFIED); properties.add(SpiConstants.PROPNAME_MIMETYPE); properties.add(SpiConstants.PROPNAME_TITLE); List<String> typeAttributes = getTypeAttributes(object.getType()); properties.addAll(typeAttributes); } else { properties = new HashSet<String>(); properties.add(SpiConstants.PROPNAME_ACTION); properties.add(SpiConstants.PROPNAME_DOCID); properties.add(SpiConstants.PROPNAME_LASTMODIFIED); properties.add(OBJECT_ID_NAME); } return properties; } }
Broke up the 180-line findProperty method into six methods: findProperty findCoreProperty - shared properties between add and delete findAddProperty - properties unique to add findFolderProperty - google:folder property, based on r_folder_path findDctmAttribute - Documentum attributes getDctmAttribute - gets Documentum attribute values The only semantic change was that in cases where a Property object with no values could have been returned, the code will now return null. (The previous behavior was inconsistent, sometimes return an empty Property object and sometimes returning null. The CM has slightly better logging for null, and handles the two values identically.) M projects/google-enterprise-connector-dctm/source/java/com/google/enterprise/connector/dctm/DctmSysobjectDocument.java
projects/google-enterprise-connector-dctm/source/java/com/google/enterprise/connector/dctm/DctmSysobjectDocument.java
Broke up the 180-line findProperty method into six methods:
<ide><path>rojects/google-enterprise-connector-dctm/source/java/com/google/enterprise/connector/dctm/DctmSysobjectDocument.java <ide> import java.util.ArrayList; <ide> import java.util.Calendar; <ide> import java.util.Date; <del>import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> } <ide> } <ide> <add> /** <add> * {@inheritDoc} <add> * <add> * <p>This implementation looks up the properties when this method <add> * is called. <add> */ <ide> public Property findProperty(String name) throws RepositoryDocumentException, <ide> RepositoryLoginException, RepositoryException { <ide> if (name == null || name.length() == 0) <ide> return null; <ide> <del> LinkedList<Value> values = new LinkedList<Value>(); <add> List<Value> values = new LinkedList<Value>(); <ide> <ide> if (logger.isLoggable(Level.FINEST)) <ide> logger.finest("In findProperty; name: " + name); <ide> <ide> if (ActionType.ADD.equals(action)) { <ide> fetch(); <del> if (SpiConstants.PROPNAME_ACTION.equals(name)) { <del> values.add(Value.getStringValue(action.toString())); <del> } else if (name.equals(SpiConstants.PROPNAME_DOCID)) { <del> values.add(Value.getStringValue(versionId)); <del> } else if (SpiConstants.PROPNAME_CONTENT.equals(name)) { <del> try { <del> if (canIndex(true)) { <del> values.add(Value.getBinaryValue(object.getContent())); <del> } <del> } catch (RepositoryDocumentException e) { <del> // FIXME: In the unlikely event the user only has BROWSE <del> // permission for a document, we'll end up here. That's <del> // fine, but the google:mimetype property will not be reset <del> // to "text/plain" in that case. <del> logger.warning("RepositoryDocumentException thrown: " + e <del> + " on getting property: " + name); <del> } <del> } else if (SpiConstants.PROPNAME_DISPLAYURL.equals(name)) { <del> String displayUrl = traversalManager.getServerUrl() + docId; <del> values.add(Value.getStringValue(displayUrl)); <del> } else if (PROPNAME_FOLDER.equals(name)) { <del> // TODO: SpiConstants.PROPNAME_FOLDER in CM 3.0. <del> int count = object.getValueCount("i_folder_id"); <del> if (count == 0) <del> return null; <del> <del> // We have already done a fetch of this object, so we read <del> // i_folder_id directly rather than doing a subquery or join <del> // on the object ID. <del> StringBuilder dql = new StringBuilder(); <del> dql.append("select r_folder_path from dm_folder "); <del> dql.append("where r_folder_path is not null and r_object_id in ("); <del> for (int i = 0; i < count; i++) { <del> dql.append('\''); <del> dql.append(object.getRepeatingValue("i_folder_id", i).asString()); <del> dql.append("',"); <del> } <del> dql.setCharAt(dql.length() - 1, ')'); <del> dql.append(" ENABLE (row_based)"); <del> <del> IQuery query = traversalManager.getClientX().getQuery(); <del> query.setDQL(dql.toString()); <del> try { <del> ICollection collec = query.execute(session, IQuery.READ_QUERY); <del> try { <del> while (collec.next()) { <del> values.add( <del> Value.getStringValue(collec.getString("r_folder_path"))); <del> } <del> } finally { <del> collec.close(); <del> } <del> } catch (RepositoryDocumentException e) { <del> logger.warning("RepositoryDocumentException thrown: " + e <del> + " on getting property: " + name); <del> } <del> } else if (SpiConstants.PROPNAME_SECURITYTOKEN.equals(name)) { <del> try { <del> values.add(Value.getStringValue(object.getACLDomain() + " " <del> + object.getACLName())); <del> } catch (RepositoryDocumentException e) { <del> logger.warning("RepositoryDocumentException thrown: " + e <del> + " on getting property: " + name); <del> } <del> } else if (SpiConstants.PROPNAME_ISPUBLIC.equals(name)) { <del> values.add(Value.getBooleanValue(traversalManager.isPublic())); <del> } else if (SpiConstants.PROPNAME_LASTMODIFIED.equals(name)) { <del> if (timeStamp != null) { <del> values.add(Value.getDateValue(getCalendarFromDate(timeStamp.getDate()))); <del> } <del> } else if (SpiConstants.PROPNAME_MIMETYPE.equals(name)) { <del> try { <del> IFormat dctmForm = object.getFormat(); <del> String mimetype = dctmForm.getMIMEType(); <del> logger.fine("mimetype of the document " + versionId + ": " + mimetype); <del> // Modification in order to index empty documents. <del> if (canIndex(false)) { <del> values.add(Value.getStringValue(mimetype)); <del> } <del> } catch (RepositoryDocumentException e) { <del> logger.warning("RepositoryDocumentException thrown: " + e <del> + " on getting property: " + name); <del> } <del> } else if (SpiConstants.PROPNAME_TITLE.equals(name)) { <del> values.add(Value.getStringValue(object.getObjectName())); <del> } else if (name.matches(PROPNAME_REGEXP)) { <del> if (UNSUPPORTED_PROPNAMES.add(name)) { <del> logger.finest("Ignoring unsupported SPI property " + name); <del> } <add> boolean found = findCoreProperty(name, values); <add> if (!found) <add> found = findAddProperty(name, values); <add> if (!found) <ide> return null; <del> } else if (OBJECT_ID_NAME.equals(name)) { <del> values.add(Value.getStringValue(docId)); <del> } else if (name.equals("r_object_type")) { <del> // Retrieves object type and its super type(s). <del> for (IType value = object.getType(); value != null; value = getSuperType(value)) { <del> String typeName = value.getName(); <del> values.add(Value.getStringValue(typeName)); <del> } <del> } else { <del> // TODO: We could store the data types for each attribute in <del> // the type attributes cache, and save about 2% of the <del> // traversal time here by avoiding the calls to findAttrIndex <del> // and getAttr. <del> int attrIndex = object.findAttrIndex(name); <del> if (attrIndex != -1) { <del> IAttr attr = object.getAttr(attrIndex); <del> for (int i = 0, n = object.getValueCount(name); i < n; i++) { <del> IValue val = object.getRepeatingValue(name, i); <del> try { <del> switch (attr.getDataType()) { <del> case IAttr.DM_BOOLEAN: <del> values.add(Value.getBooleanValue(val.asBoolean())); <del> break; <del> case IAttr.DM_DOUBLE: <del> values.add(Value.getDoubleValue(val.asDouble())); <del> break; <del> case IAttr.DM_ID: <del> // TODO: Should we check for null here? <del> values.add(Value.getStringValue(val.asId().getId())); <del> break; <del> case IAttr.DM_INTEGER: <del> values.add(Value.getLongValue(val.asInteger())); <del> break; <del> case IAttr.DM_STRING: <del> values.add(Value.getStringValue(val.asString())); <del> break; <del> case IAttr.DM_TIME: <del> Date date = val.asTime().getDate(); <del> if (date != null) { <del> values.add(Value.getDateValue(getCalendarFromDate(date))); <del> } <del> break; <del> default: <del> // TODO: Should this be an exception, or just logged <del> // directly as a warning? <del> throw new AssertionError(String.valueOf(attr.getDataType())); <del> } <del> } catch (Exception e) { <del> logger.log(Level.WARNING, "error getting the value of index " <del> + i + " of the attribute " + name, e); <del> } <del> } <del> } else { <del> // No property by that name found. <del> return null; <del> } <del> } <del> } else { <del> if (SpiConstants.PROPNAME_ACTION.equals(name)) { <del> values.add(Value.getStringValue(action.toString())); <del> } else if (name.equals(SpiConstants.PROPNAME_DOCID)) { <del> values.add(Value.getStringValue(versionId)); <del> } else if (name.equals(SpiConstants.PROPNAME_LASTMODIFIED)) { <del> if (timeStamp != null) { <del> values.add(Value.getDateValue(getCalendarFromDate(timeStamp.getDate()))); <del> } <del> } else if (OBJECT_ID_NAME.equals(name)) { <del> values.add(Value.getStringValue(docId)); <add> } else { <add> boolean found = findCoreProperty(name, values); <add> if (!found) <add> return null; <add> } <add> <add> if (logger.isLoggable(Level.FINE)) { <add> logger.fine("property " + name + " has the values " + values); <add> } <add> return values.isEmpty() ? null : new SimpleProperty(values); <add> } <add> <add> /** <add> * Adds the values for the named property to the list. The <add> * properties handled by this method are always available, for both <add> * add and delete actions. <add> * <add> * @param name a property name <add> * @param values the empty list to add values to <add> * @return true if values were added to the list <add> * @throws RepositoryException if an unexpected error occurs <add> */ <add> private boolean findCoreProperty(String name, List<Value> values) <add> throws RepositoryException { <add> if (SpiConstants.PROPNAME_ACTION.equals(name)) { <add> values.add(Value.getStringValue(action.toString())); <add> } else if (name.equals(SpiConstants.PROPNAME_DOCID)) { <add> values.add(Value.getStringValue(versionId)); <add> } else if (name.equals(SpiConstants.PROPNAME_LASTMODIFIED)) { <add> if (timeStamp == null) { <add> return false; <add> } <add> values.add(Value.getDateValue( <add> getCalendarFromDate(timeStamp.getDate()))); <add> } else { <add> // No property by that name found. <add> return false; <add> } <add> return true; <add> } <add> <add> /** <add> * Adds the values for the named property to the list. The <add> * properties handled by this method are available only for the add <add> * action. A fetched SysObject is used to obtain the values. <add> * <add> * @param name a property name <add> * @param values the empty list to add values to <add> * @return true if values were added to the list <add> * @throws RepositoryException if an unexpected error occurs <add> */ <add> /* TODO: Should we unify the RepositoryDocumentException handling? */ <add> private boolean findAddProperty(String name, List<Value> values) <add> throws RepositoryException { <add> if (SpiConstants.PROPNAME_CONTENT.equals(name)) { <add> try { <add> if (canIndex(true)) { <add> values.add(Value.getBinaryValue(object.getContent())); <add> } <add> } catch (RepositoryDocumentException e) { <add> // FIXME: In the unlikely event the user only has BROWSE <add> // permission for a document, we'll end up here. That's <add> // fine, but the google:mimetype property will not be reset <add> // to "text/plain" in that case. <add> logger.warning("RepositoryDocumentException thrown: " + e <add> + " on getting property: " + name); <add> } <add> } else if (SpiConstants.PROPNAME_DISPLAYURL.equals(name)) { <add> String displayUrl = traversalManager.getServerUrl() + docId; <add> values.add(Value.getStringValue(displayUrl)); <add> } else if (PROPNAME_FOLDER.equals(name)) { <add> // TODO: SpiConstants.PROPNAME_FOLDER in CM 3.0. <add> return findFolderProperty(name, values); <add> } else if (SpiConstants.PROPNAME_SECURITYTOKEN.equals(name)) { <add> try { <add> values.add(Value.getStringValue(object.getACLDomain() + " " <add> + object.getACLName())); <add> } catch (RepositoryDocumentException e) { <add> logger.warning("RepositoryDocumentException thrown: " + e <add> + " on getting property: " + name); <add> } <add> } else if (SpiConstants.PROPNAME_ISPUBLIC.equals(name)) { <add> values.add(Value.getBooleanValue(traversalManager.isPublic())); <add> } else if (SpiConstants.PROPNAME_MIMETYPE.equals(name)) { <add> try { <add> IFormat dctmForm = object.getFormat(); <add> String mimetype = dctmForm.getMIMEType(); <add> logger.fine("mimetype of the document " + versionId + ": " + mimetype); <add> // The GSA will not index empty documents with binary content types, <add> // so omit the content type if the document cannot be indexed. <add> if (canIndex(false)) { <add> values.add(Value.getStringValue(mimetype)); <add> } <add> } catch (RepositoryDocumentException e) { <add> logger.warning("RepositoryDocumentException thrown: " + e <add> + " on getting property: " + name); <add> } <add> } else if (SpiConstants.PROPNAME_TITLE.equals(name)) { <add> values.add(Value.getStringValue(object.getObjectName())); <add> } else if (name.matches(PROPNAME_REGEXP)) { <add> if (UNSUPPORTED_PROPNAMES.add(name)) { <add> logger.finest("Ignoring unsupported SPI property " + name); <add> } <add> return false; <add> } else { <add> return findDctmAttribute(name, values); <add> } <add> <add> return true; <add> } <add> <add> /** <add> * Adds the values for the folder paths to the list. <add> * <add> * @param name a property name <add> * @param values the empty list to add values to <add> * @return true if values were added to the list <add> * @throws RepositoryException if an unexpected error occurs <add> */ <add> private boolean findFolderProperty(String name, List<Value> values) <add> throws RepositoryException { <add> // We have already done a fetch of this object, so we read <add> // i_folder_id directly rather than doing a subquery or join <add> // on the object ID. <add> int count = object.getValueCount("i_folder_id"); <add> if (count == 0) <add> return false; <add> <add> StringBuilder dql = new StringBuilder(); <add> dql.append("select r_folder_path from dm_folder "); <add> dql.append("where r_folder_path is not null and r_object_id in ("); <add> for (int i = 0; i < count; i++) { <add> dql.append('\''); <add> dql.append(object.getRepeatingValue("i_folder_id", i).asString()); <add> dql.append("',"); <add> } <add> dql.setCharAt(dql.length() - 1, ')'); <add> dql.append(" ENABLE (row_based)"); <add> <add> IQuery query = traversalManager.getClientX().getQuery(); <add> query.setDQL(dql.toString()); <add> try { <add> ICollection collec = query.execute(session, IQuery.READ_QUERY); <add> try { <add> while (collec.next()) { <add> values.add( <add> Value.getStringValue(collec.getString("r_folder_path"))); <add> } <add> } finally { <add> collec.close(); <add> } <add> } catch (RepositoryDocumentException e) { <add> logger.warning("RepositoryDocumentException thrown: " + e <add> + " on getting property: " + name); <add> } <add> <add> return true; <add> } <add> <add> /** <add> * Adds the values for a Documentum attribute to the list. <add> * <add> * @param name a attribute name <add> * @param values the empty list to add values to <add> * @return true if values were added to the list <add> * @throws RepositoryException if an unexpected error occurs <add> */ <add> private boolean findDctmAttribute(String name, List<Value> values) <add> throws RepositoryException { <add> if (OBJECT_ID_NAME.equals(name)) { <add> values.add(Value.getStringValue(docId)); <add> } else if (name.equals("r_object_type")) { <add> // Retrieves object type and its super type(s). <add> for (IType value = object.getType(); <add> value != null; <add> value = getSuperType(value)) { <add> String typeName = value.getName(); <add> values.add(Value.getStringValue(typeName)); <add> } <add> } else { <add> // TODO: We could store the data types for each attribute in <add> // the type attributes cache, and save about 2% of the <add> // traversal time here by avoiding the calls to findAttrIndex <add> // and getAttr. <add> int attrIndex = object.findAttrIndex(name); <add> if (attrIndex != -1) { <add> IAttr attr = object.getAttr(attrIndex); <add> getDctmAttribute(name, attr.getDataType(), values); <ide> } else { <ide> // No property by that name found. <del> return null; <del> } <del> } <del> <del> if (logger.isLoggable(Level.FINE)) { <del> logger.fine("property " + name + " has the values " + values); <del> } <del> return new SimpleProperty(values); <add> return false; <add> } <add> } <add> <add> return true; <add> } <add> <add> /** <add> * Helper method that values for a Documentum attribute to the list. <add> * <add> * @param name an attribute name <add> * @param dataType the data type of the attribute <add> * @param values the empty list to add values to <add> * @throws RepositoryException if an unexpected error occurs <add> */ <add> private void getDctmAttribute(String name, int dataType, List<Value> values) <add> throws RepositoryException { <add> for (int i = 0, n = object.getValueCount(name); i < n; i++) { <add> IValue val = object.getRepeatingValue(name, i); <add> try { <add> switch (dataType) { <add> case IAttr.DM_BOOLEAN: <add> values.add(Value.getBooleanValue(val.asBoolean())); <add> break; <add> case IAttr.DM_DOUBLE: <add> values.add(Value.getDoubleValue(val.asDouble())); <add> break; <add> case IAttr.DM_ID: <add> // TODO: Should we check for null here? <add> values.add(Value.getStringValue(val.asId().getId())); <add> break; <add> case IAttr.DM_INTEGER: <add> values.add(Value.getLongValue(val.asInteger())); <add> break; <add> case IAttr.DM_STRING: <add> values.add(Value.getStringValue(val.asString())); <add> break; <add> case IAttr.DM_TIME: <add> Date date = val.asTime().getDate(); <add> if (date != null) { <add> values.add(Value.getDateValue(getCalendarFromDate(date))); <add> } <add> break; <add> default: <add> // TODO: Should this be an exception, or just logged <add> // directly as a warning? <add> throw new AssertionError(String.valueOf(dataType)); <add> } <add> } catch (Exception e) { <add> logger.log(Level.WARNING, "error getting the value of index " <add> + i + " of the attribute " + name, e); <add> } <add> } <ide> } <ide> <ide> /** <ide> String typeName = type.getName(); <ide> if (superTypes.containsKey(typeName)) <ide> return superTypes.get(typeName); <del> IType superType = type.getSuperType(); <del> superTypes.put(typeName, superType); <del> return superType; <add> else { <add> IType superType = type.getSuperType(); <add> superTypes.put(typeName, superType); <add> return superType; <add> } <ide> } <ide> <ide> /** <ide> } <ide> <ide> public Set<String> getPropertyNames() throws RepositoryException { <del> Set<String> properties = null; <add> Set<String> properties; <ide> if (ActionType.ADD.equals(action)) { <ide> fetch(); <ide> properties = new HashSet<String>(); <ide> List<String> typeAttributes = getTypeAttributes(object.getType()); <ide> properties.addAll(typeAttributes); <ide> } else { <add> // XXX: This is dead code. The CM never asks for the property <add> // names for delete actions. Does it matter? <ide> properties = new HashSet<String>(); <ide> properties.add(SpiConstants.PROPNAME_ACTION); <ide> properties.add(SpiConstants.PROPNAME_DOCID); <ide> properties.add(SpiConstants.PROPNAME_LASTMODIFIED); <del> properties.add(OBJECT_ID_NAME); <ide> } <ide> return properties; <ide> }
JavaScript
mit
ccd78b3a2a4740c2adbc35b19f44f7f7fd82a440
0
sensortower/daterangepicker,sensortower/daterangepicker
// generated using generator-gulp-webapp 1.0.3 import gulp from 'gulp'; import coffee from 'gulp-coffee'; import gutil from 'gulp-util'; import include from 'gulp-include'; import gulpLoadPlugins from 'gulp-load-plugins'; import browserSync from 'browser-sync'; import del from 'del'; const $ = gulpLoadPlugins(); const reload = browserSync.reload; gulp.task('styles', () => { return gulp.src([ 'src/styles/*.scss', 'app/styles/*.scss' ]) .pipe($.plumber()) .pipe($.sass.sync({ outputStyle: 'expanded', precision: 10, includePaths: ['.'] }).on('error', gutil.log)) .pipe($.autoprefixer({browsers: ['last 1 version']})) .pipe(gulp.dest('.tmp/styles')) .pipe(reload({stream: true})); }); gulp.task('scripts', () => { return gulp.src([ 'src/scripts/*.coffee', 'app/scripts/*.coffee' ]) .pipe(include()).on('error', gutil.log) .pipe($.plumber()) .pipe(coffee({bare: true}).on('error', gutil.log)) .pipe(gulp.dest('.tmp/scripts')) .pipe(reload({stream: true})); }); gulp.task('html', ['styles', 'scripts'], () => { const assets = $.useref.assets({searchPath: ['.tmp', 'app', '.']}); return gulp.src('app/*.html') .pipe(assets) .pipe($.if('*.js', $.uglify())) .pipe($.if('*.css', $.minifyCss({compatibility: '*'}))) .pipe(assets.restore()) .pipe($.useref()) .pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true}))) .pipe(gulp.dest('dist')); }); gulp.task('clean', del.bind(null, ['.tmp', 'dist'])); gulp.task('serve', ['styles', 'scripts'], () => { browserSync({ notify: false, port: 9000, ghostMode: { clicks: false, forms: false, scroll: false }, server: { baseDir: ['.tmp', 'app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'src/scripts/**/*.coffee', 'src/templates/**/*.html', 'app/scripts/**/*.coffee' ]).on('change', reload); gulp.watch('src/styles/**/*.scss', ['styles']); gulp.watch('app/styles/**/*.scss', ['styles']); gulp.watch('src/scripts/**/*.coffee', ['scripts']); gulp.watch('src/templates/**/*.html', ['scripts']); gulp.watch('app/scripts/**/*.coffee', ['scripts']); }); gulp.task('build', ['html', 'scripts', 'styles'], () => { return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true})); }); gulp.task('default', ['clean'], () => { gulp.start('build'); });
gulpfile.babel.js
// generated using generator-gulp-webapp 1.0.3 import gulp from 'gulp'; import coffee from 'gulp-coffee'; import gutil from 'gulp-util'; import include from 'gulp-include'; import gulpLoadPlugins from 'gulp-load-plugins'; import browserSync from 'browser-sync'; import del from 'del'; const $ = gulpLoadPlugins(); const reload = browserSync.reload; gulp.task('styles', () => { return gulp.src([ 'src/styles/*.scss', 'app/styles/*.scss' ]) .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe($.sass.sync({ outputStyle: 'expanded', precision: 10, includePaths: ['.'] }).on('error', gutil.log)) .pipe($.autoprefixer({browsers: ['last 1 version']})) .pipe($.sourcemaps.write()) .pipe(gulp.dest('.tmp/styles')) .pipe(reload({stream: true})); }); gulp.task('scripts', () => { return gulp.src([ 'src/scripts/*.coffee', 'app/scripts/*.coffee' ]) .pipe(include()).on('error', gutil.log) .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe(coffee({bare: true}).on('error', gutil.log)) .pipe(gulp.dest('.tmp/scripts')) .pipe(reload({stream: true})); }); gulp.task('html', ['styles', 'scripts'], () => { const assets = $.useref.assets({searchPath: ['.tmp', 'app', '.']}); return gulp.src('app/*.html') .pipe(assets) .pipe($.if('*.js', $.uglify())) .pipe($.if('*.css', $.minifyCss({compatibility: '*'}))) .pipe(assets.restore()) .pipe($.useref()) .pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true}))) .pipe(gulp.dest('dist')); }); gulp.task('clean', del.bind(null, ['.tmp', 'dist'])); gulp.task('serve', ['styles', 'scripts'], () => { browserSync({ notify: false, port: 9000, ghostMode: { clicks: false, forms: false, scroll: false }, server: { baseDir: ['.tmp', 'app'], routes: { '/bower_components': 'bower_components' } } }); gulp.watch([ 'app/*.html', 'src/scripts/**/*.coffee', 'src/templates/**/*.html', 'app/scripts/**/*.coffee' ]).on('change', reload); gulp.watch('src/styles/**/*.scss', ['styles']); gulp.watch('app/styles/**/*.scss', ['styles']); gulp.watch('src/scripts/**/*.coffee', ['scripts']); gulp.watch('src/templates/**/*.html', ['scripts']); gulp.watch('app/scripts/**/*.coffee', ['scripts']); }); gulp.task('build', ['html', 'scripts', 'styles'], () => { return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true})); }); gulp.task('default', ['clean'], () => { gulp.start('build'); });
disabled sourcemaps
gulpfile.babel.js
disabled sourcemaps
<ide><path>ulpfile.babel.js <ide> 'app/styles/*.scss' <ide> ]) <ide> .pipe($.plumber()) <del> .pipe($.sourcemaps.init()) <ide> .pipe($.sass.sync({ <ide> outputStyle: 'expanded', <ide> precision: 10, <ide> includePaths: ['.'] <ide> }).on('error', gutil.log)) <ide> .pipe($.autoprefixer({browsers: ['last 1 version']})) <del> .pipe($.sourcemaps.write()) <ide> .pipe(gulp.dest('.tmp/styles')) <ide> .pipe(reload({stream: true})); <ide> }); <ide> ]) <ide> .pipe(include()).on('error', gutil.log) <ide> .pipe($.plumber()) <del> .pipe($.sourcemaps.init()) <ide> .pipe(coffee({bare: true}).on('error', gutil.log)) <ide> .pipe(gulp.dest('.tmp/scripts')) <ide> .pipe(reload({stream: true}));
Java
mit
e398c5035b29b6e409f6a46c48ace7c9da4fcbde
0
mzmine/mzmine3,mzmine/mzmine3
/* * Copyright 2006-2008 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 * MZmine; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peakpicking.threestep.massdetection; import net.sf.mzmine.data.DataPoint; import net.sf.mzmine.data.Peak; import net.sf.mzmine.data.PeakStatus; import net.sf.mzmine.data.RawDataFile; import net.sf.mzmine.util.Range; /** * * This class is only used for visualization terms by MassDetectorSetupDialog. * */ class FakePeak implements Peak { private DataPoint datapoint; private Range mzRange, intensityRange; private int scanNumber; /** * * @param scanNumber * @param datapoint */ public FakePeak(int scanNumber, DataPoint datapoint) { this.datapoint = datapoint; this.scanNumber = scanNumber; mzRange = new Range(datapoint.getMZ()); intensityRange = new Range(datapoint.getIntensity()); } public float getArea() { return 0; } public RawDataFile getDataFile() { return null; } public DataPoint getDataPoint(int scanNumber) { return datapoint; } public float getHeight() { return 0; } public float getMZ() { return 0; } public PeakStatus getPeakStatus() { return null; } public float getRT() { return 0; } public DataPoint[] getRawDataPoints(int scanNumber) { return null; } public Range getRawDataPointsIntensityRange() { return intensityRange; } public Range getRawDataPointsMZRange() { return mzRange; } public Range getRawDataPointsRTRange() { return null; } public int[] getScanNumbers() { int scanNumbers[] = { scanNumber }; return scanNumbers; } }
src/net/sf/mzmine/modules/peakpicking/threestep/massdetection/FakePeak.java
/* * Copyright 2006-2008 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 * MZmine; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peakpicking.threestep.massdetection; import net.sf.mzmine.data.DataPoint; import net.sf.mzmine.data.Peak; import net.sf.mzmine.data.PeakStatus; import net.sf.mzmine.data.RawDataFile; import net.sf.mzmine.util.Range; /** * * This class is only used for visualization terms by MassDetectorSetupDialog. * */ class FakePeak implements Peak { private DataPoint datapoint; private Range mzRange, intensityRange; private int scanNumber; /** * * @param scanNumber * @param datapoint */ public FakePeak(int scanNumber, DataPoint datapoint) { super(); this.datapoint = datapoint; this.scanNumber = scanNumber; mzRange = new Range(datapoint.getMZ()); intensityRange = new Range(datapoint.getIntensity()); } public float getArea() { return 0; } public RawDataFile getDataFile() { return null; } public DataPoint getDataPoint(int scanNumber) { return datapoint; } public float getHeight() { return 0; } public float getMZ() { return 0; } public PeakStatus getPeakStatus() { return null; } public float getRT() { return 0; } public DataPoint[] getRawDataPoints(int scanNumber) { return null; } public Range getRawDataPointsIntensityRange() { return intensityRange; } public Range getRawDataPointsMZRange() { return mzRange; } public Range getRawDataPointsRTRange() { return null; } public int[] getScanNumbers() { int scanNumbers[] = { scanNumber }; return scanNumbers; } public void setMZ(float mz) { // TODO Auto-generated method stub } }
Cleanup
src/net/sf/mzmine/modules/peakpicking/threestep/massdetection/FakePeak.java
Cleanup
<ide><path>rc/net/sf/mzmine/modules/peakpicking/threestep/massdetection/FakePeak.java <ide> * @param datapoint <ide> */ <ide> public FakePeak(int scanNumber, DataPoint datapoint) { <del> super(); <ide> this.datapoint = datapoint; <ide> this.scanNumber = scanNumber; <ide> mzRange = new Range(datapoint.getMZ()); <ide> return scanNumbers; <ide> } <ide> <del> public void setMZ(float mz) { <del> // TODO Auto-generated method stub <del> <del> } <del> <ide> }
Java
apache-2.0
333060bebb07eb7cd4d0654dbfba742ba5bbd5dd
0
rcordovano/autopsy,millmanorama/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,millmanorama/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,esaunders/autopsy,wschaeferB/autopsy,millmanorama/autopsy,millmanorama/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy
/* * * Autopsy Forensic Browser * * Copyright 2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.commonfilesearch; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.openide.util.NbBundle; /** * Manager for present state of errors on the Common Files Search. */ class UserInputErrorManager { static final int FREQUENCY_PERCENTAGE_OUT_OF_RANGE_KEY = 1; static final int NO_FILE_CATEGORIES_SELECTED_KEY = 2; private final Map<Integer, ErrorMessage> currentErrors; /** * Construct a new ErrorManager which can be used to track the status * of all known error states, retrieve error messages, and determine if * anything is in an error state. */ @NbBundle.Messages({ "UserInputErrorManager.frequency=Invalid Frequency Percentage: 0 < % < 100.", "UserInputErrorManager.categories=No file categories are included in the search."}) UserInputErrorManager (){ //when new errors are needed for the dialog, define a key and a value // and add them to the map. this.currentErrors = new HashMap<>(); this.currentErrors.put(FREQUENCY_PERCENTAGE_OUT_OF_RANGE_KEY, new ErrorMessage(Bundle.UserInputErrorManager_frequency())); this.currentErrors.put(NO_FILE_CATEGORIES_SELECTED_KEY, new ErrorMessage(Bundle.UserInputErrorManager_categories())); } /** * Toggle the given error message on, or off * @param errorId the error to toggle * @param errorState true for on, false for off */ void setError(int errorId, boolean errorState){ if(this.currentErrors.containsKey(errorId)){ this.currentErrors.get(errorId).setStatus(errorState); } else { throw new IllegalArgumentException(String.format("The given errorId is not mapped to an ErrorMessage: %s.", errorId)); } } /** * Are any user settings presently in an error state? * @return true for yes, else false */ boolean anyErrors(){ return this.currentErrors.values().stream().anyMatch(errorMessage -> errorMessage.isErrorSet() == true); } /** * Get a list of distinct string messages describing the various error states. */ List<String> getErrors(){ return this.currentErrors.values().stream() .filter(errorMessage -> errorMessage.isErrorSet() == true) .map(ErrorMessage::getMessage) .collect(Collectors.toList()); } /** * Represents an error message for the CommonFilesSearch panel, it's * uniqueId, and it's status. */ private class ErrorMessage { private final String message; private boolean status; /** * Create a message with a unique uniqueId. Default status is false (off). * @param uniqueId unique uniqueId * @param message message to display */ ErrorMessage(String message){ this.message = message; this.status = false; } /** * Update the status of this message * @param status */ void setStatus(boolean status){ this.status = status; } /** * Return the message * @return */ String getMessage(){ return this.message; } /** * Return the status (true for error status, false for no error) * @return */ boolean isErrorSet(){ return this.status; } } }
Core/src/org/sleuthkit/autopsy/commonfilesearch/UserInputErrorManager.java
/* * * Autopsy Forensic Browser * * Copyright 2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.commonfilesearch; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Manager for present state of errors on the Common Files Search. */ class UserInputErrorManager { static final int FREQUENCY_PERCENTAGE_OUT_OF_RANGE_KEY = 1; static final int NO_FILE_CATEGORIES_SELECTED_KEY = 2; private final Map<Integer, ErrorMessage> currentErrors; /** * Construct a new ErrorManager which can be used to track the status * of all known error states, retrieve error messages, and determine if * anything is in an error state. */ UserInputErrorManager (){ //when new errors are needed for the dialog, define a key and a value // and add them to the map. this.currentErrors = new HashMap<>(); this.currentErrors.put(FREQUENCY_PERCENTAGE_OUT_OF_RANGE_KEY, new ErrorMessage("Invalid Frequency Percentage: 0 < % < 100.")); this.currentErrors.put(NO_FILE_CATEGORIES_SELECTED_KEY, new ErrorMessage("No file categories are included in the search.")); } /** * Toggle the given error message on, or off * @param errorId the error to toggle * @param errorState true for on, false for off */ void setError(int errorId, boolean errorState){ if(this.currentErrors.containsKey(errorId)){ this.currentErrors.get(errorId).setStatus(errorState); } else { throw new IllegalArgumentException(String.format("The given errorId is not mapped to an ErrorMessage: %s.", errorId)); } } /** * Are any user settings presently in an error state? * @return true for yes, else false */ boolean anyErrors(){ return this.currentErrors.values().stream().anyMatch(errorMessage -> errorMessage.isErrorSet() == true); } /** * Get a list of distinct string messages describing the various error states. */ List<String> getErrors(){ return this.currentErrors.values().stream() .filter(errorMessage -> errorMessage.isErrorSet() == true) .map(ErrorMessage::getMessage) .collect(Collectors.toList()); } /** * Represents an error message for the CommonFilesSearch panel, it's * uniqueId, and it's status. */ private class ErrorMessage { private final String message; private boolean status; /** * Create a message with a unique uniqueId. Default status is false (off). * @param uniqueId unique uniqueId * @param message message to display */ ErrorMessage(String message){ this.message = message; this.status = false; } /** * Update the status of this message * @param status */ void setStatus(boolean status){ this.status = status; } /** * Return the message * @return */ String getMessage(){ return this.message; } /** * Return the status (true for error status, false for no error) * @return */ boolean isErrorSet(){ return this.status; } } }
ui text added to bundles
Core/src/org/sleuthkit/autopsy/commonfilesearch/UserInputErrorManager.java
ui text added to bundles
<ide><path>ore/src/org/sleuthkit/autopsy/commonfilesearch/UserInputErrorManager.java <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.stream.Collectors; <add>import org.openide.util.NbBundle; <ide> <ide> /** <ide> * Manager for present state of errors on the Common Files Search. <ide> * of all known error states, retrieve error messages, and determine if <ide> * anything is in an error state. <ide> */ <add> @NbBundle.Messages({ <add> "UserInputErrorManager.frequency=Invalid Frequency Percentage: 0 < % < 100.", <add> "UserInputErrorManager.categories=No file categories are included in the search."}) <ide> UserInputErrorManager (){ <ide> <ide> //when new errors are needed for the dialog, define a key and a value <ide> // and add them to the map. <ide> <ide> this.currentErrors = new HashMap<>(); <del> this.currentErrors.put(FREQUENCY_PERCENTAGE_OUT_OF_RANGE_KEY, new ErrorMessage("Invalid Frequency Percentage: 0 < % < 100.")); <del> this.currentErrors.put(NO_FILE_CATEGORIES_SELECTED_KEY, new ErrorMessage("No file categories are included in the search.")); <add> this.currentErrors.put(FREQUENCY_PERCENTAGE_OUT_OF_RANGE_KEY, new ErrorMessage(Bundle.UserInputErrorManager_frequency())); <add> this.currentErrors.put(NO_FILE_CATEGORIES_SELECTED_KEY, new ErrorMessage(Bundle.UserInputErrorManager_categories())); <ide> } <ide> <ide> /**
Java
mit
4792c05a9e9d5043689ba1fea216df84bccb206f
0
colus001/Bean-Android-SDK,androidgrl/Bean-Android-SDK,swstack/Bean-Android-SDK,PunchThrough/Bean-Android-SDK,colus001/Bean-Android-SDK,PunchThrough/bean-sdk-android,hongbinz/Bean-Android-SDK,hongbinz/Bean-Android-SDK,PunchThrough/Bean-Android-SDK,PunchThrough/bean-sdk-android,androidgrl/Bean-Android-SDK,swstack/Bean-Android-SDK
package com.punchthrough.bean.sdk.internal.ble; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.content.Context; import com.punchthrough.bean.sdk.internal.battery.BatteryProfile; import com.punchthrough.bean.sdk.internal.device.DeviceProfile; import com.punchthrough.bean.sdk.internal.exception.MetadataParsingException; import com.punchthrough.bean.sdk.internal.serial.GattSerialTransportProfile; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareChunk; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareImageType; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareMetadata; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareUploadState; import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.Callback; import com.punchthrough.bean.sdk.message.UploadProgress; import com.punchthrough.bean.sdk.upload.FirmwareBundle; import com.punchthrough.bean.sdk.upload.FirmwareImage; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; public class GattClient { private static final String TAG = "GattClient"; private final GattSerialTransportProfile mSerialProfile; private final DeviceProfile mDeviceProfile; private final BatteryProfile mBatteryProfile; private BluetoothGatt mGatt; private List<BaseProfile> mProfiles = new ArrayList<>(10); private Queue<Runnable> mOperationsQueue = new ArrayDeque<>(32); private boolean mOperationInProgress = false; private boolean mConnected = false; private boolean mDiscoveringServices = false; // These class variables are used for firmware uploads. /** * The maximum time, in ms, the client will wait for an update from the Bean before aborting the * firmware upload process and throwing an error */ private static final int FIRMWARE_UPLOAD_TIMEOUT = 3000; /** * The OAD Service contains the OAD Identify and Block characteristics */ private static final UUID SERVICE_OAD = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); /** * The OAD Identify characteristic is used to negotiate the start of a firmware transfer */ private static final UUID CHAR_OAD_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); /** * The OAD Block characteristic is used to send firmware chunks and confirm transfer completion */ private static final UUID CHAR_OAD_BLOCK = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); /** * The OAD Identify characteristic for this device. Assigned when firmware upload is started. */ private BluetoothGattCharacteristic oadIdentify; /** * The OAD Block characteristic for this device. Assigned when firmware upload is started. */ private BluetoothGattCharacteristic oadBlock; /** * True if the OAD Identify characteristic is notifying, false otherwise */ private boolean oadIdentifyNotifying = false; /** * True if the OAD Block characteristic is notifying, false otherwise */ private boolean oadBlockNotifying = false; /** * State of the current firmware upload process. */ private FirmwareUploadState firmwareUploadState = FirmwareUploadState.INACTIVE; /** * Aborts firmware upload and throws an error if we go too long without a response from the CC. */ private Timer firmwareStateTimeout; /** * Firmware bundle with A and B images to send */ FirmwareBundle firmwareBundle; /** * Chunks of firmware to be sent in order */ private List<FirmwareChunk> fwChunksToSend; /** * Firmware chunk counter. The packet ID must be incremented for each chunk that is sent. */ private int currFwPacketNum = 0; /** * Called to inform the Bean class when firmware upload progress is made. */ private Callback<UploadProgress> onProgress; /** * Called to inform the Bean class when firmware upload is complete. */ private Runnable onComplete; /** * Called when an error causes the firmware upload to fail. */ private Callback<BeanError> onError; private final BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (status != BluetoothGatt.GATT_SUCCESS) { fireConnectionStateChange(BluetoothGatt.STATE_DISCONNECTED); disconnect(); return; } if (newState == BluetoothGatt.STATE_CONNECTED) { mConnected = true; } fireConnectionStateChange(newState); } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { mDiscoveringServices = false; if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireServicesDiscovered(); } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } if (uploadInProgress()) { if (isOADIdentifyCharacteristic(characteristic)) { resetFirmwareStateTimeout(); if (firmwareUploadState == FirmwareUploadState.AWAIT_CURRENT_HEADER) { prepareResponseHeader(characteristic.getValue()); } else if (firmwareUploadState == FirmwareUploadState.AWAIT_XFER_ACCEPT) { // Existing header read, new header sent, Identify pinged -> // Bean rejected firmware version throwBeanError(BeanError.BEAN_REJECTED_FW); } } else if (isOADBlockCharacteristic(characteristic)) { if (firmwareUploadState == FirmwareUploadState.AWAIT_XFER_ACCEPT) { // Existing header read, new header sent, Block pinged -> // Bean accepted firmware version, begin transfer // TODO: Begin transfer } } } fireCharacteristicsRead(characteristic); executeNextOperation(); } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireCharacteristicWrite(characteristic); executeNextOperation(); } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { if (uploadInProgress() && isOADCharacteristic(characteristic)) { mGatt.readCharacteristic(characteristic); } fireCharacteristicChanged(characteristic); } @Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireDescriptorRead(descriptor); executeNextOperation(); } @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireDescriptorWrite(descriptor); executeNextOperation(); } @Override public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); } } }; public GattClient() { mSerialProfile = new GattSerialTransportProfile(this); mDeviceProfile = new DeviceProfile(this); mBatteryProfile = new BatteryProfile(this); mProfiles.add(mSerialProfile); mProfiles.add(mDeviceProfile); mProfiles.add(mBatteryProfile); } private void fireDescriptorRead(BluetoothGattDescriptor descriptor) { for (BaseProfile profile : mProfiles) { profile.onDescriptorRead(this, descriptor); } } private synchronized void queueOperation(Runnable operation) { mOperationsQueue.offer(operation); if (!mOperationInProgress) { executeNextOperation(); } } private synchronized void executeNextOperation() { Runnable operation = mOperationsQueue.poll(); if (operation != null) { mOperationInProgress = true; operation.run(); } else { mOperationInProgress = false; } } public void connect(Context context, BluetoothDevice device) { if (mGatt != null) { mGatt.disconnect(); mGatt.close(); } mConnected = false; mGatt = device.connectGatt(context, false, mBluetoothGattCallback); } private void fireDescriptorWrite(BluetoothGattDescriptor descriptor) { for (BaseProfile profile : mProfiles) { profile.onDescriptorWrite(this, descriptor); } } private void fireCharacteristicChanged(BluetoothGattCharacteristic characteristic) { for (BaseProfile profile : mProfiles) { profile.onCharacteristicChanged(this, characteristic); } } private void fireCharacteristicWrite(BluetoothGattCharacteristic characteristic) { for (BaseProfile profile : mProfiles) { profile.onCharacteristicWrite(this, characteristic); } } private void fireCharacteristicsRead(BluetoothGattCharacteristic characteristic) { for (BaseProfile profile : mProfiles) { profile.onCharacteristicRead(this, characteristic); } } private void fireServicesDiscovered() { for (BaseProfile profile : mProfiles) { profile.onServicesDiscovered(this); } } private synchronized void fireConnectionStateChange(int newState) { if (newState == BluetoothGatt.STATE_DISCONNECTED) { mOperationsQueue.clear(); mOperationInProgress = false; mConnected = false; } else if (newState == BluetoothGatt.STATE_CONNECTED) { mConnected = true; } for (BaseProfile profile : mProfiles) { profile.onConnectionStateChange(newState); } } public List<BluetoothGattService> getServices() { return mGatt.getServices(); } public BluetoothGattService getService(UUID uuid) { return mGatt.getService(uuid); } public boolean discoverServices() { if (mDiscoveringServices) { return true; } mDiscoveringServices = true; return mGatt.discoverServices(); } public synchronized boolean readCharacteristic(final BluetoothGattCharacteristic characteristic) { queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { mGatt.readCharacteristic(characteristic); } } }); return true; } public synchronized boolean writeCharacteristic(final BluetoothGattCharacteristic characteristic) { final byte[] value = characteristic.getValue(); queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { characteristic.setValue(value); mGatt.writeCharacteristic(characteristic); } } }); return true; } public boolean readDescriptor(final BluetoothGattDescriptor descriptor) { queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { mGatt.readDescriptor(descriptor); } } }); return true; } public boolean writeDescriptor(final BluetoothGattDescriptor descriptor) { final byte[] value = descriptor.getValue(); queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { descriptor.setValue(value); mGatt.writeDescriptor(descriptor); } } }); return true; } public boolean readRemoteRssi() { return mGatt.readRemoteRssi(); } public boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) { return mGatt.setCharacteristicNotification(characteristic, enable); } private boolean connect() { return mGatt != null && mGatt.connect(); } public void disconnect() { close(); throwBeanError(BeanError.UNKNOWN); } private synchronized void close() { if (mGatt != null) { mGatt.close(); } mGatt = null; } public GattSerialTransportProfile getSerialProfile() { return mSerialProfile; } public DeviceProfile getDeviceProfile() { return mDeviceProfile; } public BatteryProfile getBatteryProfile() { return mBatteryProfile; } public void programWithFirmware(FirmwareBundle bundle, Callback<UploadProgress> onProgress, Runnable onComplete, Callback<BeanError> onError) { // Ensure Bean is connected and services have been discovered if (!mConnected) { onError.onResult(BeanError.NOT_CONNECTED); } if (mGatt.getServices() == null) { onError.onResult(BeanError.SERVICES_NOT_DISCOVERED); } // Set event handlers this.onProgress = onProgress; this.onComplete = onComplete; this.onError = onError; // Save firmware bundle so we have both images when response header is received this.firmwareBundle = bundle; verifyNotifyEnabled(); } private void resetFirmwareUploadState() { firmwareUploadState = FirmwareUploadState.INACTIVE; stopFirmwareStateTimeout(); } private void verifyNotifyEnabled() { // Ensure all characteristics are discovered and notifying if (oadIdentify != null && oadBlock != null && oadIdentifyNotifying && oadBlockNotifying) { requestCurrentHeader(); } else { enableOADNotifications(); } } private void enableOADNotifications() { firmwareUploadState = FirmwareUploadState.AWAIT_NOTIFY_ENABLED; BluetoothGattService oadService = mGatt.getService(SERVICE_OAD); if (oadService == null) { throwBeanError(BeanError.MISSING_OAD_SERVICE); return; } oadIdentify = oadService.getCharacteristic(CHAR_OAD_IDENTIFY); if (oadIdentify == null) { throwBeanError(BeanError.MISSING_OAD_IDENTIFY); return; } oadBlock = oadService.getCharacteristic(CHAR_OAD_BLOCK); if (oadBlock == null) { throwBeanError(BeanError.MISSING_OAD_BLOCK); return; } oadIdentifyNotifying = enableNotifyForChar(oadIdentify); oadBlockNotifying = enableNotifyForChar(oadBlock); if (oadIdentifyNotifying && oadBlockNotifying) { requestCurrentHeader(); } else { throwBeanError(BeanError.ENABLE_OAD_NOTIFY_FAILED); } } // https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) { boolean result = mGatt.setCharacteristicNotification(characteristic, true); String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"; BluetoothGattDescriptor descriptor = characteristic.getDescriptor( UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mGatt.writeDescriptor(descriptor); return result; } private void requestCurrentHeader() { firmwareUploadState = FirmwareUploadState.AWAIT_CURRENT_HEADER; // To request the current header, write [0x00] to OAD Identify writeToCharacteristic(oadIdentify, new byte[]{0x00}); } private void prepareResponseHeader(byte[] rawRequestHeader) { FirmwareMetadata existingMeta; try { existingMeta = FirmwareMetadata.fromPayload(rawRequestHeader); } catch (MetadataParsingException e) { throwBeanError(BeanError.UNPARSABLE_FW_METADATA); return; } // TODO: Check FW to flash's version against existing FW FirmwareImageType type = existingMeta.type(); FirmwareImage toSend; if (type == FirmwareImageType.A) { toSend = firmwareBundle.imageA(); } else if (type == FirmwareImageType.B) { toSend = firmwareBundle.imageB(); } else { throwBeanError(BeanError.UNPARSABLE_FW_METADATA); return; } FirmwareMetadata newMeta = toSend.metadata(); fwChunksToSend = toSend.chunks(); firmwareUploadState = FirmwareUploadState.AWAIT_XFER_ACCEPT; // Write the new image metadata writeToCharacteristic(oadIdentify, newMeta.toPayload()); } private void stopFirmwareStateTimeout() { if (firmwareStateTimeout != null) { firmwareStateTimeout.cancel(); firmwareStateTimeout = null; } } private void resetFirmwareStateTimeout() { TimerTask onTimeout = new TimerTask() { @Override public void run() { if (firmwareUploadState == FirmwareUploadState.AWAIT_CURRENT_HEADER) { throwBeanError(BeanError.FW_VER_REQ_TIMEOUT); } else if (firmwareUploadState == FirmwareUploadState.AWAIT_XFER_ACCEPT) { throwBeanError(BeanError.FW_START_TIMEOUT); } else if (firmwareUploadState == FirmwareUploadState.SEND_FW_CHUNKS) { throwBeanError(BeanError.FW_TRANSFER_TIMEOUT); } else if (firmwareUploadState == FirmwareUploadState.AWAIT_COMPLETION) { throwBeanError(BeanError.FW_COMPLETE_TIMEOUT); } } }; stopFirmwareStateTimeout(); firmwareStateTimeout = new Timer(); firmwareStateTimeout.schedule(onTimeout, FIRMWARE_UPLOAD_TIMEOUT); } private void throwBeanError(BeanError error) { resetFirmwareUploadState(); if (onError != null) { onError.onResult(error); } } private boolean uploadInProgress() { return firmwareUploadState == FirmwareUploadState.INACTIVE; } private boolean isOADBlockCharacteristic(BluetoothGattCharacteristic charc) { UUID uuid = charc.getUuid(); return uuid.equals(CHAR_OAD_BLOCK); } private boolean isOADIdentifyCharacteristic(BluetoothGattCharacteristic charc) { UUID uuid = charc.getUuid(); return uuid.equals(CHAR_OAD_IDENTIFY); } private boolean isOADCharacteristic(BluetoothGattCharacteristic charc) { return isOADBlockCharacteristic(charc) || isOADIdentifyCharacteristic(charc); } private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) { charc.setValue(data); return mGatt.writeCharacteristic(charc); } }
beansdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/GattClient.java
package com.punchthrough.bean.sdk.internal.ble; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.content.Context; import com.punchthrough.bean.sdk.internal.battery.BatteryProfile; import com.punchthrough.bean.sdk.internal.device.DeviceProfile; import com.punchthrough.bean.sdk.internal.exception.MetadataParsingException; import com.punchthrough.bean.sdk.internal.serial.GattSerialTransportProfile; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareChunk; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareImageType; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareMetadata; import com.punchthrough.bean.sdk.internal.upload.firmware.FirmwareUploadState; import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.Callback; import com.punchthrough.bean.sdk.message.UploadProgress; import com.punchthrough.bean.sdk.upload.FirmwareBundle; import com.punchthrough.bean.sdk.upload.FirmwareImage; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; public class GattClient { private static final String TAG = "GattClient"; private final GattSerialTransportProfile mSerialProfile; private final DeviceProfile mDeviceProfile; private final BatteryProfile mBatteryProfile; private BluetoothGatt mGatt; private List<BaseProfile> mProfiles = new ArrayList<>(10); private Queue<Runnable> mOperationsQueue = new ArrayDeque<>(32); private boolean mOperationInProgress = false; private boolean mConnected = false; private boolean mDiscoveringServices = false; // These class variables are used for firmware uploads. /** * The maximum time, in ms, the client will wait for an update from the Bean before aborting the * firmware upload process and throwing an error */ private static final int FIRMWARE_UPLOAD_TIMEOUT = 3000; /** * The OAD Service contains the OAD Identify and Block characteristics */ private static final UUID SERVICE_OAD = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); /** * The OAD Identify characteristic is used to negotiate the start of a firmware transfer */ private static final UUID CHAR_OAD_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); /** * The OAD Block characteristic is used to send firmware chunks and confirm transfer completion */ private static final UUID CHAR_OAD_BLOCK = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); /** * The OAD Identify characteristic for this device. Assigned when firmware upload is started. */ private BluetoothGattCharacteristic oadIdentify; /** * The OAD Block characteristic for this device. Assigned when firmware upload is started. */ private BluetoothGattCharacteristic oadBlock; /** * True if the OAD Identify characteristic is notifying, false otherwise */ private boolean oadIdentifyNotifying = false; /** * True if the OAD Block characteristic is notifying, false otherwise */ private boolean oadBlockNotifying = false; /** * State of the current firmware upload process. */ private FirmwareUploadState firmwareUploadState = FirmwareUploadState.INACTIVE; /** * Aborts firmware upload and throws an error if we go too long without a response from the CC. */ private Timer firmwareStateTimeout; /** * Firmware bundle with A and B images to send */ FirmwareBundle firmwareBundle; /** * Chunks of firmware to be sent in order */ private List<FirmwareChunk> fwChunksToSend; /** * Firmware chunk counter. The packet ID must be incremented for each chunk that is sent. */ private int currFwPacketNum = 0; /** * Called to inform the Bean class when firmware upload progress is made. */ private Callback<UploadProgress> onProgress; /** * Called to inform the Bean class when firmware upload is complete. */ private Runnable onComplete; /** * Called when an error causes the firmware upload to fail. */ private Callback<BeanError> onError; private final BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (status != BluetoothGatt.GATT_SUCCESS) { fireConnectionStateChange(BluetoothGatt.STATE_DISCONNECTED); disconnect(); return; } if (newState == BluetoothGatt.STATE_CONNECTED) { mConnected = true; } fireConnectionStateChange(newState); } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { mDiscoveringServices = false; if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireServicesDiscovered(); } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } if (uploadInProgress()) { if (isOADIdentifyCharacteristic(characteristic)) { resetFirmwareStateTimeout(); if (firmwareUploadState == FirmwareUploadState.AWAIT_CURRENT_HEADER) { prepareResponseHeader(characteristic.getValue()); } else if (firmwareUploadState == FirmwareUploadState.AWAIT_XFER_ACCEPT) { // Existing header read, new header sent, Identify pinged -> // Bean rejected firmware version throwBeanError(BeanError.BEAN_REJECTED_FW); } } else if (isOADBlockCharacteristic(characteristic)) { if (firmwareUploadState == FirmwareUploadState.AWAIT_XFER_ACCEPT) { // Existing header read, new header sent, Block pinged -> // Bean accepted firmware version, begin transfer // TODO: Begin transfer } } } fireCharacteristicsRead(characteristic); executeNextOperation(); } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireCharacteristicWrite(characteristic); executeNextOperation(); } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { if (uploadInProgress() && isOADCharacteristic(characteristic)) { mGatt.readCharacteristic(characteristic); } fireCharacteristicChanged(characteristic); } @Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireDescriptorRead(descriptor); executeNextOperation(); } @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); return; } fireDescriptorWrite(descriptor); executeNextOperation(); } @Override public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { disconnect(); } } }; public GattClient() { mSerialProfile = new GattSerialTransportProfile(this); mDeviceProfile = new DeviceProfile(this); mBatteryProfile = new BatteryProfile(this); mProfiles.add(mSerialProfile); mProfiles.add(mDeviceProfile); mProfiles.add(mBatteryProfile); } private void fireDescriptorRead(BluetoothGattDescriptor descriptor) { for (BaseProfile profile : mProfiles) { profile.onDescriptorRead(this, descriptor); } } private synchronized void queueOperation(Runnable operation) { mOperationsQueue.offer(operation); if (!mOperationInProgress) { executeNextOperation(); } } private synchronized void executeNextOperation() { Runnable operation = mOperationsQueue.poll(); if (operation != null) { mOperationInProgress = true; operation.run(); } else { mOperationInProgress = false; } } public void connect(Context context, BluetoothDevice device) { if (mGatt != null) { mGatt.disconnect(); mGatt.close(); } mConnected = false; mGatt = device.connectGatt(context, false, mBluetoothGattCallback); } private void fireDescriptorWrite(BluetoothGattDescriptor descriptor) { for (BaseProfile profile : mProfiles) { profile.onDescriptorWrite(this, descriptor); } } private void fireCharacteristicChanged(BluetoothGattCharacteristic characteristic) { for (BaseProfile profile : mProfiles) { profile.onCharacteristicChanged(this, characteristic); } } private void fireCharacteristicWrite(BluetoothGattCharacteristic characteristic) { for (BaseProfile profile : mProfiles) { profile.onCharacteristicWrite(this, characteristic); } } private void fireCharacteristicsRead(BluetoothGattCharacteristic characteristic) { for (BaseProfile profile : mProfiles) { profile.onCharacteristicRead(this, characteristic); } } private void fireServicesDiscovered() { for (BaseProfile profile : mProfiles) { profile.onServicesDiscovered(this); } } private synchronized void fireConnectionStateChange(int newState) { if (newState == BluetoothGatt.STATE_DISCONNECTED) { mOperationsQueue.clear(); mOperationInProgress = false; mConnected = false; } else if (newState == BluetoothGatt.STATE_CONNECTED) { mConnected = true; } for (BaseProfile profile : mProfiles) { profile.onConnectionStateChange(newState); } } public List<BluetoothGattService> getServices() { return mGatt.getServices(); } public BluetoothGattService getService(UUID uuid) { return mGatt.getService(uuid); } public boolean discoverServices() { if (mDiscoveringServices) { return true; } mDiscoveringServices = true; return mGatt.discoverServices(); } public synchronized boolean readCharacteristic(final BluetoothGattCharacteristic characteristic) { queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { mGatt.readCharacteristic(characteristic); } } }); return true; } public synchronized boolean writeCharacteristic(final BluetoothGattCharacteristic characteristic) { final byte[] value = characteristic.getValue(); queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { characteristic.setValue(value); mGatt.writeCharacteristic(characteristic); } } }); return true; } public boolean readDescriptor(final BluetoothGattDescriptor descriptor) { queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { mGatt.readDescriptor(descriptor); } } }); return true; } public boolean writeDescriptor(final BluetoothGattDescriptor descriptor) { final byte[] value = descriptor.getValue(); queueOperation(new Runnable() { @Override public void run() { if (mGatt != null) { descriptor.setValue(value); mGatt.writeDescriptor(descriptor); } } }); return true; } public boolean readRemoteRssi() { return mGatt.readRemoteRssi(); } public boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) { return mGatt.setCharacteristicNotification(characteristic, enable); } private boolean connect() { return mGatt != null && mGatt.connect(); } public void disconnect() { close(); throwBeanError(BeanError.UNKNOWN); } private synchronized void close() { if (mGatt != null) { mGatt.close(); } mGatt = null; } public GattSerialTransportProfile getSerialProfile() { return mSerialProfile; } public DeviceProfile getDeviceProfile() { return mDeviceProfile; } public BatteryProfile getBatteryProfile() { return mBatteryProfile; } public void programWithFirmware(FirmwareBundle bundle, Callback<UploadProgress> onProgress, Runnable onComplete, Callback<BeanError> onError) { // Ensure Bean is connected and services have been discovered if (!mConnected) { onError.onResult(BeanError.NOT_CONNECTED); } if (mGatt.getServices() == null) { onError.onResult(BeanError.SERVICES_NOT_DISCOVERED); } // Set event handlers this.onProgress = onProgress; this.onComplete = onComplete; this.onError = onError; // Save firmware bundle so we have both images when response header is received this.firmwareBundle = bundle; verifyNotifyEnabled(); } private void resetFirmwareUploadState() { firmwareUploadState = FirmwareUploadState.INACTIVE; stopFirmwareStateTimeout(); } private void verifyNotifyEnabled() { // Ensure all characteristics are discovered and notifying if (oadIdentify != null && oadBlock != null && oadIdentifyNotifying && oadBlockNotifying) { requestCurrentHeader(); } else { enableOADNotifications(); } } private void enableOADNotifications() { firmwareUploadState = FirmwareUploadState.AWAIT_NOTIFY_ENABLED; BluetoothGattService oadService = mGatt.getService(SERVICE_OAD); if (oadService == null) { throwBeanError(BeanError.MISSING_OAD_SERVICE); return; } oadIdentify = oadService.getCharacteristic(CHAR_OAD_IDENTIFY); if (oadIdentify == null) { throwBeanError(BeanError.MISSING_OAD_IDENTIFY); return; } oadBlock = oadService.getCharacteristic(CHAR_OAD_BLOCK); if (oadBlock == null) { throwBeanError(BeanError.MISSING_OAD_BLOCK); return; } oadIdentifyNotifying = enableNotifyForChar(oadIdentify); oadBlockNotifying = enableNotifyForChar(oadBlock); if (oadIdentifyNotifying && oadBlockNotifying) { enableOADNotifications(); } else { throwBeanError(BeanError.ENABLE_OAD_NOTIFY_FAILED); } } // https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) { boolean result = mGatt.setCharacteristicNotification(characteristic, true); String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"; BluetoothGattDescriptor descriptor = characteristic.getDescriptor( UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); mGatt.writeDescriptor(descriptor); return result; } private void requestCurrentHeader() { firmwareUploadState = FirmwareUploadState.AWAIT_CURRENT_HEADER; // To request the current header, write [0x00] to OAD Identify writeToCharacteristic(oadIdentify, new byte[]{0x00}); } private void prepareResponseHeader(byte[] rawRequestHeader) { FirmwareMetadata existingMeta; try { existingMeta = FirmwareMetadata.fromPayload(rawRequestHeader); } catch (MetadataParsingException e) { throwBeanError(BeanError.UNPARSABLE_FW_METADATA); return; } // TODO: Check FW to flash's version against existing FW FirmwareImageType type = existingMeta.type(); FirmwareImage toSend; if (type == FirmwareImageType.A) { toSend = firmwareBundle.imageA(); } else if (type == FirmwareImageType.B) { toSend = firmwareBundle.imageB(); } else { throwBeanError(BeanError.UNPARSABLE_FW_METADATA); return; } FirmwareMetadata newMeta = toSend.metadata(); fwChunksToSend = toSend.chunks(); firmwareUploadState = FirmwareUploadState.AWAIT_XFER_ACCEPT; // Write the new image metadata writeToCharacteristic(oadIdentify, newMeta.toPayload()); } private void stopFirmwareStateTimeout() { if (firmwareStateTimeout != null) { firmwareStateTimeout.cancel(); firmwareStateTimeout = null; } } private void resetFirmwareStateTimeout() { TimerTask onTimeout = new TimerTask() { @Override public void run() { if (firmwareUploadState == FirmwareUploadState.AWAIT_CURRENT_HEADER) { throwBeanError(BeanError.FW_VER_REQ_TIMEOUT); } else if (firmwareUploadState == FirmwareUploadState.AWAIT_XFER_ACCEPT) { throwBeanError(BeanError.FW_START_TIMEOUT); } else if (firmwareUploadState == FirmwareUploadState.SEND_FW_CHUNKS) { throwBeanError(BeanError.FW_TRANSFER_TIMEOUT); } else if (firmwareUploadState == FirmwareUploadState.AWAIT_COMPLETION) { throwBeanError(BeanError.FW_COMPLETE_TIMEOUT); } } }; stopFirmwareStateTimeout(); firmwareStateTimeout = new Timer(); firmwareStateTimeout.schedule(onTimeout, FIRMWARE_UPLOAD_TIMEOUT); } private void throwBeanError(BeanError error) { resetFirmwareUploadState(); if (onError != null) { onError.onResult(error); } } private boolean uploadInProgress() { return firmwareUploadState == FirmwareUploadState.INACTIVE; } private boolean isOADBlockCharacteristic(BluetoothGattCharacteristic charc) { UUID uuid = charc.getUuid(); return uuid.equals(CHAR_OAD_BLOCK); } private boolean isOADIdentifyCharacteristic(BluetoothGattCharacteristic charc) { UUID uuid = charc.getUuid(); return uuid.equals(CHAR_OAD_IDENTIFY); } private boolean isOADCharacteristic(BluetoothGattCharacteristic charc) { return isOADBlockCharacteristic(charc) || isOADIdentifyCharacteristic(charc); } private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) { charc.setValue(data); return mGatt.writeCharacteristic(charc); } }
Fix enable notify to not infinitely recurse
beansdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/GattClient.java
Fix enable notify to not infinitely recurse
<ide><path>eansdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/GattClient.java <ide> oadIdentifyNotifying = enableNotifyForChar(oadIdentify); <ide> oadBlockNotifying = enableNotifyForChar(oadBlock); <ide> if (oadIdentifyNotifying && oadBlockNotifying) { <del> enableOADNotifications(); <add> requestCurrentHeader(); <ide> } else { <ide> throwBeanError(BeanError.ENABLE_OAD_NOTIFY_FAILED); <ide> }
Java
mit
c40c472aede8c36b501b6cbde34f520ca73dba0d
0
Aquerr/EagleFactions,Aquerr/EagleFactions
package io.github.aquerr.eaglefactions.common.commands; import io.github.aquerr.eaglefactions.api.EagleFactions; import io.github.aquerr.eaglefactions.api.entities.Claim; import io.github.aquerr.eaglefactions.api.entities.Faction; import io.github.aquerr.eaglefactions.common.EagleFactionsPlugin; import io.github.aquerr.eaglefactions.common.PluginInfo; import io.github.aquerr.eaglefactions.common.messaging.Messages; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.world.World; import java.util.Optional; public class RegenCommand extends AbstractCommand { public RegenCommand(EagleFactions plugin) { super(plugin); } @Override public CommandResult execute(CommandSource source, CommandContext context) throws CommandException { final Faction factionToRegen = context.requireOne("faction"); if (factionToRegen.isSafeZone() || factionToRegen.isWarZone()) { throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, "This faction cannot be disbanded!")); } /* Firstly, we're simply disbanding the faction. */ boolean didSucceed = super.getPlugin().getFactionLogic().disbandFaction(factionToRegen.getName()); if(didSucceed) { if (source instanceof Player) { Player player = (Player) source; EagleFactionsPlugin.AUTO_CLAIM_LIST.remove(player.getUniqueId()); EagleFactionsPlugin.CHAT_LIST.remove(player.getUniqueId()); } } else { throw new CommandException((Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.RED, Messages.SOMETHING_WENT_WRONG))); } /* After a successful disband we can regenerate faction claims. */ for (Claim claim : factionToRegen.getClaims()) { Optional<World> world = Sponge.getServer().getWorld(claim.getWorldUUID()); if (!world.isPresent()) { throw new CommandException((Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.RED, Messages.SOMETHING_WENT_WRONG))); } world.get().regenerateChunk(claim.getChunkPosition()); } source.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.WHITE, "The faction was successfully regenerated!")); return CommandResult.success(); } }
common/src/main/java/io/github/aquerr/eaglefactions/common/commands/RegenCommand.java
package io.github.aquerr.eaglefactions.common.commands; import io.github.aquerr.eaglefactions.api.EagleFactions; import io.github.aquerr.eaglefactions.api.entities.Claim; import io.github.aquerr.eaglefactions.api.entities.Faction; import io.github.aquerr.eaglefactions.common.EagleFactionsPlugin; import io.github.aquerr.eaglefactions.common.PluginInfo; import io.github.aquerr.eaglefactions.common.messaging.Messages; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import java.util.Optional; public class RegenCommand extends AbstractCommand { public RegenCommand(EagleFactions plugin) { super(plugin); } @Override public CommandResult execute(CommandSource source, CommandContext context) throws CommandException { final Faction factionToRegen = context.requireOne("faction"); if (factionToRegen.isSafeZone() || factionToRegen.isWarZone()) { throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, "This faction cannot be disbanded!")); } /* Firstly, we're simply disbanding the faction. */ boolean didSucceed = super.getPlugin().getFactionLogic().disbandFaction(factionToRegen.getName()); if(didSucceed) { if (source instanceof Player) { Player player = (Player) source; EagleFactionsPlugin.AUTO_CLAIM_LIST.remove(player.getUniqueId()); EagleFactionsPlugin.CHAT_LIST.remove(player.getUniqueId()); } } else { throw new CommandException((Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.RED, Messages.SOMETHING_WENT_WRONG))); } /* After a successful disband we can regenerate faction claims. */ for (Claim claim : factionToRegen.getClaims()) { Sponge.getServer().getWorld(claim.getWorldUUID()).ifPresent(world -> { world.regenerateChunk(claim.getChunkPosition()); }); } source.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.WHITE, "The faction was successfully regenerated!")); return CommandResult.success(); } }
Fix code formatting
common/src/main/java/io/github/aquerr/eaglefactions/common/commands/RegenCommand.java
Fix code formatting
<ide><path>ommon/src/main/java/io/github/aquerr/eaglefactions/common/commands/RegenCommand.java <ide> import org.spongepowered.api.entity.living.player.Player; <ide> import org.spongepowered.api.text.Text; <ide> import org.spongepowered.api.text.format.TextColors; <add>import org.spongepowered.api.world.World; <ide> <ide> import java.util.Optional; <ide> <ide> { <ide> final Faction factionToRegen = context.requireOne("faction"); <ide> <del> if (factionToRegen.isSafeZone() || factionToRegen.isWarZone()) { <add> if (factionToRegen.isSafeZone() || factionToRegen.isWarZone()) <add> { <ide> throw new CommandException(Text.of(PluginInfo.ERROR_PREFIX, TextColors.RED, "This faction cannot be disbanded!")); <ide> } <ide> <ide> boolean didSucceed = super.getPlugin().getFactionLogic().disbandFaction(factionToRegen.getName()); <ide> if(didSucceed) <ide> { <del> if (source instanceof Player) { <add> if (source instanceof Player) <add> { <ide> Player player = (Player) source; <ide> <ide> EagleFactionsPlugin.AUTO_CLAIM_LIST.remove(player.getUniqueId()); <ide> <ide> /* After a successful disband we can regenerate faction claims. */ <ide> <del> for (Claim claim : factionToRegen.getClaims()) { <del> Sponge.getServer().getWorld(claim.getWorldUUID()).ifPresent(world -> { <del> world.regenerateChunk(claim.getChunkPosition()); <del> }); <add> for (Claim claim : factionToRegen.getClaims()) <add> { <add> Optional<World> world = Sponge.getServer().getWorld(claim.getWorldUUID()); <add> <add> if (!world.isPresent()) <add> { <add> throw new CommandException((Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.RED, Messages.SOMETHING_WENT_WRONG))); <add> } <add> <add> world.get().regenerateChunk(claim.getChunkPosition()); <ide> } <del> <ide> <ide> source.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.WHITE, "The faction was successfully regenerated!")); <ide>
Java
mit
0073f09a6c4cb8789f064965e8e1f2a923d06f99
0
jeottesen/21CardTrickCS3750
import java.awt.Color; import java.awt.Dimension; import java.util.Stack; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class Dealer{ // Association with Board class private Board board; // Association between Player and Dealer private Player player; private Stack<Card> trickDeck; private int dealNumber = 1; public Dealer(Board board) { this.board = board; dealNumber = 1; Deck deck = new Deck(); trickDeck = new Stack<>(); trickDeck.addAll(deck.random21()); } public void deal() { for (int i = 0; i < Globals.CARDS_PER_COLUMN; i++) { board.addToColumn(1, trickDeck.pop()); board.addToColumn(2, trickDeck.pop()); board.addToColumn(3, trickDeck.pop()); } } public void revealCard() { Card revealCard = board.getColumnTwo().getCards().get(4); JPanel overlay = new JPanel(); overlay.setBounds(50, 50, Globals.CARD_WI, Globals.CARD_HI); overlay.setBackground(new Color(0,0,0,125)); overlay.setPreferredSize(new Dimension(250,150)); overlay.setVisible(true); board.add(overlay); overlay.add(revealCard); revealCard.setLocation(300,200); JOptionPane.showMessageDialog(null, "Tell the truth, this is your card!"); //Board.newDeal() -- This does not exist yet. But if we choose to implement it, it should be called here. } public void pickupCards(int column) { if (column == 1) { trickDeck.addAll(board.getColumnTwo().getCards()); trickDeck.addAll(board.getColumnOne().getCards()); trickDeck.addAll(board.getColumnThree().getCards()); } else if (column == 2) { trickDeck.addAll(board.getColumnOne().getCards()); trickDeck.addAll(board.getColumnTwo().getCards()); trickDeck.addAll(board.getColumnThree().getCards()); } else if (column == 3) { trickDeck.addAll(board.getColumnOne().getCards()); trickDeck.addAll(board.getColumnThree().getCards()); trickDeck.addAll(board.getColumnTwo().getCards()); } if (dealNumber == 3) { revealCard(); } dealNumber++; } }
src/Dealer.java
import java.awt.Color; import java.awt.Dimension; import java.util.Stack; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class Dealer{ // Association with Board class private Board board; // Association between Player and Dealer private Player player; private Stack<Card> trickDeck; private int dealNumber = 1; public Dealer(Board board) { this.board = board; dealNumber = 1; Deck deck = new Deck(); trickDeck = new Stack<>(); trickDeck.addAll(deck.random21()); } public void deal() { for (int i = 0; i < Globals.CARDS_PER_COLUMN; i++) { board.addToColumn(1, trickDeck.pop()); board.addToColumn(2, trickDeck.pop()); board.addToColumn(3, trickDeck.pop()); } } public void revealCard() { //Card SecretCard; //SecretCard = trickDeck.get(10); // setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel p1 = new JPanel(); //p1.setTitle("Transparent Panel"); p1.setBounds(50, 50, Globals.CARD_WI, Globals.CARD_HI); // Set the background, black with 125 as alpha value // This is less transparent p1.setBackground(new Color(0,0,0,125)); p1.setPreferredSize(new Dimension(250,150)); // Add the panels to the JFrame board.add(p1); //setSize(600,400); p1.setVisible(true); board.getColumnTwo().getCards().get(4); // This should be the last line JOptionPane.showMessageDialog(null, "Tell the truth, this is your card!"); // Board.newDeal() -- This does not exist yet. But if we choose to implement it, it should be called here. } public void pickupCards(int column) { if (column == 1) { trickDeck.addAll(board.getColumnTwo().getCards()); trickDeck.addAll(board.getColumnOne().getCards()); trickDeck.addAll(board.getColumnThree().getCards()); } else if (column == 2) { trickDeck.addAll(board.getColumnOne().getCards()); trickDeck.addAll(board.getColumnTwo().getCards()); trickDeck.addAll(board.getColumnThree().getCards()); } else if (column == 3) { trickDeck.addAll(board.getColumnOne().getCards()); trickDeck.addAll(board.getColumnThree().getCards()); trickDeck.addAll(board.getColumnTwo().getCards()); } if (dealNumber == 3) { revealCard(); } dealNumber++; } }
"revealCard()" Method Updates "revealCard()" method updates.
src/Dealer.java
"revealCard()" Method Updates
<ide><path>rc/Dealer.java <ide> <ide> public void revealCard() <ide> { <del> //Card SecretCard; <del> //SecretCard = trickDeck.get(10); <add> Card revealCard = board.getColumnTwo().getCards().get(4); <add> JPanel overlay = new JPanel(); <ide> <del> <del> // setDefaultCloseOperation(EXIT_ON_CLOSE); <del> JPanel p1 = new JPanel(); <del> //p1.setTitle("Transparent Panel"); <del> p1.setBounds(50, 50, Globals.CARD_WI, Globals.CARD_HI); <del> <del> // Set the background, black with 125 as alpha value <del> // This is less transparent <del> p1.setBackground(new Color(0,0,0,125)); <del> <del> p1.setPreferredSize(new Dimension(250,150)); <del> <del> // Add the panels to the JFrame <del> board.add(p1); <del> <del> //setSize(600,400); <del> p1.setVisible(true); <del> board.getColumnTwo().getCards().get(4); <del> <del> // This should be the last line <add> overlay.setBounds(50, 50, Globals.CARD_WI, Globals.CARD_HI); <add> overlay.setBackground(new Color(0,0,0,125)); <add> overlay.setPreferredSize(new Dimension(250,150)); <add> overlay.setVisible(true); <add> board.add(overlay); <add> overlay.add(revealCard); <add> revealCard.setLocation(300,200); <ide> JOptionPane.showMessageDialog(null, "Tell the truth, this is your card!"); <ide> <del> // Board.newDeal() -- This does not exist yet. But if we choose to implement it, it should be called here. <add> //Board.newDeal() -- This does not exist yet. But if we choose to implement it, it should be called here. <ide> } <ide> <ide> public void pickupCards(int column)
Java
apache-2.0
6b1ae762fd3cdba46f788bd2e0af778013ef13cb
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Common; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMClass.CMObjectType; 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.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.Common.interfaces.AccountStats.PrideStat; import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback; 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.ChannelsLibrary.CMChannel; import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData; import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag; 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 org.mozilla.javascript.*; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; /* Copyright 2008-2020 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 DefaultScriptingEngine implements ScriptingEngine { @Override public String ID() { return "DefaultScriptingEngine"; } @Override public String name() { return "Default Scripting Engine"; } protected static final Map<String,Integer> funcH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> methH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> progH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> connH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> gstatH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> signH = new Hashtable<String,Integer>(); protected static final Map<String, AtomicInteger> counterCache= new Hashtable<String, AtomicInteger>(); protected static final Map<String, Pattern> patterns = new Hashtable<String, Pattern>(); protected boolean noDelay = CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLEDELAY); protected String scope = ""; protected int tickStatus = Tickable.STATUS_NOT; protected boolean isSavable = true; protected boolean alwaysTriggers = false; protected MOB lastToHurtMe = null; protected Room lastKnownLocation= null; protected Room homeKnownLocation= null; protected Tickable altStatusTickable= null; protected List<DVector> oncesDone = new Vector<DVector>(); protected Map<Integer,Integer> delayTargetTimes = new Hashtable<Integer,Integer>(); protected Map<Integer,int[]> delayProgCounters= new Hashtable<Integer,int[]>(); protected Map<Integer,Integer> lastTimeProgsDone= new Hashtable<Integer,Integer>(); protected Map<Integer,Integer> lastDayProgsDone = new Hashtable<Integer,Integer>(); protected Set<Integer> registeredEvents = new HashSet<Integer>(); protected Map<Integer,Long> noTrigger = new Hashtable<Integer,Long>(); protected MOB backupMOB = null; protected CMMsg lastMsg = null; protected Resources resources = null; protected Environmental lastLoaded = null; protected String myScript = ""; protected String defaultQuestName = ""; protected String scriptKey = null; protected boolean runInPassiveAreas= true; protected boolean debugBadScripts = false; protected List<ScriptableResponse>que = new Vector<ScriptableResponse>(); protected final AtomicInteger recurseCounter = new AtomicInteger(); protected volatile Object cachedRef = null; public DefaultScriptingEngine() { super(); //CMClass.bumpCounter(this,CMClass.CMObjectType.COMMON);//removed for mem & perf debugBadScripts=CMSecurity.isDebugging(CMSecurity.DbgFlag.BADSCRIPTS); resources = Resources.instance(); } @Override public boolean isSavable() { return isSavable; } @Override public void setSavable(final boolean truefalse) { isSavable = truefalse; } @Override public String defaultQuestName() { return defaultQuestName; } protected Quest defaultQuest() { if(defaultQuestName.length()==0) return null; return CMLib.quests().fetchQuest(defaultQuestName); } @Override public void setVarScope(final String newScope) { if((newScope==null)||(newScope.trim().length()==0)||newScope.equalsIgnoreCase("GLOBAL")) { scope=""; resources=Resources.instance(); } else scope=newScope.toUpperCase().trim(); if(scope.equalsIgnoreCase("*")||scope.equals("INDIVIDUAL")) resources = Resources.newResources(); else { resources=(Resources)Resources.getResource("VARSCOPE-"+scope); if(resources==null) { resources = Resources.newResources(); Resources.submitResource("VARSCOPE-"+scope,resources); } if(cachedRef==this) bumpUpCache(scope); } } @Override public String getVarScope() { return scope; } protected Object[] newObjs() { return new Object[ScriptingEngine.SPECIAL_NUM_OBJECTS]; } @Override public String getLocalVarXML() { if((scope==null)||(scope.length()==0)) return ""; final StringBuffer str=new StringBuffer(""); for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { final String key=k.next(); if(key.startsWith("SCRIPTVAR-")) { str.append("<"+key.substring(10)+">"); @SuppressWarnings("unchecked") final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource(key); for(final Enumeration<String> e=H.keys();e.hasMoreElements();) { final String vn=e.nextElement(); final String val=H.get(vn); str.append("<"+vn+">"+CMLib.xml().parseOutAngleBrackets(val)+"</"+vn+">"); } str.append("</"+key.substring(10)+">"); } } return str.toString(); } @Override public void setLocalVarXML(final String xml) { for(final Iterator<String> k = Resources.findResourceKeys("SCRIPTVAR-");k.hasNext();) { final String key=k.next(); if(key.startsWith("SCRIPTVAR-")) resources._removeResource(key); } final List<XMLLibrary.XMLTag> V=CMLib.xml().parseAllXML(xml); for(int v=0;v<V.size();v++) { final XMLTag piece=V.get(v); if((piece.contents()!=null)&&(piece.contents().size()>0)) { final String kkey="SCRIPTVAR-"+piece.tag(); final Hashtable<String,String> H=new Hashtable<String,String>(); for(int c=0;c<piece.contents().size();c++) { final XMLTag piece2=piece.contents().get(c); H.put(piece2.tag(),piece2.value()); } resources._submitResource(kkey,H); } } } private Quest getQuest(final String named) { if((defaultQuestName.length()>0) &&(named.equals("*")||named.equalsIgnoreCase(defaultQuestName))) return defaultQuest(); Quest Q=null; for(int i=0;i<CMLib.quests().numQuests();i++) { try { Q = CMLib.quests().fetchQuest(i); } catch (final Exception e) { } if(Q!=null) { if(Q.name().equalsIgnoreCase(named)) { if(Q.running()) return Q; } } } return CMLib.quests().fetchQuest(named); } @Override public int getTickStatus() { final Tickable T=altStatusTickable; if(T!=null) return T.getTickStatus(); return tickStatus; } @Override public void registerDefaultQuest(final String qName) { if((qName==null)||(qName.trim().length()==0)) defaultQuestName=""; else { defaultQuestName=qName.trim(); if(cachedRef==this) bumpUpCache(defaultQuestName); } } @Override public CMObject newInstance() { try { return this.getClass().newInstance(); } catch(final Exception e) { Log.errOut(ID(),e); } return new DefaultScriptingEngine(); } @Override public CMObject copyOf() { try { final DefaultScriptingEngine S=(DefaultScriptingEngine)this.clone(); //CMClass.bumpCounter(S,CMClass.CMObjectType.COMMON);//removed for mem & perf S.reset(); return S; } catch(final CloneNotSupportedException e) { return new DefaultScriptingEngine(); } } /* protected void finalize() { CMClass.unbumpCounter(this, CMClass.CMObjectType.COMMON); }// removed for mem & perf */ /* * c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger */ protected String[] parseBits(final DVector script, final int row, final String instructions) { final String line=(String)script.elementAt(row,1); final String[] newLine=parseBits(line,instructions); script.setElementAt(row,2,newLine); return newLine; } protected String[] parseSpecial3PartEval(final String[][] eval, final int t) { String[] tt=eval[0]; final String funcParms=tt[t]; final String[] tryTT=parseBits(funcParms,"ccr"); if(signH.containsKey(tryTT[1])) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ else { String[] parsed=null; if(CMParms.cleanBit(funcParms).equals(funcParms)) parsed=parseBits("'"+funcParms+"' . .","cr"); else parsed=parseBits(funcParms+" . .","cr"); tt=insertStringArray(tt,parsed,t); eval[0]=tt; } return tt; } /* * c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger */ protected String[] parseBits(String line, final String instructions) { String[] newLine=new String[instructions.length()]; for(int i=0;i<instructions.length();i++) { switch(instructions.charAt(i)) { case 'c': newLine[i] = CMParms.getCleanBit(line, i); break; case 'C': newLine[i] = CMParms.getCleanBit(line, i).toUpperCase().trim(); break; case 'r': newLine[i] = CMParms.getPastBitClean(line, i - 1); break; case 'R': newLine[i] = CMParms.getPastBitClean(line, i - 1).toUpperCase().trim(); break; case 'p': newLine[i] = CMParms.getPastBit(line, i - 1); break; case 'P': newLine[i] = CMParms.getPastBit(line, i - 1).toUpperCase().trim(); break; case 'S': line = line.toUpperCase(); //$FALL-THROUGH$ case 's': { final String s = CMParms.getPastBit(line, i - 1); final int numBits = CMParms.numBits(s); final String[] newNewLine = new String[newLine.length - 1 + numBits]; for (int x = 0; x < i; x++) newNewLine[x] = newLine[x]; for (int x = 0; x < numBits; x++) newNewLine[i + x] = CMParms.getCleanBit(s, i - 1); newLine = newNewLine; i = instructions.length(); break; } case 'T': line = line.toUpperCase(); //$FALL-THROUGH$ case 't': { final String s = CMParms.getPastBit(line, i - 1); String[] newNewLine = null; if (CMParms.getCleanBit(s, 0).equalsIgnoreCase("P")) { newNewLine = new String[newLine.length + 1]; for (int x = 0; x < i; x++) newNewLine[x] = newLine[x]; newNewLine[i] = "P"; newNewLine[i + 1] = CMParms.getPastBitClean(s, 0); } else { final int numNewBits = (s.trim().length() == 0) ? 1 : CMParms.numBits(s); newNewLine = new String[newLine.length - 1 + numNewBits]; for (int x = 0; x < i; x++) newNewLine[x] = newLine[x]; for (int x = 0; x < numNewBits; x++) newNewLine[i + x] = CMParms.getCleanBit(s, x); } newLine = newNewLine; i = instructions.length(); break; } } } return newLine; } protected String[] insertStringArray(final String[] oldS, final String[] inS, final int where) { final String[] newLine=new String[oldS.length+inS.length-1]; for(int i=0;i<where;i++) newLine[i]=oldS[i]; for(int i=0;i<inS.length;i++) newLine[where+i]=inS[i]; for(int i=where+1;i<oldS.length;i++) newLine[inS.length+i-1]=oldS[i]; return newLine; } /* * c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger */ protected String[] parseBits(final String[][] oldBits, final int start, final String instructions) { final String[] tt=oldBits[0]; final String parseMe=tt[start]; final String[] parsed=parseBits(parseMe,instructions); if(parsed.length==1) { tt[start]=parsed[0]; return tt; } final String[] newLine=insertStringArray(tt,parsed,start); oldBits[0]=newLine; return newLine; } @Override public boolean endQuest(final PhysicalAgent hostObj, final MOB mob, final String quest) { if(mob!=null) { final List<DVector> scripts=getScripts(); if(!mob.amDead()) { lastKnownLocation=mob.location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } String trigger=""; String[] tt=null; for(int v=0;v<scripts.size();v++) { final DVector script=scripts.get(v); if(script.size()>0) { trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); tt=(String[])script.elementAt(0,2); if((getTriggerCode(trigger,tt)==13) //questtimeprog quest_time_prog &&(!oncesDone.contains(script))) { if(tt==null) tt=parseBits(script,0,"CCC"); if((tt!=null) &&((tt[1].equals(quest)||(tt[1].equals("*")))) &&(CMath.s_int(tt[2])<0)) { oncesDone.add(script); execute(hostObj,mob,mob,mob,null,null,script,null,newObjs()); return true; } } } } } return false; } @Override public List<String> externalFiles() { final Vector<String> xmlfiles=new Vector<String>(); parseLoads(getScript(), 0, xmlfiles, null); return xmlfiles; } protected String getVarHost(final Environmental E, String rawHost, final MOB source, final Environmental target, final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { if(!rawHost.equals("*")) { if(E==null) rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost); else if(E instanceof Room) rawHost=CMLib.map().getExtendedRoomID((Room)E); else rawHost=E.Name(); } return rawHost; } @SuppressWarnings("unchecked") @Override public boolean isVar(final String host, String var) { if(host.equalsIgnoreCase("*")) { String val=null; Hashtable<String,String> H=null; String key=null; var=var.toUpperCase(); for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { key=k.next(); if(key.startsWith("SCRIPTVAR-")) { H=(Hashtable<String,String>)resources._getResource(key); val=H.get(var); if(val!=null) return true; } } return false; } final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host); String val=null; if(H!=null) val=H.get(var.toUpperCase()); return (val!=null); } public String getVar(final Environmental E, final String rawHost, final String var, final MOB source, final Environmental target, final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var); } @Override public String getVar(final String host, final String var) { String varVal = getVar(resources,host,var,null); if(varVal != null) return varVal; if((this.defaultQuestName!=null)&&(this.defaultQuestName.length()>0)) { final Resources questResources=(Resources)Resources.getResource("VARSCOPE-"+this.defaultQuestName); if((questResources != null)&&(resources!=questResources)) { varVal = getVar(questResources,host,var,null); if(varVal != null) return varVal; } } if(resources == Resources.instance()) return ""; return getVar(Resources.instance(),host,var,""); } @SuppressWarnings("unchecked") public String getVar(final Resources resources, final String host, String var, final String defaultVal) { if(host.equalsIgnoreCase("*")) { if(var.equals("COFFEEMUD_SYSTEM_INTERNAL_NONFILENAME_SCRIPT")) { final StringBuffer str=new StringBuffer(""); parseLoads(getScript(),0,null,str); return str.toString(); } String val=null; Hashtable<String,String> H=null; String key=null; var=var.toUpperCase(); for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { key=k.next(); if(key.startsWith("SCRIPTVAR-")) { H=(Hashtable<String,String>)resources._getResource(key); val=H.get(var); if(val!=null) return val; } } return defaultVal; } Resources.instance(); final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host); String val=null; if(H!=null) val=H.get(var.toUpperCase()); else if((defaultQuestName!=null)&&(defaultQuestName.length()>0)) { final MOB M=CMLib.players().getPlayerAllHosts(host); if(M!=null) { for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null) &&(SE!=this) &&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName())) &&(SE.isVar(host,var))) return SE.getVar(host,var); } } } if(val==null) return defaultVal; return val; } private StringBuffer getResourceFileData(final String named, final boolean showErrors) { final Quest Q=getQuest("*"); if(Q!=null) return Q.getResourceFileData(named, showErrors); return new CMFile(Resources.makeFileResourceName(named),null,CMFile.FLAG_LOGERRORS).text(); } @Override public String getScript() { return myScript; } public void reset() { que = new Vector<ScriptableResponse>(); lastToHurtMe = null; lastKnownLocation= null; homeKnownLocation=null; altStatusTickable= null; oncesDone = new Vector<DVector>(); delayTargetTimes = new Hashtable<Integer,Integer>(); delayProgCounters= new Hashtable<Integer,int[]>(); lastTimeProgsDone= new Hashtable<Integer,Integer>(); lastDayProgsDone = new Hashtable<Integer,Integer>(); registeredEvents = new HashSet<Integer>(); noTrigger = new Hashtable<Integer,Long>(); backupMOB = null; lastMsg = null; bumpUpCache(); } @Override public void setScript(String newParms) { newParms=CMStrings.replaceAll(newParms,"'","`"); if(newParms.startsWith("+")) { final String superParms=getScript(); Resources.removeResource(getScriptResourceKey()); newParms=superParms+";"+newParms.substring(1); } myScript=newParms; if(myScript.length()>100) scriptKey="PARSEDPRG: "+myScript.substring(0,100)+myScript.length()+myScript.hashCode(); else scriptKey="PARSEDPRG: "+myScript; reset(); } public boolean isFreeToBeTriggered(final Tickable affecting) { if(alwaysTriggers) return CMLib.flags().canActAtAll(affecting); else return CMLib.flags().canFreelyBehaveNormal(affecting); } protected String parseLoads(final String text, final int depth, final Vector<String> filenames, final StringBuffer nonFilenameScript) { final StringBuffer results=new StringBuffer(""); String parse=text; if(depth>10) return ""; // no including off to infinity String p=null; while(parse.length()>0) { final int y=parse.toUpperCase().indexOf("LOAD="); if(y>=0) { p=parse.substring(0,y).trim(); if((!p.endsWith(";")) &&(!p.endsWith("\n")) &&(!p.endsWith("~")) &&(!p.endsWith("\r")) &&(p.length()>0)) { if(nonFilenameScript!=null) nonFilenameScript.append(parse.substring(0,y+1)); results.append(parse.substring(0,y+1)); parse=parse.substring(y+1); continue; } results.append(p+"\n"); int z=parse.indexOf('~',y); while((z>0)&&(parse.charAt(z-1)=='\\')) z=parse.indexOf('~',z+1); if(z>0) { final String filename=parse.substring(y+5,z).trim(); parse=parse.substring(z+1); if((filenames!=null)&&(!filenames.contains(filename))) filenames.addElement(filename); results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null)); } else { final String filename=parse.substring(y+5).trim(); if((filenames!=null)&&(!filenames.contains(filename))) filenames.addElement(filename); results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null)); break; } } else { if(nonFilenameScript!=null) nonFilenameScript.append(parse); results.append(parse); break; } } return results.toString(); } protected void buildHashes() { if(funcH.size()==0) { synchronized(funcH) { if(funcH.size()==0) { for(int i=0;i<funcs.length;i++) funcH.put(funcs[i],Integer.valueOf(i+1)); for(int i=0;i<methods.length;i++) methH.put(methods[i],Integer.valueOf(i+1)); for(int i=0;i<progs.length;i++) progH.put(progs[i],Integer.valueOf(i+1)); for(int i=0;i<progs.length;i++) methH.put(progs[i],Integer.valueOf(Integer.MIN_VALUE)); for(int i=0;i<CONNECTORS.length;i++) connH.put(CONNECTORS[i],Integer.valueOf(i)); for(int i=0;i<SIGNS.length;i++) signH.put(SIGNS[i],Integer.valueOf(i)); } } } } protected List<DVector> parseScripts(String text) { buildHashes(); while((text.length()>0) &&(Character.isWhitespace(text.charAt(0)))) text=text.substring(1); boolean staticSet=false; if((text.length()>10) &&(text.substring(0,10).toUpperCase().startsWith("STATIC="))) { staticSet=true; text=text.substring(7); } text=parseLoads(text,0,null,null); if(staticSet) { text=CMStrings.replaceAll(text,"'","`"); myScript=text; reset(); } final List<List<String>> V = CMParms.parseDoubleDelimited(text,'~',';'); final Vector<DVector> V2=new Vector<DVector>(3); for(final List<String> ls : V) { final DVector DV=new DVector(3); for(final String s : ls) DV.addElement(s,null,null); V2.add(DV); } return V2; } protected Room getRoom(final String thisName, final Room imHere) { if(thisName.length()==0) return null; if((imHere!=null) &&(imHere.roomID().equalsIgnoreCase(thisName))) return imHere; if((imHere!=null)&&(thisName.startsWith("#"))&&(CMath.isLong(thisName.substring(1)))) return CMLib.map().getRoom(imHere.getArea().Name()+thisName); final Room room=CMLib.map().getRoom(thisName); if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName))) { if(CMath.bset(room.getArea().flags(),Area.FLAG_INSTANCE_PARENT) &&(imHere!=null) &&(CMath.bset(imHere.getArea().flags(),Area.FLAG_INSTANCE_CHILD)) &&(imHere.getArea().Name().endsWith("_"+room.getArea().Name())) &&(thisName.indexOf('#')>=0)) { final Room otherRoom=CMLib.map().getRoom(imHere.getArea().Name()+thisName.substring(thisName.indexOf('#'))); if((otherRoom!=null)&&(otherRoom.roomID().endsWith(thisName))) return otherRoom; } return room; } List<Room> rooms=new Vector<Room>(1); if((imHere!=null)&&(imHere.getArea()!=null)) rooms=CMLib.map().findAreaRoomsLiberally(null, imHere.getArea(), thisName, "RIEPM",100); if(rooms.size()==0) { if(debugBadScripts) Log.debugOut("ScriptingEngine","World room search called for: "+thisName); rooms=CMLib.map().findWorldRoomsLiberally(null,thisName, "RIEPM",100,2000); } if(rooms.size()>0) return rooms.get(CMLib.dice().roll(1,rooms.size(),-1)); if(room == null) { final int x=thisName.indexOf('@'); if(x>0) { Room R=CMLib.map().getRoom(thisName.substring(x+1)); if((R==null)||(R==imHere)) { final Area A=CMLib.map().getArea(thisName.substring(x+1)); R=(A!=null)?A.getRandomMetroRoom():null; } if((R!=null)&&(R!=imHere)) return getRoom(thisName.substring(0,x),R); } } return room; } protected void logError(final Environmental scripted, final String cmdName, final String errType, final String errMsg) { if(scripted!=null) { final Room R=CMLib.map().roomLocation(scripted); String scriptFiles=CMParms.toListString(externalFiles()); if((scriptFiles == null)||(scriptFiles.trim().length()==0)) scriptFiles=CMStrings.limit(this.getScript(),80); if((scriptFiles == null)||(scriptFiles.trim().length()==0)) Log.errOut(new Exception("Scripting Error")); if((scriptFiles == null)||(scriptFiles.trim().length()==0)) scriptFiles=getScriptResourceKey(); Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg+"/"+scriptFiles); if(R!=null) R.showHappens(CMMsg.MSG_OK_VISUAL,L("Scripting Error: @x1/@x2/@x3/@x4/@x5/@x6",scripted.name(),CMLib.map().getExtendedRoomID(R),cmdName,errType,errMsg,scriptFiles)); } else Log.errOut("Scripting","*/*/"+CMParms.toListString(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg); } protected boolean simpleEvalStr(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName) { final int x=arg1.compareToIgnoreCase(arg2); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (x == 0); case SIGN_EQGT: case SIGN_GTEQ: return (x == 0) || (x > 0); case SIGN_EQLT: case SIGN_LTEQ: return (x == 0) || (x < 0); case SIGN_GRAT: return (x > 0); case SIGN_LEST: return (x < 0); case SIGN_NTEQ: return (x != 0); default: return (x == 0); } } protected boolean simpleEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName) { final long val1=CMath.s_long(arg1.trim()); final long val2=CMath.s_long(arg2.trim()); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (val1 == val2); case SIGN_EQGT: case SIGN_GTEQ: return val1 >= val2; case SIGN_EQLT: case SIGN_LTEQ: return val1 <= val2; case SIGN_GRAT: return (val1 > val2); case SIGN_LEST: return (val1 < val2); case SIGN_NTEQ: return (val1 != val2); default: return (val1 == val2); } } protected boolean simpleExpressionEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName) { final double val1=CMath.s_parseMathExpression(arg1.trim()); final double val2=CMath.s_parseMathExpression(arg2.trim()); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (val1 == val2); case SIGN_EQGT: case SIGN_GTEQ: return val1 >= val2; case SIGN_EQLT: case SIGN_LTEQ: return val1 <= val2; case SIGN_GRAT: return (val1 > val2); case SIGN_LEST: return (val1 < val2); case SIGN_NTEQ: return (val1 != val2); default: return (val1 == val2); } } protected List<MOB> loadMobsFromFile(final Environmental scripted, String filename) { filename=filename.trim(); @SuppressWarnings("unchecked") List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMMONSTERS-"+filename); if(monsters!=null) return monsters; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); monsters=new Vector<MOB>(); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"MOBS")!=null) { final String error=CMLib.coffeeMaker().addMOBsFromXML(xml,monsters,null); if(error.length()>0) { logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(monsters.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMMONSTERS-"+filename,monsters); for(final Object O : monsters) { if(O instanceof MOB) CMLib.threads().deleteAllTicks((MOB)O); } } else { logError(scripted,"XMLLOAD","?","No MOBs in XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } return monsters; } protected List<MOB> generateMobsFromFile(final Environmental scripted, String filename, final String tagName, final String rest) { filename=filename.trim(); @SuppressWarnings("unchecked") List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest); if(monsters!=null) return monsters; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); monsters=new Vector<MOB>(); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null) { final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>(); final Map<String,String> eqParms=new HashMap<String,String>(); eqParms.putAll(CMParms.parseEQParms(rest.trim())); final String idName=tagName.toUpperCase(); try { CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>()); if((!(definedIDs.get(idName) instanceof XMLTag)) ||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("MOB"))) { logError(scripted,"XMLLOAD","?","Non-MOB tag '"+idName+"' for XML file: '"+filename+"' in "+thangName); return null; } final XMLTag piece=(XMLTag)definedIDs.get(idName); definedIDs.putAll(eqParms); try { CMLib.percolator().checkRequirements(piece, definedIDs); } catch(final CMException cme) { logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage()); return null; } CMLib.percolator().preDefineReward(piece, definedIDs); CMLib.percolator().defineReward(piece,definedIDs); monsters.addAll(CMLib.percolator().findMobs(piece, definedIDs)); CMLib.percolator().postProcess(definedIDs); if(monsters.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest,monsters); } catch(final CMException cex) { logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage()); return null; } } else { logError(scripted,"XMLLOAD","?","Invalid GEN XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName); return null; } return monsters; } protected List<Item> loadItemsFromFile(final Environmental scripted, String filename) { filename=filename.trim(); @SuppressWarnings("unchecked") List<Item> items=(List<Item>)Resources.getResource("RANDOMITEMS-"+filename); if(items!=null) return items; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } items=new Vector<Item>(); final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"ITEMS")!=null) { final String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null); if(error.length()>0) { logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"' in "+thangName); return null; } if(items.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } for(final Object O : items) { if(O instanceof Item) CMLib.threads().deleteTick((Item)O, -1); } Resources.submitResource("RANDOMITEMS-"+filename,items); } else { logError(scripted,"XMLLOAD","?","No ITEMS in XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Empty or invalid XML file: '"+filename+"' in "+thangName); return null; } return items; } protected List<Item> generateItemsFromFile(final Environmental scripted, String filename, final String tagName, final String rest) { filename=filename.trim(); @SuppressWarnings("unchecked") List<Item> items=(List<Item>)Resources.getResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest); if(items!=null) return items; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } items=new Vector<Item>(); final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null) { final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>(); final Map<String,String> eqParms=new HashMap<String,String>(); eqParms.putAll(CMParms.parseEQParms(rest.trim())); final String idName=tagName.toUpperCase(); try { CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>()); if((!(definedIDs.get(idName) instanceof XMLTag)) ||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("ITEM"))) { logError(scripted,"XMLLOAD","?","Non-ITEM tag '"+idName+"' for XML file: '"+filename+"' in "+thangName); return null; } final XMLTag piece=(XMLTag)definedIDs.get(idName); definedIDs.putAll(eqParms); try { CMLib.percolator().checkRequirements(piece, definedIDs); } catch(final CMException cme) { logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage()); return null; } CMLib.percolator().preDefineReward(piece, definedIDs); CMLib.percolator().defineReward(piece,definedIDs); items.addAll(CMLib.percolator().findItems(piece, definedIDs)); CMLib.percolator().postProcess(definedIDs); if(items.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"' in "+thangName); return null; } Resources.submitResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest,items); } catch(final CMException cex) { logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage()); return null; } } else { logError(scripted,"XMLLOAD","?","Not a GEN XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName); return null; } return items; } @SuppressWarnings("unchecked") protected Environmental findSomethingCalledThis(final String thisName, final MOB meMOB, final Room imHere, List<Environmental> OBJS, final boolean mob) { if(thisName.length()==0) return null; Environmental thing=null; Environmental areaThing=null; if(thisName.toUpperCase().trim().startsWith("FROMFILE ")) { try { List<? extends Environmental> V=null; if(mob) V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1)); else V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1)); if(V!=null) { final String name=CMParms.getPastBitClean(thisName,1); if(name.equalsIgnoreCase("ALL")) OBJS=(List<Environmental>)V; else if(name.equalsIgnoreCase("ANY")) { if(V.size()>0) areaThing=V.get(CMLib.dice().roll(1,V.size(),-1)); } else { areaThing=CMLib.english().fetchEnvironmental(V,name,true); if(areaThing==null) areaThing=CMLib.english().fetchEnvironmental(V,name,false); } } } catch(final Exception e) { } } else if(thisName.toUpperCase().trim().startsWith("FROMGENFILE ")) { try { List<? extends Environmental> V=null; final String filename=CMParms.getCleanBit(thisName, 1); final String name=CMParms.getCleanBit(thisName, 2); final String tagName=CMParms.getCleanBit(thisName, 3); final String theRest=CMParms.getPastBitClean(thisName,3); if(mob) V=generateMobsFromFile(null,filename, tagName, theRest); else V=generateItemsFromFile(null,filename, tagName, theRest); if(V!=null) { if(name.equalsIgnoreCase("ALL")) OBJS=(List<Environmental>)V; else if(name.equalsIgnoreCase("ANY")) { if(V.size()>0) areaThing=V.get(CMLib.dice().roll(1,V.size(),-1)); } else { areaThing=CMLib.english().fetchEnvironmental(V,name,true); if(areaThing==null) areaThing=CMLib.english().fetchEnvironmental(V,name,false); } } } catch(final Exception e) { } } else { if(!mob) areaThing=(meMOB!=null)?meMOB.findItem(thisName):null; try { if(areaThing==null) { final Area A=imHere.getArea(); final Vector<Environmental> all=new Vector<Environmental>(); if(mob) { all.addAll(CMLib.map().findInhabitants(A.getProperMap(),null,thisName,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(A.getProperMap(), null, thisName,100)); for(int a=all.size()-1;a>=0;a--) { if(!(all.elementAt(a) instanceof MOB)) all.removeElementAt(a); } if(all.size()>0) areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); else { all.addAll(CMLib.map().findInhabitantsFavorExact(CMLib.map().rooms(),null,thisName,false,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null, thisName,100)); for(int a=all.size()-1;a>=0;a--) { if(!(all.elementAt(a) instanceof MOB)) all.removeElementAt(a); } if(all.size()>0) thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); } } if(all.size()==0) { all.addAll(CMLib.map().findRoomItems(A.getProperMap(), null,thisName,true,100)); if(all.size()==0) all.addAll(CMLib.map().findInventory(A.getProperMap(), null,thisName,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(A.getProperMap(), null,thisName,100)); if(all.size()>0) areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); else { all.addAll(CMLib.map().findRoomItems(CMLib.map().rooms(), null,thisName,true,100)); if(all.size()==0) all.addAll(CMLib.map().findInventory(CMLib.map().rooms(), null,thisName,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null,thisName,100)); if(all.size()>0) thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); } } } } catch(final NoSuchElementException nse) { } } if(areaThing!=null) OBJS.add(areaThing); else if(thing!=null) OBJS.add(thing); if(OBJS.size()>0) return OBJS.get(0); return null; } protected PhysicalAgent getArgumentMOB(final String str, final MOB source, final MOB monster, final Environmental target, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp); } protected PhysicalAgent getArgumentItem(String str, final MOB source, final MOB monster, final PhysicalAgent scripted, final Environmental target, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { if(str.length()<2) return null; if(str.charAt(0)=='$') { if(Character.isDigit(str.charAt(1))) { Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))]; if(O instanceof PhysicalAgent) return (PhysicalAgent)O; else if((O instanceof List)&&(str.length()>3)&&(str.charAt(2)=='.')) { final List<?> V=(List<?>)O; String back=str.substring(2); if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length())&&(Character.isDigit(back.charAt(x)))) x++; final int y=CMath.s_int(back.substring(1,x).trim()); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) return null; O=V.get(y); if(O instanceof PhysicalAgent) return (PhysicalAgent)O; } str=O.toString(); // will fall through } } else if(O!=null) str=O.toString(); // will fall through else return null; } else switch(str.charAt(1)) { case 'a': return (lastKnownLocation != null) ? lastKnownLocation.getArea() : null; case 'B': case 'b': return (lastLoaded instanceof PhysicalAgent) ? (PhysicalAgent) lastLoaded : null; case 'N': case 'n': return ((source == backupMOB) && (backupMOB != null) && (monster != scripted)) ? scripted : source; case 'I': case 'i': return scripted; case 'T': case 't': return ((target == backupMOB) && (backupMOB != null) && (monster != scripted)) ? scripted : (target instanceof PhysicalAgent) ? (PhysicalAgent) target : null; case 'O': case 'o': return primaryItem; case 'P': case 'p': return secondaryItem; case 'd': case 'D': return lastKnownLocation; case 'F': case 'f': if ((monster != null) && (monster.amFollowing() != null)) return monster.amFollowing(); return null; case 'r': case 'R': return getRandPC(monster, tmp, lastKnownLocation); case 'c': case 'C': return getRandAnyone(monster, tmp, lastKnownLocation); case 'w': return primaryItem != null ? primaryItem.owner() : null; case 'W': return secondaryItem != null ? secondaryItem.owner() : null; case 'x': case 'X': if (lastKnownLocation != null) { if ((str.length() > 2) && (CMLib.directions().getGoodDirectionCode("" + str.charAt(2)) >= 0)) return lastKnownLocation.getExitInDir(CMLib.directions().getGoodDirectionCode("" + str.charAt(2))); int i = 0; Exit E = null; while (((++i) < 100) || (E != null)) E = lastKnownLocation.getExitInDir(CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1)); return E; } return null; case '[': { final int x = str.substring(2).indexOf(']'); if (x >= 0) { String mid = str.substring(2).substring(0, x); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) return Q.getQuestItem(num); } } break; } case '{': { final int x = str.substring(2).indexOf('}'); if (x >= 0) { String mid = str.substring(2).substring(0, x).trim(); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) { final MOB M=Q.getQuestMob(num); return M; } } } break; } } } if(lastKnownLocation!=null) { str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str); Environmental E=null; if(str.indexOf('#')>0) E=CMLib.map().getRoom(str); if(E==null) E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str); if(E==null) E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Wearable.FILTER_ANY); if(E==null) E=lastKnownLocation.findItem(str); if((E==null)&&(monster!=null)) E=monster.findItem(str); if(E==null) E=CMLib.players().getPlayerAllHosts(str); if((E==null)&&(source!=null)) E=source.findItem(str); if(E instanceof PhysicalAgent) return (PhysicalAgent)E; } return null; } private String makeNamedString(final Object O) { if(O instanceof List) return makeParsableString((List<?>)O); else if(O instanceof Room) return ((Room)O).displayText(null); else if(O instanceof Environmental) return ((Environmental)O).Name(); else if(O!=null) return O.toString(); return ""; } private String makeParsableString(final List<?> V) { if((V==null)||(V.size()==0)) return ""; if(V.get(0) instanceof String) return CMParms.combineQuoted(V,0); final StringBuffer ret=new StringBuffer(""); String S=null; for(int v=0;v<V.size();v++) { S=makeNamedString(V.get(v)).trim(); if(S.length()==0) ret.append("? "); else if(S.indexOf(' ')>=0) ret.append("\""+S+"\" "); else ret.append(S+" "); } return ret.toString(); } @Override public String varify(final MOB source, final Environmental target, final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp, String varifyable) { int t=varifyable.indexOf('$'); if((monster!=null)&&(monster.location()!=null)) lastKnownLocation=monster.location(); if(lastKnownLocation==null) { lastKnownLocation=source.location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } else if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; MOB randMOB=null; while((t>=0)&&(t<varifyable.length()-1)) { final char c=varifyable.charAt(t+1); String middle=""; final String front=varifyable.substring(0,t); String back=varifyable.substring(t+2); if(Character.isDigit(c)) middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]); else switch(c) { case '@': if ((t < varifyable.length() - 2) && (Character.isLetter(varifyable.charAt(t + 2))||Character.isDigit(varifyable.charAt(t + 2)))) { final Environmental E = getArgumentItem("$" + varifyable.charAt(t + 2), source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(back.length()>0) back=back.substring(1); middle = (E == null) ? "null" : "" + E; } break; case 'a': if (lastKnownLocation != null) middle = lastKnownLocation.getArea().name(); break; // case 'a': case 'A': // unnecessary, since, in coffeemud, this is part of the // name break; case 'b': middle = lastLoaded != null ? lastLoaded.name() : ""; break; case 'B': middle = lastLoaded != null ? lastLoaded.displayText() : ""; break; case 'c': case 'C': randMOB = getRandAnyone(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.name(); break; case 'd': middle = (lastKnownLocation != null) ? lastKnownLocation.displayText(monster) : ""; break; case 'D': middle = (lastKnownLocation != null) ? lastKnownLocation.description(monster) : ""; break; case 'e': if (source != null) middle = source.charStats().heshe(); break; case 'E': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().heshe(); break; case 'f': if ((monster != null) && (monster.amFollowing() != null)) middle = monster.amFollowing().name(); break; case 'F': if ((monster != null) && (monster.amFollowing() != null)) middle = monster.amFollowing().charStats().heshe(); break; case 'g': middle = ((msg == null) ? "" : msg.toLowerCase()); break; case 'G': middle = ((msg == null) ? "" : msg); break; case 'h': if (monster != null) middle = monster.charStats().himher(); break; case 'H': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.charStats().himher(); break; case 'i': if (monster != null) middle = monster.name(); break; case 'I': if (monster != null) middle = monster.displayText(); break; case 'j': if (monster != null) middle = monster.charStats().heshe(); break; case 'J': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.charStats().heshe(); break; case 'k': if (monster != null) middle = monster.charStats().hisher(); break; case 'K': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.charStats().hisher(); break; case 'l': if (lastKnownLocation != null) { final StringBuffer str = new StringBuffer(""); for (int i = 0; i < lastKnownLocation.numInhabitants(); i++) { final MOB M = lastKnownLocation.fetchInhabitant(i); if ((M != null) && (M != monster) && (CMLib.flags().canBeSeenBy(M, monster))) str.append("\"" + M.name() + "\" "); } middle = str.toString(); } break; case 'L': if (lastKnownLocation != null) { final StringBuffer str = new StringBuffer(""); for (int i = 0; i < lastKnownLocation.numItems(); i++) { final Item I = lastKnownLocation.getItem(i); if ((I != null) && (I.container() == null) && (CMLib.flags().canBeSeenBy(I, monster))) str.append("\"" + I.name() + "\" "); } middle = str.toString(); } break; case 'm': if (source != null) middle = source.charStats().hisher(); break; case 'M': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().hisher(); break; case 'n': case 'N': if (source != null) middle = source.name(); break; case 'o': case 'O': if (primaryItem != null) middle = primaryItem.name(); break; case 'p': case 'P': if (secondaryItem != null) middle = secondaryItem.name(); break; case 'r': case 'R': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.name(); break; case 's': if (source != null) middle = source.charStats().himher(); break; case 'S': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().himher(); break; case 't': case 'T': if (target != null) middle = target.name(); break; case 'w': middle = primaryItem != null ? primaryItem.owner().Name() : middle; break; case 'W': middle = secondaryItem != null ? secondaryItem.owner().Name() : middle; break; case 'x': case 'X': if (lastKnownLocation != null) { middle = ""; Exit E = null; int dir = -1; if ((t < varifyable.length() - 2) && (CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2)) >= 0)) { dir = CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2)); E = lastKnownLocation.getExitInDir(dir); } else { int i = 0; while (((++i) < 100) || (E != null)) { dir = CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1); E = lastKnownLocation.getExitInDir(dir); } } if ((dir >= 0) && (E != null)) { if (c == 'x') middle = CMLib.directions().getDirectionName(dir); else middle = E.name(); } } break; case 'y': if (source != null) middle = source.charStats().sirmadam(); break; case 'Y': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().sirmadam(); break; case '<': { final int x = back.indexOf('>'); if (x >= 0) { String mid = back.substring(0, x); final int y = mid.indexOf(' '); Environmental E = null; String arg1 = ""; if (y >= 0) { arg1 = mid.substring(0, y).trim(); E = getArgumentItem(arg1, source, monster, monster, target, primaryItem, secondaryItem, msg, tmp); mid = mid.substring(y + 1).trim(); } if (arg1.length() > 0) middle = getVar(E, arg1, mid, source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp); back = back.substring(x + 1); } break; } case '[': { middle = ""; final int x = back.indexOf(']'); if (x >= 0) { String mid = back.substring(0, x); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) middle = Q.getQuestItemName(num); } back = back.substring(x + 1); } break; } case '{': { middle = ""; final int x = back.indexOf('}'); if (x >= 0) { String mid = back.substring(0, x).trim(); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) middle = Q.getQuestMobName(num); } back = back.substring(x + 1); } break; } case '%': { middle = ""; final int x = back.indexOf('%'); if (x >= 0) { middle = functify(scripted, source, target, monster, primaryItem, secondaryItem, msg, tmp, back.substring(0, x).trim()); back = back.substring(x + 1); } break; } } if((back.startsWith(".")) &&(back.length()>1)) { if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if(back.startsWith(".LENGTH#")) { middle=""+CMParms.parse(middle).size(); back=back.substring(8); } else if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length()) &&(Character.isDigit(back.charAt(x)))) x++; final int y=CMath.s_int(back.substring(1,x).trim()); back=back.substring(x); final boolean rest=back.startsWith(".."); if(rest) back=back.substring(2); final Vector<String> V=CMParms.parse(middle); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) middle=""; else if(rest) middle=CMParms.combine(V,y); else middle=V.elementAt(y); } } } varifyable=front+middle+back; t=varifyable.indexOf('$'); } return varifyable; } protected PairList<String,String> getScriptVarSet(final String mobname, final String varname) { final PairList<String,String> set=new PairVector<String,String>(); if(mobname.equals("*")) { for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { final String key=k.next(); if(key.startsWith("SCRIPTVAR-")) { @SuppressWarnings("unchecked") final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource(key); if(varname.equals("*")) { if(H!=null) { for(final Enumeration<String> e=H.keys();e.hasMoreElements();) { final String vn=e.nextElement(); set.add(key.substring(10),vn); } } } else set.add(key.substring(10),varname); } } } else { @SuppressWarnings("unchecked") final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource("SCRIPTVAR-"+mobname); if(varname.equals("*")) { if(H!=null) { for(final Enumeration<String> e=H.keys();e.hasMoreElements();) { final String vn=e.nextElement(); set.add(mobname,vn); } } } else set.add(mobname,varname); } return set; } protected String getStatValue(final Environmental E, final String arg2) { boolean found=false; String val=""; final String uarg2=arg2.toUpperCase().trim(); for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equals(uarg2)) { val=E.getStat(uarg2); found=true; break; } } if((!found)&&(E instanceof MOB)) { final MOB M=(MOB)E; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2)) { val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); //yes, this is right found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } } } if(!found) { for(int i=0;i<M.phyStats().getStatCodes().length;i++) { if(M.phyStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(uarg2.startsWith("BASE"))) { for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } } if((!found)&&(uarg2.equals("STINK"))) { found=true; val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT); } if((!found) &&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,uarg2)!=null)) { found=true; val=CMLib.coffeeMaker().getAnyGenStat(M, uarg2); } } if((!found) &&(E instanceof Item) &&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,uarg2)!=null)) { found=true; val=CMLib.coffeeMaker().getAnyGenStat((Item)E, uarg2); } if((!found) &&(E instanceof Physical) &&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,uarg2)!=null)) { found=true; val=CMLib.coffeeMaker().getAnyGenStat((Physical)E, uarg2); } if(!found) return null; return val; } protected String getGStatValue(final Environmental E, String arg2) { if(E==null) return null; boolean found=false; String val=""; for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equalsIgnoreCase(arg2)) { val=E.getStat(arg2); found=true; break; } } if(!found) if(E instanceof MOB) { arg2=arg2.toUpperCase().trim(); final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2); if(element != null) { val=CMLib.coffeeMaker().getGenMobStat((MOB)E,element.name()); found=true; } if(!found) { final MOB M=(MOB)E; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equals(arg2)||CharStats.CODES.DESC(i).equals(arg2)) { val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equals(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } } } if(!found) { for(int i=0;i<M.phyStats().getStatCodes().length;i++) { if(M.phyStats().getStatCodes()[i].equals(arg2)) { val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equals(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(arg2.startsWith("BASE"))) { final String arg4=arg2.substring(4); for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equals(arg4)) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } if(!found) { for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equals(arg4)||CharStats.CODES.DESC(i).equals(arg4)) { val=""+M.baseCharStats().getStat(CharStats.CODES.NAME(i)); found=true; break; } } } } if((!found)&&(arg2.equals("STINK"))) { found=true; val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT); } } } else if(E instanceof Item) { final GenericBuilder.GenItemCode code = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class, arg2.toUpperCase().trim()); if(code != null) { val=CMLib.coffeeMaker().getGenItemStat((Item)E,code.name()); found=true; } } if((!found) &&(E instanceof Physical)) { if(CMLib.coffeeMaker().isAnyGenStat((Physical)E, arg2.toUpperCase().trim())) return CMLib.coffeeMaker().getAnyGenStat((Physical)E, arg2.toUpperCase().trim()); if((!found)&&(arg2.startsWith("BASE"))) { final String arg4=arg2.substring(4); for(int i=0;i<((Physical)E).basePhyStats().getStatCodes().length;i++) { if(((Physical)E).basePhyStats().getStatCodes()[i].equals(arg4)) { val=((Physical)E).basePhyStats().getStat(((Physical)E).basePhyStats().getStatCodes()[i]); found=true; break; } } } } if(found) return val; return null; } @Override public void setVar(final String baseName, String key, String val) { final PairList<String,String> vars=getScriptVarSet(baseName,key); for(int v=0;v<vars.size();v++) { final String name=vars.elementAtFirst(v); key=vars.elementAtSecond(v).toUpperCase(); @SuppressWarnings("unchecked") Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+name); if((H==null)&&(defaultQuestName!=null)&&(defaultQuestName.length()>0)) { final MOB M=CMLib.players().getPlayerAllHosts(name); if(M!=null) { for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null) &&(SE!=this) &&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName())) &&(SE.isVar(name,key))) { SE.setVar(name,key,val); return; } } } } if(H==null) { if(val.length()==0) continue; H=new Hashtable<String,String>(); resources._submitResource("SCRIPTVAR-"+name,H); } if(val.length()>0) { switch(val.charAt(0)) { case '+': if(val.equals("++")) { String num=H.get(key); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())+1); } else { String num=H.get(key); // add via +number form if(CMath.isNumber(val.substring(1).trim())) { if(num==null) num="0"; val=val.substring(1); final int amount=CMath.s_int(val.trim()); val=Integer.toString(CMath.s_int(num.trim())+amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; } break; case '-': if(val.equals("--")) { String num=H.get(key); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())-1); } else { // subtract -number form String num=H.get(key); if(CMath.isNumber(val.substring(1).trim())) { val=val.substring(1); final int amount=CMath.s_int(val.trim()); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())-amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; } break; case '*': { // multiply via *number form String num=H.get(key); if(CMath.isNumber(val.substring(1).trim())) { val=val.substring(1); final int amount=CMath.s_int(val.trim()); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())*amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; break; } case '/': { // divide /number form String num=H.get(key); if(CMath.isNumber(val.substring(1).trim())) { val=val.substring(1); final int amount=CMath.s_int(val.trim()); if(num==null) num="0"; if(amount==0) Log.errOut("Scripting","Scripting SetVar error: Division by 0: "+name+"/"+key+"="+val); else val=Integer.toString(CMath.s_int(num.trim())/amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; break; } default: break; } } if(H.containsKey(key)) H.remove(key); if(val.trim().length()>0) H.put(key,val); if(H.size()==0) resources._removeResource("SCRIPTVAR-"+name); } } @Override public String[] parseEval(final String evaluable) throws ScriptParseException { final int STATE_MAIN=0; final int STATE_INFUNCTION=1; final int STATE_INFUNCQUOTE=2; final int STATE_POSTFUNCTION=3; final int STATE_POSTFUNCEVAL=4; final int STATE_POSTFUNCQUOTE=5; final int STATE_MAYFUNCTION=6; buildHashes(); final List<String> V=new ArrayList<String>(); if((evaluable==null)||(evaluable.trim().length()==0)) return new String[]{}; final char[] evalC=evaluable.toCharArray(); int state=0; int dex=0; char lastQuote='\0'; String s=null; int depth=0; for(int c=0;c<evalC.length;c++) { switch(state) { case STATE_MAIN: { if(Character.isWhitespace(evalC[c])) { s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) { s=s.toUpperCase(); V.add(s); dex=c+1; if(funcH.containsKey(s)) state=STATE_MAYFUNCTION; else if(!connH.containsKey(s)) throw new ScriptParseException("Unknown keyword: "+s); } } else if(Character.isLetter(evalC[c]) ||(Character.isDigit(evalC[c]) &&(c>0)&&Character.isLetter(evalC[c-1]) &&(c<evalC.length-1) &&Character.isLetter(evalC[c+1]))) { /* move along */ } else { switch(evalC[c]) { case '!': { if(c==evalC.length-1) throw new ScriptParseException("Bad Syntax on last !"); V.add("NOT"); dex=c+1; break; } case '(': { s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) { s=s.toUpperCase(); V.add(s); V.add("("); dex=c+1; if(funcH.containsKey(s)) state=STATE_INFUNCTION; else if(connH.containsKey(s)) state=STATE_MAIN; else throw new ScriptParseException("Unknown keyword: "+s); } else { V.add("("); depth++; dex=c+1; } break; } case ')': s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) throw new ScriptParseException("Bad syntax before ) at: "+s); if(depth==0) throw new ScriptParseException("Unmatched ) character"); V.add(")"); depth--; dex=c+1; break; default: throw new ScriptParseException("Unknown character at: "+new String(evalC,dex,c-dex+1).trim()+": "+evaluable); } } break; } case STATE_MAYFUNCTION: { if(evalC[c]=='(') { V.add("("); dex=c+1; state=STATE_INFUNCTION; } else if(!Character.isWhitespace(evalC[c])) throw new ScriptParseException("Expected ( at "+evalC[c]+": "+evaluable); break; } case STATE_POSTFUNCTION: { if(!Character.isWhitespace(evalC[c])) { switch(evalC[c]) { case '=': case '>': case '<': case '!': { if(c==evalC.length-1) throw new ScriptParseException("Bad Syntax on last "+evalC[c]); if(!Character.isWhitespace(evalC[c+1])) { s=new String(evalC,c,2); if((!signH.containsKey(s))&&(evalC[c]!='!')) s=""+evalC[c]; } else s=""+evalC[c]; if(!signH.containsKey(s)) { c=dex-1; state=STATE_MAIN; break; } V.add(s); dex=c+(s.length()); c=c+(s.length()-1); state=STATE_POSTFUNCEVAL; break; } default: c=dex-1; state=STATE_MAIN; break; } } break; } case STATE_INFUNCTION: { if(evalC[c]==')') { V.add(new String(evalC,dex,c-dex)); V.add(")"); dex=c+1; state=STATE_POSTFUNCTION; } else if((evalC[c]=='\'')||(evalC[c]=='`')) { lastQuote=evalC[c]; state=STATE_INFUNCQUOTE; } break; } case STATE_INFUNCQUOTE: { if((evalC[c]==lastQuote) &&((c==evalC.length-1) ||((!Character.isLetter(evalC[c-1])) ||(!Character.isLetter(evalC[c+1]))))) state=STATE_INFUNCTION; break; } case STATE_POSTFUNCQUOTE: { if(evalC[c]==lastQuote) { if((V.size()>2) &&(signH.containsKey(V.get(V.size()-1))) &&(V.get(V.size()-2).equals(")"))) { final String sign=V.get(V.size()-1); V.remove(V.size()-1); V.remove(V.size()-1); final String prev=V.get(V.size()-1); if(prev.equals("(")) s=sign+" "+new String(evalC,dex+1,c-dex); else { V.remove(V.size()-1); s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex); } V.add(s); V.add(")"); dex=c+1; state=STATE_MAIN; } else throw new ScriptParseException("Bad postfunc Eval somewhere"); } break; } case STATE_POSTFUNCEVAL: { if(Character.isWhitespace(evalC[c])) { s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) { if((V.size()>1) &&(signH.containsKey(V.get(V.size()-1))) &&(V.get(V.size()-2).equals(")"))) { final String sign=V.get(V.size()-1); V.remove(V.size()-1); V.remove(V.size()-1); final String prev=V.get(V.size()-1); if(prev.equals("(")) s=sign+" "+new String(evalC,dex+1,c-dex); else { V.remove(V.size()-1); s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex); } V.add(s); V.add(")"); dex=c+1; state=STATE_MAIN; } else throw new ScriptParseException("Bad postfunc Eval somewhere"); } } else if(Character.isLetterOrDigit(evalC[c])) { /* move along */ } else if((evalC[c]=='\'')||(evalC[c]=='`')) { s=new String(evalC,dex,c-dex).trim(); if(s.length()==0) { lastQuote=evalC[c]; state=STATE_POSTFUNCQUOTE; } } break; } } } if((state==STATE_POSTFUNCQUOTE) ||(state==STATE_INFUNCQUOTE)) throw new ScriptParseException("Unclosed "+lastQuote+" in "+evaluable); if(depth>0) throw new ScriptParseException("Unclosed ( in "+evaluable); return CMParms.toStringArray(V); } public void pushEvalBoolean(final List<Object> stack, boolean trueFalse) { if(stack.size()>0) { final Object O=stack.get(stack.size()-1); if(O instanceof Integer) { final int connector=((Integer)O).intValue(); stack.remove(stack.size()-1); if((stack.size()>0) &&((stack.get(stack.size()-1) instanceof Boolean))) { final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue(); stack.remove(stack.size()-1); switch(connector) { case CONNECTOR_AND: trueFalse = preTrueFalse && trueFalse; break; case CONNECTOR_OR: trueFalse = preTrueFalse || trueFalse; break; case CONNECTOR_ANDNOT: trueFalse = preTrueFalse && (!trueFalse); break; case CONNECTOR_NOT: case CONNECTOR_ORNOT: trueFalse = preTrueFalse || (!trueFalse); break; } } else switch(connector) { case CONNECTOR_ANDNOT: case CONNECTOR_NOT: case CONNECTOR_ORNOT: trueFalse = !trueFalse; break; default: break; } } else if(O instanceof Boolean) { final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue(); stack.remove(stack.size()-1); trueFalse=preTrueFalse&&trueFalse; } } stack.add(trueFalse?Boolean.TRUE:Boolean.FALSE); } /** * Returns the index, in the given string vector, of the given string, starting * from the given index. If the string to search for contains more than one * "word", where a word is defined in space-delimited terms respecting double-quotes, * then it will return the index at which all the words in the parsed search string * are found in the given string list. * @param V the string list to search in * @param str the string to search for * @param start the index to start at (0 is good) * @return the index at which the search string was found in the string list, or -1 */ private static int strIndex(final Vector<String> V, final String str, final int start) { int x=V.indexOf(str,start); if(x>=0) return x; final List<String> V2=CMParms.parse(str); if(V2.size()==0) return -1; x=V.indexOf(V2.get(0),start); boolean found=false; while((x>=0)&&((x+V2.size())<=V.size())&&(!found)) { found=true; for(int v2=1;v2<V2.size();v2++) { if(!V.get(x+v2).equals(V2.get(v2))) { found=false; break; } } if(!found) x=V.indexOf(V2.get(0),x+1); } if(found) return x; return -1; } /** * Weird method. Accepts a string list, a combiner (see below), a string buffer to search for, * and a previously found index. The stringbuffer is always cleared during this call. * If the stringbuffer was empty, the previous found index is returned. Otherwise: * If the combiner is '&', the first index of the given stringbuffer in the string list is returned (or -1). * If the combiner is '|', the previous index is returned if it was found, otherwise the first index * of the given stringbuffer in the string list is returned (or -1). * If the combiner is '&gt;', then the previous index is returned if it was not found (-1), otherwise the * next highest found stringbuffer since the last string list search is returned, or (-1) if no more found. * If the combiner is '&lt;', then the previous index is returned if it was not found (-1), otherwise the * first found stringbuffer index is returned if it is lower than the previously found index. * Other combiners return -1. * @param V the string list to search * @param combiner the combiner, either &,|,&lt;,or &gt;. * @param buf the stringbuffer to search for, which is always cleared * @param lastIndex the previously found index * @return the result of the search */ private static int stringContains(final Vector<String> V, final char combiner, final StringBuffer buf, int lastIndex) { final String str=buf.toString().trim(); if(str.length()==0) return lastIndex; buf.setLength(0); switch (combiner) { case '&': lastIndex = strIndex(V, str, 0); return lastIndex; case '|': if (lastIndex >= 0) return lastIndex; return strIndex(V, str, 0); case '>': if (lastIndex < 0) return lastIndex; return strIndex(V, str, lastIndex + 1); case '<': { if (lastIndex < 0) return lastIndex; final int newIndex = strIndex(V, str, 0); if (newIndex < lastIndex) return newIndex; return -1; } } return -1; } /** * Main workhorse of the stringcontains mobprog function. * @param V parsed string to search * @param str the coded search function * @param index a 1-dim array of the index in the coded search str to start the search at * @param depth the number of close parenthesis to expect * @return the last index in the coded search function evaluated */ private static int stringContains(final Vector<String> V, final char[] str, final int[] index, final int depth) { final StringBuffer buf=new StringBuffer(""); int lastIndex=0; boolean quoteMode=false; char combiner='&'; for(int i=index[0];i<str.length;i++) { switch(str[i]) { case ')': if((depth>0)&&(!quoteMode)) { index[0]=i; return stringContains(V,combiner,buf,lastIndex); } buf.append(str[i]); break; case ' ': buf.append(str[i]); break; case '&': case '|': case '>': case '<': if(quoteMode) buf.append(str[i]); else { lastIndex=stringContains(V,combiner,buf,lastIndex); combiner=str[i]; } break; case '(': if(!quoteMode) { lastIndex=stringContains(V,combiner,buf,lastIndex); index[0]=i+1; final int newIndex=stringContains(V,str,index,depth+1); i=index[0]; switch(combiner) { case '&': if((lastIndex<0)||(newIndex<0)) lastIndex=-1; break; case '|': if(newIndex>=0) lastIndex=newIndex; break; case '>': if(newIndex<=lastIndex) lastIndex=-1; else lastIndex=newIndex; break; case '<': if((newIndex<0)||(newIndex>=lastIndex)) lastIndex=-1; else lastIndex=newIndex; break; } } else buf.append(str[i]); break; case '\"': quoteMode=(!quoteMode); break; case '\\': if(i<str.length-1) { buf.append(str[i+1]); i++; } break; default: if(Character.isLetter(str[i])) buf.append(Character.toLowerCase(str[i])); else buf.append(str[i]); break; } } return stringContains(V,combiner,buf,lastIndex); } /** * As the name implies, this is the implementation of the stringcontains mobprog function * @param str1 the string to search in * @param str2 the coded search expression * @return the index of the found string in the first string */ protected final static int stringContainsFunctionImpl(final String str1, final String str2) { final StringBuffer buf1=new StringBuffer(str1.toLowerCase()); for(int i=buf1.length()-1;i>=0;i--) { switch(buf1.charAt(i)) { case ' ': case '\"': case '`': break; case '\'': buf1.setCharAt(i, '`'); break; default: if(!Character.isLetterOrDigit(buf1.charAt(i))) buf1.setCharAt(i,' '); break; } } final StringBuffer buf2=new StringBuffer(str2.toLowerCase()); for(int i=buf2.length()-1;i>=0;i--) { switch(buf2.charAt(i)) { case ' ': case '\"': case '`': break; case '\'': buf2.setCharAt(i, '`'); break; default: if(!Character.isLetterOrDigit(buf2.charAt(i))) buf2.setCharAt(i,' '); break; } } final Vector<String> V=CMParms.parse(buf1.toString()); return stringContains(V,buf2.toString().toCharArray(),new int[]{0},0); } @Override public boolean eval(final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, Object[] tmp, final String[][] eval, final int startEval) { String[] tt=eval[0]; if(tmp == null) tmp = newObjs(); final List<Object> stack=new ArrayList<Object>(); for(int t=startEval;t<tt.length;t++) { if(tt[t].equals("(")) stack.add(tt[t]); else if(tt[t].equals(")")) { if(stack.size()>0) { if((!(stack.get(stack.size()-1) instanceof Boolean)) ||(stack.size()==1) ||(!(stack.get(stack.size()-2)).equals("("))) { logError(scripted,"EVAL","SYNTAX",") Format error: "+CMParms.toListString(tt)); return false; } final boolean b=((Boolean)stack.get(stack.size()-1)).booleanValue(); stack.remove(stack.size()-1); stack.remove(stack.size()-1); pushEvalBoolean(stack,b); } } else if(connH.containsKey(tt[t])) { Integer curr=connH.get(tt[t]); if((stack.size()>0) &&(stack.get(stack.size()-1) instanceof Integer)) { final int old=((Integer)stack.get(stack.size()-1)).intValue(); stack.remove(stack.size()-1); curr=Integer.valueOf(CONNECTOR_MAP[old][curr.intValue()]); } stack.add(curr); } else if(funcH.containsKey(tt[t])) { final Integer funcCode=funcH.get(tt[t]); if((t==tt.length-1) ||(!tt[t+1].equals("("))) { logError(scripted,"EVAL","SYNTAX","No ( for fuction "+tt[t]+": "+CMParms.toListString(tt)); return false; } t+=2; int tlen=0; while(((t+tlen)<tt.length)&&(!tt[t+tlen].equals(")"))) tlen++; if((t+tlen)==tt.length) { logError(scripted,"EVAL","SYNTAX","No ) for fuction "+tt[t-1]+": "+CMParms.toListString(tt)); return false; } tickStatus=Tickable.STATUS_MISC+funcCode.intValue(); final String funcParms=tt[t]; boolean returnable=false; switch(funcCode.intValue()) { case 1: // rand { String num=funcParms; if(num.endsWith("%")) num=num.substring(0,num.length()-1); final int arg=CMath.s_int(num); if(CMLib.dice().rollPercentage()<arg) returnable=true; else returnable=false; break; } case 2: // has { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HAS","Syntax","'"+eval[0][t]+"' in "+CMParms.toListString(eval[0])); return returnable; } if(E==null) returnable=false; else { if((E instanceof MOB) &&(((MOB)E).findItem(arg2)!=null)) returnable = true; else if((E instanceof Room) &&(((Room)E).findItem(arg2)!=null)) returnable=true; else { final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { if(E2!=null) returnable=((MOB)E).isMine(E2); else returnable=(((MOB)E).findItem(arg2)!=null); } else if(E instanceof Item) returnable=CMLib.english().containsString(E.name(),arg2); else if(E instanceof Room) { if(E2 instanceof Item) returnable=((Room)E).isContent((Item)E2); else returnable=(((Room)E).findItem(null,arg2)!=null); } else returnable=false; } } break; } case 74: // hasnum { if (tlen == 1) tt = parseBits(eval, t, "cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=tt[t+2]; final String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((value.length()==0)||(item.length()==0)||(cmp.length()==0)) { logError(scripted,"HASNUM","Syntax",funcParms); return returnable; } Item I=null; int num=0; if(E==null) returnable=false; else if(E instanceof MOB) { final MOB M=(MOB)E; for(int i=0;i<M.numItems();i++) { I=M.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Room) { final Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else returnable=false; break; } case 67: // hastitle { if (tlen == 1) tt = parseBits(eval, t, "cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASTITLE","Syntax",funcParms); return returnable; } if(E instanceof MOB) { final MOB M=(MOB)E; returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2)); } else returnable=false; break; } case 3: // worn { if (tlen == 1) tt = parseBits(eval, t, "cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"WORN","Syntax",funcParms); return returnable; } if(E==null) returnable=false; else if(E instanceof MOB) returnable=(((MOB)E).fetchItem(null,Wearable.FILTER_WORNONLY,arg2)!=null); else if(E instanceof Item) returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Wearable.IN_INVENTORY))); else returnable=false; break; } case 4: // isnpc { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isMonster(); break; } case 87: // isbirthday { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else { final MOB mob=(MOB)E; if(mob.playerStats()==null) returnable=false; else { final TimeClock C=CMLib.time().localClock(mob.getStartRoom()); final int month=C.getMonth(); final int day=C.getDayOfMonth(); final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY]; final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH]; if((C.getYear()==mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_LASTYEARCELEBRATED]) &&((month==bmonth)&&(day==bday))) returnable=true; else returnable=false; } } break; } case 5: // ispc { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=!((MOB)E).isMonster(); break; } case 6: // isgood { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().isGood(P); break; } case 8: // isevil { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().isEvil(P); break; } case 9: // isneutral { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().isNeutral(P); break; } case 54: // isalive { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) returnable=true; else returnable=false; break; } case 58: // isable { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) returnable=((MOB)E).fetchExpertise(X.ID())!=null; else returnable=((MOB)E).findAbility(arg2)!=null; } else returnable=false; break; } case 112: // cansee { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(!(MP instanceof MOB)) returnable=false; else { final MOB M=(MOB)MP; final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().canBeSeenBy(P, M); } break; } case 113: // canhear { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(!(MP instanceof MOB)) returnable=false; else { final MOB M=(MOB)MP; final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().canBeHeardMovingBy(P, M); } break; } case 59: // isopen { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); returnable=false; if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } break; } case 60: // islocked { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); returnable=false; if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isLocked(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isLocked(); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isLocked(); } break; } case 10: // isfight { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isInCombat(); break; } case 11: // isimmort { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,CMSecurity.SecFlag.IMMORT); break; } case 12: // ischarmed { final String arg1=CMParms.cleanBit(funcParms); final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0; break; } case 15: // isfollow { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(((MOB)E).amFollowing()==null) returnable=false; else if(((MOB)E).amFollowing().location()!=lastKnownLocation) returnable=false; else returnable=true; break; } case 73: // isservant { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null)) returnable=false; else if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0)) returnable=false; else if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null) returnable=false; else returnable=true; break; } case 95: // isspeaking { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null)) returnable=false; else { final MOB TM=(MOB)E; final Language L=CMLib.utensils().getLanguageSpoken(TM); if((L!=null) &&(!L.ID().equalsIgnoreCase("Common")) &&(L.ID().equalsIgnoreCase(arg2)||L.Name().equalsIgnoreCase(arg2)||arg2.equalsIgnoreCase("any"))) returnable=true; else if(arg2.equalsIgnoreCase("common")||arg2.equalsIgnoreCase("none")) returnable=true; else returnable=false; } break; } case 55: // ispkill { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL)) returnable=true; else returnable=false; break; } case 7: // isname { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.english().containsString(E.name(),arg2); break; } case 56: // name { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME"); break; } case 75: // currency { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY"); break; } case 61: // strin { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2; if(tt[t+1].equals("$$r")) arg2=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(monster)); else arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final List<String> V=CMParms.parse(arg1.toUpperCase()); returnable=V.contains(arg2.toUpperCase()); break; } case 62: // callfunc { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); String found=null; boolean validFunc=false; final List<DVector> scripts=getScripts(); String trigger=null; String[] ttrigger=null; for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); ttrigger=(String[])script2.elementAt(0,2); if(getTriggerCode(trigger,ttrigger)==17) { final String fnamed= (ttrigger!=null) ?ttrigger[1] :CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) logError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else if(found!=null) returnable=!(found.trim().length()==0); else returnable=false; break; } case 14: // affected { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else { final Ability A=CMClass.findAbility(arg2); if(A!=null) arg2=A.ID(); returnable=(P.fetchEffect(arg2)!=null); } break; } case 69: // isbehave { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final PhysicalAgent P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else { final Behavior B=CMClass.findBehavior(arg2); if(B!=null) arg2=B.ID(); returnable=(P.fetchBehavior(arg2)!=null); } break; } case 70: // ipaddress { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster())) returnable=false; else returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS"); break; } case 28: // questwinner { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) arg1=E.Name(); if(arg2.equalsIgnoreCase("previous")) { returnable=true; final String quest=defaultQuestName(); if((quest!=null) &&(quest.length()>0)) { ScriptingEngine prevE=null; final List<ScriptingEngine> list=new LinkedList<ScriptingEngine>(); for(final Enumeration<ScriptingEngine> e = scripted.scripts();e.hasMoreElements();) list.add(e.nextElement()); for(final Enumeration<Behavior> b=scripted.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B instanceof ScriptingEngine) list.add((ScriptingEngine)B); } for(final ScriptingEngine engine : list) { if((engine!=null) &&(engine.defaultQuestName()!=null) &&(engine.defaultQuestName().length()>0)) { if(engine == this) { if(prevE != null) { final Quest Q=CMLib.quests().fetchQuest(prevE.defaultQuestName()); if(Q != null) returnable=Q.wasWinner(arg1); } break; } prevE=engine; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=Q.wasWinner(arg1); } break; } case 93: // questscripted { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[t+1]; if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { if(E!=null) { for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B instanceof ScriptingEngine) { final ScriptingEngine SE=(ScriptingEngine)B; if((SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } } } } } } else { final Quest Q=getQuest(arg2); returnable=false; if((Q!=null)&&(E!=null)) { for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B instanceof ScriptingEngine) { final ScriptingEngine SE=(ScriptingEngine)B; if((SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } } } } break; } case 94: // questroom { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.getQuestRoomIndex(arg1)>=0); break; } case 114: // questarea { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { int num=1; Environmental E=Q.getQuestRoom(num); returnable = false; final Area parent=CMLib.map().getArea(arg1); if(parent == null) logError(scripted,"QUESTAREA","NoArea",funcParms); else while(E!=null) { final Area A=CMLib.map().areaLocation(E); if((A==parent)||(parent.isChild(A))||(A.isChild(parent))) { returnable=true; break; } num++; E=Q.getQuestRoom(num); } } break; } case 29: // questmob { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { if(E!=null) { if(Q.isObjectInUse(E)) { returnable=true; break; } } else if(Q.getQuestMobIndex(arg1)>=0) { returnable=true; break; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.getQuestMobIndex(arg1)>=0); } break; } case 31: // isquestmobalive { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { MOB M=null; if(CMath.s_int(arg1.trim())>0) M=Q.getQuestMob(CMath.s_int(arg1.trim())); else M=Q.getQuestMob(Q.getQuestMobIndex(arg1)); if(M!=null) { returnable=!M.amDead(); break; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { MOB M=null; if(CMath.s_int(arg1.trim())>0) M=Q.getQuestMob(CMath.s_int(arg1.trim())); else M=Q.getQuestMob(Q.getQuestMobIndex(arg1)); if(M==null) returnable=false; else returnable=!M.amDead(); } } break; } case 111: // itemcount { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); if(arg2.length()==0) { logError(scripted,"ITEMCOUNT","Syntax",funcParms); return returnable; } if(E==null) returnable=false; else { int num=0; if(E instanceof Container) { num++; for(final Item I : ((Container)E).getContents()) num+=I.numberOfItems(); } else if(E instanceof Item) num=((Item)E).numberOfItems(); else if(E instanceof MOB) { for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Room) { for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Area) { for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();) { for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } } else returnable=false; returnable=simpleEval(scripted,""+num,arg3,arg2,"ITEMCOUNT"); } break; } case 32: // nummobsinarea { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; MaskingLibrary.CompiledZMask MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(arg1.equals("*")) num+=R.numInhabitants(); else { for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA"); break; } case 33: // nummobs { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; MaskingLibrary.CompiledZMask MASK=null; if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("=")))) { arg3=arg3.substring(4).trim(); arg3=arg3.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg3); } try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } catch (final NoSuchElementException nse) { } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS"); break; } case 34: // numracesinarea { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; Room R=null; MOB M=null; for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA"); break; } case 35: // numraces { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } } catch (final NoSuchElementException nse) { } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES"); break; } case 30: // questobj { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final PhysicalAgent E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { if(E!=null) { if(Q.isObjectInUse(E)) { returnable=true; break; } } else if(Q.getQuestItemIndex(arg1)>=0) { returnable=true; break; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.getQuestItemIndex(arg1)>=0); } break; } case 85: // islike { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.masking().maskCheck(arg2, E,false); break; } case 86: // strcontains { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); returnable=stringContainsFunctionImpl(arg1,arg2)>=0; break; } case 92: // isodd { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } returnable = isodd; break; } case 16: // hitprcnt { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"HITPRCNT","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); final int val1=(int)Math.round(hitPctD*100.0); returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT"); } break; } case 50: // isseason { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); returnable=false; if(monster.location()!=null) { arg1=arg1.toUpperCase(); for(final TimeClock.Season season : TimeClock.Season.values()) { if(season.toString().startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getTimeObj().getSeasonCode()==season)) { returnable=true; break; } } } break; } case 51: // isweather { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); returnable=false; if(monster.location()!=null) for(int a=0;a<Climate.WEATHER_DESCS.length;a++) { if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a)) { returnable = true; break; } } break; } case 57: // ismoon { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); returnable=false; if(monster.location()!=null) { if(arg1.length()==0) returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location()); else { arg1=arg1.toUpperCase(); for(final TimeClock.MoonPhase phase : TimeClock.MoonPhase.values()) { if(phase.toString().startsWith(arg1) &&(monster.location().getArea().getTimeObj().getMoonPhase(monster.location())==phase)) { returnable=true; break; } } } } break; } case 110: // ishour { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim(); if(monster.location()==null) returnable=false; else if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1))) returnable=true; else returnable=false; break; } case 38: // istime { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim(); if(monster.location()==null) returnable=false; else if(("daytime").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAY)) returnable=true; else if(("dawn").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAWN)) returnable=true; else if(("dusk").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DUSK)) returnable=true; else if(("nighttime").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.NIGHT)) returnable=true; else if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1))) returnable=true; else returnable=false; break; } case 39: // isday { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 103: // ismonth { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getMonth()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 104: // isyear { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getYear()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 105: // isrlhour { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 106: // isrlday { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.DATE) == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 107: // isrlmonth { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.MONTH)+1 == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 108: // isrlyear { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.YEAR) == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 45: // nummobsroom { if(tlen==1) { if(CMParms.numBits(funcParms)>2) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ else tt=parseBits(eval,t,"cr"); /* tt[t+0] */ } int num=0; int startbit=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); if(signH.containsKey(tt[t+1])) { String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); startbit++; if(!name.equalsIgnoreCase("*")) { num=0; MaskingLibrary.CompiledZMask MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { final boolean usePreCompiled = (name.equals(tt[t+0])); name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=usePreCompiled?CMLib.masking().getPreCompiledMask(name): CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { final MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } } else if(!signH.containsKey(tt[t+0])) { logError(scripted,"NUMMOBSROOM","Syntax","No SIGN found: "+funcParms); return returnable; } final String comp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit+1]); if(lastKnownLocation!=null) returnable=simpleEval(scripted,""+num,arg2,comp,"NUMMOBSROOM"); break; } case 63: // numpcsroom { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Room R=lastKnownLocation; if(R!=null) { int num=0; for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if((M!=null)&&(!M.isMonster())) num++; } returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSROOM"); } break; } case 79: // numpcsarea { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); if(lastKnownLocation!=null) { int num=0; for(final Session S : CMLib.sessions().localOnlineIterable()) { if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA"); } break; } case 115: // expertise { // mob ability type > 10 if(tlen==1) tt=parseBits(eval,t,"ccccr"); /* tt[t+0] */ final Physical P=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); final MOB M; if(P instanceof MOB) M=(MOB)P; else { returnable=false; logError(scripted,"EXPLORED","Unknown MOB",tt[t+0]); return returnable; } final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); Ability A=M.fetchAbility(arg2); if(A==null) A=CMClass.getAbility(arg2); if(A==null) { returnable=false; logError(scripted,"EXPLORED","Unknown Ability on MOB '"+M.name()+"'",tt[t+1]); return returnable; } final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim()); if(experFlag == null) { returnable=false; logError(scripted,"EXPLORED","Unknown Exper Flag",tt[t+2]); return returnable; } final int num=CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag); final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final String arg5=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+4]); if(lastKnownLocation!=null) { returnable=simpleEval(scripted,""+num,arg5,arg4,"EXPERTISE"); } break; } case 77: // explored { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) { logError(scripted,"EXPLORED","Unknown Code",whom); return returnable; } Area A=null; if(!where.equalsIgnoreCase("world")) { A=CMLib.map().getArea(where); if(A==null) { final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2 != null) A=CMLib.map().areaLocation(E2); } if(A==null) { logError(scripted,"EXPLORED","Unknown Area",where); return returnable; } } if(lastKnownLocation!=null) { int pct=0; final MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED"); } break; } case 72: // faction { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp); final Faction F=CMLib.factions().getFaction(arg1); if((E==null)||(!(E instanceof MOB))) { logError(scripted,"FACTION","Unknown Code",whom); return returnable; } if(F==null) { logError(scripted,"FACTION","Unknown Faction",arg1); return returnable; } final MOB M=(MOB)E; String value=null; if(!M.hasFaction(F.factionID())) value=""; else { final int myfac=M.fetchFaction(F.factionID()); if(CMath.isNumber(arg2.trim())) value=Integer.toString(myfac); else { final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),myfac); if(FR==null) value=""; else value=FR.name(); } } if(lastKnownLocation!=null) returnable=simpleEval(scripted,value,arg2,cmp,"FACTION"); break; } case 46: // numitemsroom { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); int ct=0; if(lastKnownLocation!=null) { for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } } returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM"); break; } case 47: //mobitem { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); MOB M=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else M=lastKnownLocation.fetchInhabitant(arg1.trim()); } Item which=null; int ct=1; if(M!=null) { for(int i=0;i<M.numItems();i++) { final Item I=M.getItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which = I; break; } ct++; } } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg3) ||CMLib.english().containsString(which.Name(),arg3) ||CMLib.english().containsString(which.displayText(),arg3)); break; } case 49: // hastattoo { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASTATTOO","Syntax",funcParms); break; } else if((E!=null)&&(E instanceof MOB)) returnable=(((MOB)E).findTattoo(arg2)!=null); else returnable=false; break; } case 109: // hastattootime { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=tt[t+2]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASTATTOO","Syntax",funcParms); break; } else if((E!=null)&&(E instanceof MOB)) { final Tattoo T=((MOB)E).findTattoo(arg2); if(T==null) returnable=false; else returnable=simpleEval(scripted,""+T.getTickDown(),arg3,cmp,"ISTATTOOTIME"); } else returnable=false; break; } case 99: // hasacctattoo { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASACCTATTOO","Syntax",funcParms); break; } else if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null)) returnable=((MOB)E).playerStats().getAccount().findTattoo(arg2)!=null; else returnable=false; break; } case 48: // numitemsmob { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); MOB which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); } int ct=0; if(which!=null) { for(int i=0;i<which.numItems();i++) { final Item I=which.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } } returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB"); break; } case 101: // numitemsshop { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); PhysicalAgent which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); if(which == null) which=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(which == null) which=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); } int ct=0; if(which!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next()) { ct++; } } } } returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSSHOP"); break; } case 100: // shopitem { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); } Environmental which=null; int ct=1; if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();) { final Environmental E=i.next(); if(ct==CMath.s_int(arg2.trim())) { which = E; break; } ct++; } } } if(which==null) returnable=false; else { returnable=(CMLib.english().containsString(which.name(),arg3) ||CMLib.english().containsString(which.Name(),arg3) ||CMLib.english().containsString(which.displayText(),arg3)); if(returnable) setShopPrice(shopHere,which,tmp); } } else returnable=false; break; } case 102: // shophas { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); } returnable=false; if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { final Environmental E=shop.getStock(arg2.trim(), null); returnable = (E!=null); if(returnable) setShopPrice(shopHere,E,tmp); } } } break; } case 43: // roommob { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); Environmental which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1.trim()); } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 44: // roomitem { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); Environmental which=null; int ct=1; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg1.trim())) { which = I; break; } ct++; } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 36: // ishere { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((arg1.length()>0)&&(lastKnownLocation!=null)) returnable=((lastKnownLocation.findItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null)); else returnable=false; break; } case 17: // inroom { if(tlen==1) tt=parseSpecial3PartEval(eval,t); String comp="=="; Environmental E=monster; String arg2; if(signH.containsKey(tt[t+1])) { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=tt[t+1]; arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); } else arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); Room R=null; if(arg2.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { final Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM"); } break; } case 90: // inarea { if(tlen==1) tt=parseSpecial3PartEval(eval,t); String comp="=="; Environmental E=monster; String arg3; if(signH.containsKey(tt[t+1])) { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=tt[t+1]; arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); } else arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); Room R=null; if(arg3.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg3,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) { try { final String lnAstr=(lastKnownLocation!=null)?lastKnownLocation.getArea().Name():null; if((lnAstr!=null)&&(lnAstr.equalsIgnoreCase(arg3))) R=lastKnownLocation; if(R==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { final Area A=a.nextElement(); if((A!=null)&&(A.Name().equalsIgnoreCase(arg3))) { if((lnAstr!=null) &&(lnAstr.equals(A.Name()))) R=lastKnownLocation; else if(!A.isProperlyEmpty()) R=A.getRandomProperRoom(); } } } if(R==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { final Area A=a.nextElement(); if((A!=null)&&(CMLib.english().containsString(A.Name(),arg3))) { if((lnAstr!=null) &&(lnAstr.equals(A.Name()))) R=lastKnownLocation; else if(!A.isProperlyEmpty()) R=A.getRandomProperRoom(); } } } } catch (final NoSuchElementException nse) { } } if(R==null) R=getRoom(arg3,lastKnownLocation); if((R!=null) &&(CMath.bset(R.getArea().flags(),Area.FLAG_INSTANCE_PARENT)) &&(lastKnownLocation!=null) &&(lastKnownLocation.getArea()!=R.getArea()) &&(CMath.bset(lastKnownLocation.getArea().flags(),Area.FLAG_INSTANCE_CHILD)) &&(CMLib.map().getModelArea(lastKnownLocation.getArea())==R.getArea())) R=lastKnownLocation; if(E==null) returnable=false; else { final Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg3.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA"); } break; } case 89: // isrecall { if(tlen==1) tt=parseSpecial3PartEval(eval,t); String comp="=="; Environmental E=monster; String arg2; if(signH.containsKey(tt[t+1])) { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=tt[t+1]; arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); } else arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); Room R=null; if(arg2.startsWith("$")) R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { final Room R2=CMLib.map().getStartRoom(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL"); } break; } case 37: // inlocale { if(tlen==1) { if(CMParms.numBits(funcParms)>1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ else { final int numBits=2; String[] parsed=null; if(CMParms.cleanBit(funcParms).equals(funcParms)) parsed=parseBits("'"+funcParms+"'"+CMStrings.repeat(" .",numBits-1),"cr"); else parsed=parseBits(funcParms+CMStrings.repeat(" .",numBits-1),"cr"); tt=insertStringArray(tt,parsed,t); eval[0]=tt; } } String arg2=null; Environmental E=monster; if(tt[t+1].equals(".")) arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); else { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); } if(E==null) returnable=false; else if(arg2.length()==0) returnable=true; else { final Room R=CMLib.map().roomLocation(E); if(R==null) returnable=false; else if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0) returnable=true; else returnable=false; } break; } case 18: // sex { if(tlen==1) tt=parseBits(eval,t,"CcR"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; String arg3=tt[t+2]; if(CMath.isNumber(arg3.trim())) { switch(CMath.s_int(arg3.trim())) { case 0: arg3 = "NEUTER"; break; case 1: arg3 = "MALE"; break; case 2: arg3 = "FEMALE"; break; } } final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"SEX","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase(); if(arg2.equals("==")) returnable=arg3.startsWith(sex); else if(arg2.equals("!=")) returnable=!arg3.startsWith(sex); else { logError(scripted,"SEX","Syntax",funcParms); return returnable; } } break; } case 91: // datetime { if(tlen==1) tt=parseBits(eval,t,"Ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.trim()); if(index<0) logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) { String val=null; switch(index) { case 2: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 3: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 4: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getMonth(); break; case 5: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getYear(); break; default: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay(); break; } returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME"); } break; } case 13: // stat { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"STAT","Syntax",funcParms); break; } if(E==null) returnable=false; else { final String val=getStatValue(E,arg2); if(val==null) { logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"STAT"); } break; } case 52: // gstat { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"GSTAT","Syntax",funcParms); break; } if(E==null) returnable=false; else { final String val=getGStatValue(E,arg2); if(val==null) { logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT"); } break; } case 19: // position { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"POSITION","Syntax",funcParms); return returnable; } if(P==null) returnable=false; else { String sex="STANDING"; if(CMLib.flags().isSleeping(P)) sex="SLEEPING"; else if(CMLib.flags().isSitting(P)) sex="SITTING"; if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"POSITION","Syntax",funcParms); return returnable; } } break; } case 20: // level { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"LEVEL","Syntax",funcParms); return returnable; } if(P==null) returnable=false; else { final int val1=P.phyStats().level(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL"); } break; } case 80: // questpoints { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"QUESTPOINTS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getQuestPoint(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS"); } break; } case 83: // qvar { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Quest Q=getQuest(arg1); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"QVAR","Syntax",funcParms); return returnable; } if(Q==null) returnable=false; else returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR"); break; } case 84: // math { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); if(!CMath.isMathExpression(arg1)) { logError(scripted,"MATH","Syntax",funcParms); return returnable; } if(!CMath.isMathExpression(arg3)) { logError(scripted,"MATH","Syntax",funcParms); return returnable; } returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH"); break; } case 81: // trains { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"TRAINS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getTrains(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS"); } break; } case 82: // pracs { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"PRACS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getPractices(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS"); } break; } case 66: // clanrank { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLANRANK","Syntax",funcParms); return returnable; } if(!(E instanceof MOB)) returnable=false; else { int val1=-1; Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) val1=((MOB)E).getClanRole(C.clanID()).second.intValue(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK"); } break; } case 64: // deity { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"DEITY","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).getWorshipCharID(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { logError(scripted,"DEITY","Syntax",funcParms); return returnable; } } break; } case 68: // clandata { if(tlen==1) tt=parseBits(eval,t,"cccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLANDATA","Syntax",funcParms); return returnable; } String clanID=null; if((E!=null)&&(E instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); } else { clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); if((scripted instanceof MOB) &&(CMLib.clans().getClanAnyHost(clanID)==null)) { final List<Pair<Clan,Integer>> Cs=CMLib.clans().getClansByCategory((MOB)scripted, clanID); if((Cs!=null)&&(Cs.size()>0)) clanID=Cs.get(0).first.clanID(); } } final Clan C=CMLib.clans().findClan(clanID); if(C!=null) { if(!C.isStat(arg2)) logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); else { final String whichVal=C.getStat(arg2).trim(); if(CMath.isNumber(whichVal)&&CMath.isNumber(arg4.trim())) returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA"); else returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA"); } } break; } case 98: // clanqualifies { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"CLANQUALIFIES","Syntax",funcParms); return returnable; } final Clan C=CMLib.clans().findClan(arg2); if((C!=null)&&(E instanceof MOB)) { final MOB mob=(MOB)E; if(C.isOnlyFamilyApplicants() &&(!CMLib.clans().isFamilyOfMembership(mob,C.getMemberList()))) returnable=false; else if(CMLib.clans().getClansByCategory(mob, C.getCategory()).size()>CMProps.getMaxClansThisCategory(C.getCategory())) returnable=false; if(returnable && (!CMLib.masking().maskCheck(C.getBasicRequirementMask(), mob, true))) returnable=false; else if(returnable && (CMLib.masking().maskCheck(C.getAcceptanceSettings(),mob,true))) returnable=false; } else { logError(scripted,"CLANQUALIFIES","Unknown clan "+arg2+" or "+arg1+" is not a mob",funcParms); return returnable; } break; } case 65: // clan { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"CLAN","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String clanID=""; Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); if(arg2.equals("==")) returnable=clanID.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!clanID.equalsIgnoreCase(arg3); else if(arg2.equals("in")) returnable=((MOB)E).getClanRole(arg3)!=null; else if(arg2.equals("notin")) returnable=((MOB)E).getClanRole(arg3)==null; else { logError(scripted,"CLAN","Syntax",funcParms); return returnable; } } break; } case 88: // mood { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"MOOD","Syntax",funcParms); return returnable; } if((P==null)||(!(P instanceof MOB))) returnable=false; else { final Ability moodA=P.fetchEffect("Mood"); if(moodA!=null) { final String sex=moodA.text(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { logError(scripted,"MOOD","Syntax",funcParms); return returnable; } } } break; } case 21: // class { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().displayClassName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } } break; } case 22: // baseclass { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } } break; } case 23: // race { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"RACE","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().raceName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"RACE","Syntax",funcParms); return returnable; } } break; } case 24: //racecat { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"RACECAT","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"RACECAT","Syntax",funcParms); return returnable; } } break; } case 25: // goldamt { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"GOLDAMT","Syntax",funcParms); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"GOLDAMT","Syntax",funcParms); return returnable; } returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT"); } break; } case 78: // exp { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"EXP","Syntax",funcParms); break; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getExperience(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP"); } break; } case 76: // value { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0)) { logError(scripted,"VALUE","Syntax",funcParms); break; } if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase())); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"VALUE","Syntax",funcParms); return returnable; } returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT"); } break; } case 26: // objtype { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"OBJTYPE","Syntax",funcParms); return returnable; } if(E==null) returnable=false; else { final String sex=CMClass.classID(E).toUpperCase(); if(arg2.equals("==")) returnable=sex.indexOf(arg3)>=0; else if(arg2.equals("!=")) returnable=sex.indexOf(arg3)<0; else { logError(scripted,"OBJTYPE","Syntax",funcParms); return returnable; } } break; } case 27: // var { if(tlen==1) tt=parseBits(eval,t,"cCcr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"VAR","Syntax",funcParms); return returnable; } final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut("(VAR "+arg1+" "+arg2 +"["+val+"] "+arg3+" "+arg4); if(arg3.equals("==")||arg3.equals("=")) returnable=val.equals(arg4); else if(arg3.equals("!=")||(arg3.contentEquals("<>"))) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { logError(scripted,"VAR","Syntax",funcParms); return returnable; } break; } case 41: // eval { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg3=tt[t+1]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); if(arg3.length()==0) { logError(scripted,"EVAL","Syntax",funcParms); return returnable; } if(arg3.equals("==")) returnable=val.equals(arg4); else if(arg3.equals("!=")) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { logError(scripted,"EVAL","Syntax",funcParms); return returnable; } break; } case 40: // number { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) { if(!Character.isDigit(val.charAt(i))) { isnumber = false; break; } } returnable=isnumber; break; } case 42: // randnum { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s.trim())) arg1=CMath.s_parseIntExpression(arg1s.trim()); else arg1=CMParms.parse(arg1s.trim()).size(); final String arg2=tt[t+1]; final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim(); int arg3=0; if(CMath.isMathExpression(arg3s.trim())) arg3=CMath.s_parseIntExpression(arg3s.trim()); else arg3=CMParms.parse(arg3s.trim()).size(); arg1=CMLib.dice().roll(1,arg1,0); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM"); break; } case 71: // rand0num { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s)) arg1=CMath.s_parseIntExpression(arg1s); else arg1=CMParms.parse(arg1s).size(); final String arg2=tt[t+1]; final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim(); int arg3=0; if(CMath.isMathExpression(arg3s)) arg3=CMath.s_parseIntExpression(arg3s); else arg3=CMParms.parse(arg3s).size(); arg1=CMLib.dice().roll(1,arg1,-1); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM"); break; } case 53: // incontainer { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[t+1]; final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else if(E instanceof MOB) { if(arg2.length()==0) returnable=(((MOB)E).riding()==null); else if(E2!=null) returnable=(((MOB)E).riding()==E2); else returnable=false; } else if(E instanceof Item) { if(arg2.length()==0) returnable=(((Item)E).container()==null); else if(E2!=null) returnable=(((Item)E).container()==E2); else returnable=false; } else returnable=false; break; } case 96: // iscontents { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]); if(E==null) returnable=false; else if(E instanceof Rideable) { if(arg2.length()==0) returnable=((Rideable)E).numRiders()==0; else returnable=CMLib.english().fetchEnvironmental(new XVector<Rider>(((Rideable)E).riders()), arg2, false)!=null; } if(E instanceof Container) { if(arg2.length()==0) returnable=!((Container)E).hasContent(); else returnable=CMLib.english().fetchEnvironmental(((Container)E).getDeepContents(), arg2, false)!=null; } else returnable=false; break; } case 97: // wornon { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]); final String arg3=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+2]); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"WORNON","Syntax",funcParms); return returnable; } final int wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim()); returnable=false; if(wornLoc<0) logError(scripted,"EVAL","BAD WORNON LOCATION",arg2); else if(E instanceof MOB) { final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0); if((items.size()==0)&&(arg3.length()==0)) returnable=true; else returnable = CMLib.english().fetchEnvironmental(items, arg3, false)!=null; } break; } default: logError(scripted,"EVAL","UNKNOWN",CMParms.toListString(tt)); return false; } pushEvalBoolean(stack,returnable); while((t<tt.length)&&(!tt[t].equals(")"))) t++; } else { logError(scripted,"EVAL","SYNTAX","BAD CONJUCTOR "+tt[t]+": "+CMParms.toListString(tt)); return false; } } if((stack.size()!=1) ||(!(stack.get(0) instanceof Boolean))) { logError(scripted,"EVAL","SYNTAX","Unmatched (: "+CMParms.toListString(tt)); return false; } return ((Boolean)stack.get(0)).booleanValue(); } protected void setShopPrice(final ShopKeeper shopHere, final Environmental E, final Object[] tmp) { if(shopHere instanceof MOB) { final ShopKeeper.ShopPrice price = CMLib.coffeeShops().sellingPrice((MOB)shopHere, null, E, shopHere, shopHere.getShop(), true); if(price.experiencePrice>0) tmp[SPECIAL_9SHOPHASPRICE] = price.experiencePrice+"xp"; else if(price.questPointPrice>0) tmp[SPECIAL_9SHOPHASPRICE] = price.questPointPrice+"qp"; else tmp[SPECIAL_9SHOPHASPRICE] = CMLib.beanCounter().abbreviatedPrice((MOB)shopHere,price.absoluteGoldPrice); } } @Override public String functify(final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp, final String evaluable) { if(evaluable.length()==0) return ""; final StringBuffer results = new StringBuffer(""); final int y=evaluable.indexOf('('); final int z=evaluable.indexOf(')',y); final String preFab=(y>=0)?evaluable.substring(0,y).toUpperCase().trim():""; Integer funcCode=funcH.get(preFab); if(funcCode==null) funcCode=Integer.valueOf(0); if((y<0)||(z<y)) { logError(scripted,"()","Syntax",evaluable); return ""; } else { tickStatus=Tickable.STATUS_MISC2+funcCode.intValue(); final String funcParms=evaluable.substring(y+1,z).trim(); switch(funcCode.intValue()) { case 1: // rand { results.append(CMLib.dice().rollPercentage()); break; } case 2: // has { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); ArrayList<Item> choices=new ArrayList<Item>(); if(E==null) choices=new ArrayList<Item>(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).numItems();i++) { final Item I=((MOB)E).getItem(i); if((I!=null)&&(I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null)) choices.add(I); } } else if(E instanceof Item) { if(E instanceof Container) choices.addAll(((Container)E).getDeepContents()); else choices.add((Item)E); } else if(E instanceof Room) { for(int i=0;i<((Room)E).numItems();i++) { final Item I=((Room)E).getItem(i); if((I!=null)&&(I.container()==null)) choices.add(I); } } if(choices.size()>0) results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name()); break; } case 74: // hasnum { final String arg1=CMParms.getCleanBit(funcParms,0); final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1)); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((item.length()==0)||(E==null)) logError(scripted,"HASNUM","Syntax",funcParms); else { Item I=null; int num=0; if(E instanceof MOB) { final MOB M=(MOB)E; for(int i=0;i<M.numItems();i++) { I=M.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; results.append(""+num); } else if(E instanceof Room) { final Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } } break; } case 3: // worn { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); ArrayList<Item> choices=new ArrayList<Item>(); if(E==null) choices=new ArrayList<Item>(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).numItems();i++) { final Item I=((MOB)E).getItem(i); if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null)) choices.add(I); } } else if((E instanceof Item)&&(!(((Item)E).amWearingAt(Wearable.IN_INVENTORY)))) { if(E instanceof Container) choices.addAll(((Container)E).getDeepContents()); else choices.add((Item)E); } if(choices.size()>0) results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name()); break; } case 4: // isnpc case 5: // ispc results.append("[unimplemented function]"); break; case 87: // isbirthday { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null)) { final MOB mob=(MOB)E; final TimeClock C=CMLib.time().localClock(mob.getStartRoom()); final int day=C.getDayOfMonth(); final int month=C.getMonth(); int year=C.getYear(); final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY]; final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH]; if((month>bmonth)||((month==bmonth)&&(day>bday))) year++; final StringBuffer timeDesc=new StringBuffer(""); if(C.getDaysInWeek()>0) { long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth(); x=x+((long)(bmonth-1))*((long)C.getDaysInMonth()); x=x+bmonth; timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", "); } timeDesc.append("the "+bday+CMath.numAppendage(bday)); timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]); if(C.getYearNames().length>0) timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year)); results.append(timeDesc.toString()); } break; } case 6: // isgood { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) { final Faction.FRange FR=CMLib.factions().getRange(CMLib.factions().getAlignmentID(),((MOB)E).fetchFaction(CMLib.factions().getAlignmentID())); if(FR!=null) results.append(FR.name()); else results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID())); } break; } case 8: // isevil { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(CMLib.flags().getAlignmentName(E).toLowerCase()); break; } case 9: // isneutral { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID())); break; } case 11: // isimmort results.append("[unimplemented function]"); break; case 54: // isalive { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) results.append(((MOB)E).healthText(null)); else if(E!=null) results.append(E.name()+" is dead."); break; } case 58: // isable { final String arg1=CMParms.getCleanBit(funcParms,0); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) { final Pair<String,Integer> s=((MOB)E).fetchExpertise(X.ID()); if(s!=null) results.append(s.getKey()+((s.getValue()!=null)?s.getValue().toString():"")); } else { final Ability A=((MOB)E).findAbility(arg2); if(A!=null) results.append(""+A.proficiency()); } } break; } case 59: // isopen { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); boolean returnable=false; if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } results.append(""+returnable); break; } case 60: // islocked { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) results.append(((Container)E).keyName()); else if((E!=null)&&(E instanceof Exit)) results.append(((Exit)E).keyName()); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) results.append(E.keyName()); } break; } case 62: // callfunc { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); String found=null; boolean validFunc=false; final List<DVector> scripts=getScripts(); String trigger=null; String[] ttrigger=null; for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); ttrigger=(String[])script2.elementAt(0,2); if(getTriggerCode(trigger,ttrigger)==17) { final String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) logError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else results.append(found); break; } case 61: // strin { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); final List<String> V=CMParms.parse(arg1.toUpperCase()); results.append(V.indexOf(arg2.toUpperCase())); break; } case 55: // ispkill { final String arg1=CMParms.cleanBit(funcParms); final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) results.append("false"); else if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL)) results.append("true"); else results.append("false"); break; } case 10: // isfight { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat())) results.append(((MOB)E).getVictim().name()); break; } case 12: // ischarmed { final String arg1=CMParms.cleanBit(funcParms); final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final List<Ability> V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING); for(int v=0;v<V.size();v++) results.append((V.get(v).name())+" "); } break; } case 15: // isfollow { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null) &&(((MOB)E).amFollowing().location()==lastKnownLocation)) results.append(((MOB)E).amFollowing().name()); break; } case 73: // isservant { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0)) results.append(((MOB)E).getLiegeID()); break; } case 95: // isspeaking { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final MOB TM=(MOB)E; final Language L=CMLib.utensils().getLanguageSpoken(TM); if(L!=null) results.append(L.Name()); else results.append("Common"); } break; } case 56: // name case 7: // isname { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(E.name()); break; } case 75: // currency { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(CMLib.beanCounter().getCurrency(E)); break; } case 14: // affected { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E instanceof Physical)&&(((Physical)E).numEffects()>0)) results.append(((Physical)E).effects().nextElement().name()); break; } case 69: // isbehave { final String arg1=CMParms.cleanBit(funcParms); final PhysicalAgent E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if(B!=null) results.append(B.ID()+" "); } } break; } case 70: // ipaddress { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) results.append(((MOB)E).session().getAddress()); break; } case 28: // questwinner { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) { for(int q=0;q<CMLib.quests().numQuests();q++) { final Quest Q=CMLib.quests().fetchQuest(q); if((Q!=null)&&(Q.wasWinner(E.Name()))) results.append(Q.name()+" "); } } break; } case 93: // questscripted { final String arg1=CMParms.cleanBit(funcParms); final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) { for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null)&&(SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0)) { final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName()); if(Q!=null) results.append(Q.name()+" "); else results.append(SE.defaultQuestName()+" "); } } for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if(B instanceof ScriptingEngine) { final ScriptingEngine SE=(ScriptingEngine)B; if((SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0)) { final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName()); if(Q!=null) results.append(Q.name()+" "); else results.append(SE.defaultQuestName()+" "); } } } } break; } case 30: // questobj { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0)) questName = this.defaultQuestName(); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestItem(num); while(E!=null) { if(E.Name().indexOf(' ')>=0) list.append("\""+E.Name()+"\" "); else list.append(E.Name()+" "); num++; E=Q.getQuestItem(num); } results.append(list.toString().trim()); break; } case 94: // questroom { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestRoom(num); while(E!=null) { final String roomID=CMLib.map().getExtendedRoomID((Room)E); if(roomID.indexOf(' ')>=0) list.append("\""+roomID+"\" "); else list.append(roomID+" "); num++; E=Q.getQuestRoom(num); } results.append(list.toString().trim()); break; } case 114: // questarea { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestRoom(num); while(E!=null) { final String areaName=CMLib.map().areaLocation(E).name(); if(list.indexOf(areaName)<0) { if(areaName.indexOf(' ')>=0) list.append("\""+areaName+"\" "); else list.append(areaName+" "); } num++; E=Q.getQuestRoom(num); } results.append(list.toString().trim()); break; } case 29: // questmob { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0)) questName=this.defaultQuestName(); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestMob(num); while(E!=null) { if(E.Name().indexOf(' ')>=0) list.append("\""+E.Name()+"\" "); else list.append(E.Name()+" "); num++; E=Q.getQuestMob(num); } results.append(list.toString().trim()); break; } case 31: // isquestmobalive { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; MOB E=Q.getQuestMob(num); while(E!=null) { if(CMLib.flags().isInTheGame(E,true)) { if(E.Name().indexOf(' ')>=0) list.append("\""+E.Name()+"\" "); else list.append(E.Name()+" "); } num++; E=Q.getQuestMob(num); } results.append(list.toString().trim()); break; } case 49: // hastattoo { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { for(final Enumeration<Tattoo> t = ((MOB)E).tattoos();t.hasMoreElements();) results.append(t.nextElement().ID()).append(" "); } break; } case 109: // hastattootime { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final Tattoo T=((MOB)E).findTattoo(arg2); if(T!=null) results.append(T.getTickDown()); } break; } case 99: // hasacctattoo { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null)) { for(final Enumeration<Tattoo> t = ((MOB)E).playerStats().getAccount().tattoos();t.hasMoreElements();) results.append(t.nextElement().ID()).append(" "); } break; } case 32: // nummobsinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); int num=0; MaskingLibrary.CompiledZMask MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(arg1.equals("*")) num+=R.numInhabitants(); else { for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } results.append(num); break; } case 33: // nummobs { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); MaskingLibrary.CompiledZMask MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } catch(final NoSuchElementException nse) { } results.append(num); break; } case 34: // numracesinarea { int num=0; final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Room R=null; MOB M=null; for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } results.append(num); break; } case 35: // numraces { int num=0; final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Room R=null; MOB M=null; try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } } catch (final NoSuchElementException nse) { } results.append(num); break; } case 112: // cansee { break; } case 113: // canhear { break; } case 111: // itemcount { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { int num=0; if(E instanceof Container) { num++; for(final Item I : ((Container)E).getContents()) num+=I.numberOfItems(); } else if(E instanceof Item) num=((Item)E).numberOfItems(); else if(E instanceof MOB) { for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Room) { for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Area) { for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();) { for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } } results.append(""+num); } break; } case 16: // hitprcnt { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); final int val1=(int)Math.round(hitPctD*100.0); results.append(val1); } break; } case 50: // isseason { if(monster.location()!=null) results.append(monster.location().getArea().getTimeObj().getSeasonCode().toString()); break; } case 51: // isweather { if(monster.location()!=null) results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]); break; } case 57: // ismoon { if(monster.location()!=null) results.append(monster.location().getArea().getTimeObj().getMoonPhase(monster.location()).toString()); break; } case 38: // istime { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getTODCode().getDesc().toLowerCase()); break; } case 110: // ishour { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getHourOfDay()); break; } case 103: // ismonth { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getMonth()); break; } case 104: // isyear { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getYear()); break; } case 105: // isrlhour { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); break; } case 106: // isrlday { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.DATE)); break; } case 107: // isrlmonth { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.MONTH)); break; } case 108: // isrlyear { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.YEAR)); break; } case 39: // isday { if(lastKnownLocation!=null) results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth()); break; } case 43: // roommob { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Environmental which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1.trim()); if(which!=null) { final List<MOB> list=new ArrayList<MOB>(); for(int i=0;i<lastKnownLocation.numInhabitants();i++) { final MOB M=lastKnownLocation.fetchInhabitant(i); if(M!=null) list.add(M); } results.append(CMLib.english().getContextName(list,which)); } } break; } case 44: // roomitem { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Environmental which=null; int ct=1; if(lastKnownLocation!=null) { final List<Item> list=new ArrayList<Item>(); for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) { list.add(I); if(ct==CMath.s_int(arg1.trim())) { which = I; break; } ct++; } } if(which!=null) results.append(CMLib.english().getContextName(list,which)); } break; } case 45: // nummobsroom { int num=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((name.length()>0)&&(!name.equalsIgnoreCase("*"))) { num=0; MaskingLibrary.CompiledZMask MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { final MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } results.append(""+num); break; } case 63: // numpcsroom { final Room R=lastKnownLocation; if(R!=null) { int num=0; for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if((M!=null)&&(!M.isMonster())) num++; } results.append(""+num); } break; } case 115: // expertise { // mob ability type > 10 final String arg1=CMParms.getCleanBit(funcParms,0); final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final MOB M; if(P instanceof MOB) { M=(MOB)P; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1)); Ability A=M.fetchAbility(arg2); if(A==null) A=CMClass.getAbility(arg2); if(A!=null) { final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,1)); final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim()); if(experFlag != null) results.append(""+CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag)); } } break; } case 79: // numpcsarea { if(lastKnownLocation!=null) { int num=0; for(final Session S : CMLib.sessions().localOnlineIterable()) { if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } results.append(""+num); } break; } case 77: // explored { final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1)); final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { Area A=null; if(!where.equalsIgnoreCase("world")) { A=CMLib.map().getArea(where); if(A==null) { final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2!=null) A=CMLib.map().areaLocation(E2); } } if((lastKnownLocation!=null) &&((A!=null)||(where.equalsIgnoreCase("world")))) { int pct=0; final MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); results.append(""+pct); } } break; } case 72: // faction { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBit(funcParms,0); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final Faction F=CMLib.factions().getFaction(arg2); if(F==null) logError(scripted,"FACTION","Unknown Faction",arg1); else if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID()))) { final int value=((MOB)E).fetchFaction(F.factionID()); final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),value); if(FR!=null) results.append(FR.name()); } break; } case 46: // numitemsroom { int ct=0; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } results.append(""+ct); break; } case 47: //mobitem { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); MOB M=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else M=lastKnownLocation.fetchInhabitant(arg1.trim()); } Item which=null; int ct=1; if(M!=null) { for(int i=0;i<M.numItems();i++) { final Item I=M.getItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which = I; break; } ct++; } } } if(which!=null) results.append(which.name()); break; } case 100: // shopitem { final String arg1raw=CMParms.getCleanBit(funcParms,0); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp); } Environmental which=null; int ct=1; if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++) { final Environmental E=i.next(); if(ct==CMath.s_int(arg2.trim())) { which = E; setShopPrice(shopHere,E,tmp); break; } } } } } if(which!=null) results.append(which.name()); break; } case 101: // numitemsshop { final String arg1raw = CMParms.cleanBit(funcParms); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw); PhysicalAgent which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); if(which == null) which=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(which == null) which=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp); } int ct=0; if(which!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next()) { ct++; } } } } results.append(""+ct); break; } case 102: // shophas { final String arg1raw=CMParms.cleanBit(funcParms); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp); } if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { int ct=0; for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next()) ct++; final int which=CMLib.dice().roll(1, ct, -1); ct=0; for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++) { final Environmental E=i.next(); if(which == ct) { results.append(E.Name()); setShopPrice(shopHere,E,tmp); break; } } } } } break; } case 48: // numitemsmob { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); MOB which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); } int ct=0; if(which!=null) { for(int i=0;i<which.numItems();i++) { final Item I=which.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } } results.append(""+ct); break; } case 36: // ishere { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().name()); break; } case 17: // inroom { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(CMLib.map().getExtendedRoomID(lastKnownLocation)); else results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E))); break; } case 90: // inarea { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name()); else { final Room R=CMLib.map().roomLocation(E); results.append(R==null?"Nowhere":R.getArea().Name()); } break; } case 89: // isrecall { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E))); break; } case 37: // inlocale { final String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(parms.trim().length()==0) { if(lastKnownLocation!=null) results.append(lastKnownLocation.name()); } else { final Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final Room R=CMLib.map().roomLocation(E); if(R!=null) results.append(R.name()); } } break; } case 18: // sex { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().genderName()); break; } case 91: // datetime { final String arg1=CMParms.getCleanBit(funcParms,0); final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim()); if(index<0) logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) { switch(index) { case 2: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 3: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 4: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth()); break; case 5: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear()); break; default: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay()); break; } } break; } case 13: // stat { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final String val=getStatValue(E,arg2); if(val==null) { logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 52: // gstat { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final String val=getGStatValue(E,arg2); if(val==null) { logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 19: // position { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P!=null) { final String sex; if(CMLib.flags().isSleeping(P)) sex="SLEEPING"; else if(CMLib.flags().isSitting(P)) sex="SITTING"; else sex="STANDING"; results.append(sex); break; } break; } case 20: // level { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P!=null) results.append(P.phyStats().level()); break; } case 80: // questpoints { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getQuestPoint()); break; } case 83: // qvar { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); if((arg1.length()!=0)&&(arg2.length()!=0)) { final Quest Q=getQuest(arg1); if(Q!=null) results.append(Q.getStat(arg2)); } break; } case 84: // math { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); results.append(""+Math.round(CMath.s_parseMathExpression(arg1))); break; } case 85: // islike { final String arg1=CMParms.cleanBit(funcParms); results.append(CMLib.masking().maskDesc(arg1)); break; } case 86: // strcontains { results.append("[unimplemented function]"); break; } case 81: // trains { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getTrains()); break; } case 92: // isodd { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(funcParms)).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } if( isodd ) { results.append( CMath.s_long( val.trim() ) ); } break; } case 82: // pracs { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getPractices()); break; } case 68: // clandata { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((E!=null)&&(E instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); } else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); final Clan C=CMLib.clans().findClan(clanID); if(C!=null) { if(!C.isStat(arg2)) logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); else results.append(C.getStat(arg2)); } break; } case 98: // clanqualifies { final String arg1=CMParms.cleanBit(funcParms); Clan C=CMLib.clans().getClan(arg1); if(C==null) C=CMLib.clans().findClan(arg1); if(C!=null) { if(C.getAcceptanceSettings().length()>0) results.append(CMLib.masking().maskDesc(C.getAcceptanceSettings())); if(C.getBasicRequirementMask().length()>0) results.append(CMLib.masking().maskDesc(C.getBasicRequirementMask())); if(C.isOnlyFamilyApplicants()) results.append("Must belong to the family."); final int total=CMProps.getMaxClansThisCategory(C.getCategory()); if(C.getCategory().length()>0) results.append("May belong to only "+total+" "+C.getCategory()+" clan. "); else results.append("May belong to only "+total+" standard clan. "); } break; } case 67: // hastitle { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)) { final MOB M=(MOB)E; results.append(M.playerStats().getActiveTitle()); } break; } case 66: // clanrank { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); Clan C=null; if(E instanceof MOB) { C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; } else C=CMLib.clans().findClan(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1)); if(C!=null) { final Pair<Clan,Integer> p=((MOB)E).getClanRole(C.clanID()); if(p!=null) results.append(p.second.toString()); } break; } case 21: // class { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().displayClassName()); break; } case 64: // deity { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final String sex=((MOB)E).getWorshipCharID(); results.append(sex); } break; } case 65: // clan { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) results.append(C.clanID()); } break; } case 88: // mood { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { final Ability moodA=((MOB)E).fetchEffect("Mood"); if(moodA!=null) results.append(CMStrings.capitalizeAndLower(moodA.text())); } break; } case 22: // baseclass { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getCurrentClass().baseClass()); break; } case 23: // race { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().raceName()); break; } case 24: //racecat { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getMyRace().racialCategory()); break; } case 25: // goldamt { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"GOLDAMT","Syntax",funcParms); return results.toString(); } results.append(val1); } break; } case 78: // exp { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=((MOB)E).getExperience(); results.append(val1); } break; } case 76: // value { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); return results.toString(); } final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2)); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"GOLDAMT","Syntax",funcParms); return results.toString(); } results.append(val1); } break; } case 26: // objtype { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final String sex=CMClass.classID(E).toLowerCase(); results.append(sex); } break; } case 53: // incontainer { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(((MOB)E).riding()!=null) results.append(((MOB)E).riding().Name()); } else if(E instanceof Item) { if(((Item)E).riding()!=null) results.append(((Item)E).riding().Name()); else if(((Item)E).container()!=null) results.append(((Item)E).container().Name()); else if(E instanceof Container) { final List<Item> V=((Container)E).getDeepContents(); for(int v=0;v<V.size();v++) results.append("\""+V.get(v).Name()+"\" "); } } } break; } case 27: // var { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase(); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); results.append(val); break; } case 41: // eval results.append("[unimplemented function]"); break; case 40: // number { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) { if(!Character.isDigit(val.charAt(i))) { isnumber = false; break; } } if(isnumber) results.append(CMath.s_long(val.trim())); break; } case 42: // randnum { final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,0)); break; } case 71: // rand0num { final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,-1)); break; } case 96: // iscontents { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof Rideable) { for(final Enumeration<Rider> r=((Rideable)E).riders();r.hasMoreElements();) results.append(CMParms.quoteIfNecessary(r.nextElement().name())).append(" "); } if(E instanceof Container) { for (final Item item : ((Container)E).getDeepContents()) results.append(CMParms.quoteIfNecessary(item.name())).append(" "); } break; } case 97: // wornon { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase(); final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); int wornLoc=-1; if(arg2.length()>0) wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim()); if(wornLoc<0) logError(scripted,"EVAL","BAD WORNON LOCATION",arg2); else if(E instanceof MOB) { final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0); for(final Item item : items) results.append(CMParms.quoteIfNecessary(item.name())).append(" "); } break; } default: logError(scripted,"Unknown Val",preFab,evaluable); return results.toString(); } } return results.toString(); } protected MOB getRandPC(final MOB monster, final Object[] tmp, final Room room) { if((tmp[SPECIAL_RANDPC]==null)||(tmp[SPECIAL_RANDPC]==monster)) { MOB M=null; if(room!=null) { final List<MOB> choices = new ArrayList<MOB>(); for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if((!M.isMonster())&&(M!=monster)) { final HashSet<MOB> seen=new HashSet<MOB>(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } choices.add(M); } } if(choices.size() > 0) tmp[SPECIAL_RANDPC] = choices.get(CMLib.dice().roll(1,choices.size(),-1)); } } return (MOB)tmp[SPECIAL_RANDPC]; } protected MOB getRandAnyone(final MOB monster, final Object[] tmp, final Room room) { if((tmp[SPECIAL_RANDANYONE]==null)||(tmp[SPECIAL_RANDANYONE]==monster)) { MOB M=null; if(room!=null) { final List<MOB> choices = new ArrayList<MOB>(); for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if(M!=monster) { final HashSet<MOB> seen=new HashSet<MOB>(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } choices.add(M); } } if(choices.size() > 0) tmp[SPECIAL_RANDANYONE] = choices.get(CMLib.dice().roll(1,choices.size(),-1)); } } return (MOB)tmp[SPECIAL_RANDANYONE]; } @Override public String execute(final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final DVector script, final String msg, final Object[] tmp) { return execute(scripted,source,target,monster,primaryItem,secondaryItem,script,msg,tmp,1); } public String execute(PhysicalAgent scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, final DVector script, String msg, final Object[] tmp, final int startLine) { tickStatus=Tickable.STATUS_START; String s=null; String[] tt=null; String cmd=null; final boolean traceDebugging=CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTTRACE); if(traceDebugging && startLine == 1 && script.size()>0 && script.get(0, 1).toString().trim().length()>0) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": * EXECUTE: "+script.get(0, 1).toString()); for(int si=startLine;si<script.size();si++) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.length()==0) continue; if(traceDebugging) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": "+s); Integer methCode=methH.get(cmd); if((methCode==null)&&(cmd.startsWith("MP"))) { for(int i=0;i<methods.length;i++) { if(methods[i].startsWith(cmd)) methCode=Integer.valueOf(i); } } if(methCode==null) methCode=Integer.valueOf(0); tickStatus=Tickable.STATUS_MISC3+methCode.intValue(); switch(methCode.intValue()) { case 57: // <SCRIPT> { if(tt==null) tt=parseBits(script,si,"C"); final StringBuffer jscript=new StringBuffer(""); while((++si)<script.size()) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); break; } jscript.append(s+"\n"); } if(CMSecurity.isApprovedJScript(jscript)) { final Context cx = Context.enter(); try { final JScriptEvent scope = new JScriptEvent(this,scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp); cx.initStandardObjects(scope); final String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString", "getCMType"}; scope.defineFunctionProperties(names, JScriptEvent.class, ScriptableObject.DONTENUM); cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null); } catch(final Exception e) { Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage()); } Context.exit(); } else if(CMProps.getIntVar(CMProps.Int.JSCRIPTS)==CMSecurity.JSCRIPT_REQ_APPROVAL) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,L("A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script.")); } break; } case 19: // if { if(tt==null) { try { final String[] ttParms=parseEval(s.substring(2)); tt=new String[ttParms.length+1]; tt[0]="IF"; for(int i=0;i<ttParms.length;i++) tt[i+1]=ttParms[i]; script.setElementAt(si,2,tt); script.setElementAt(si, 3, new Triad<DVector,DVector,Integer>(null,null,null)); } catch(final Exception e) { logError(scripted,"IF","Syntax",e.getMessage()); tickStatus=Tickable.STATUS_END; return null; } } final String[][] EVAL={tt}; final boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVAL,1); if(EVAL[0]!=tt) { tt=EVAL[0]; script.setElementAt(si,2,tt); } boolean foundendif=false; @SuppressWarnings({ "unchecked", "rawtypes" }) Triad<DVector,DVector,Integer> parsedBlocks = (Triad)script.elementAt(si, 3); DVector subScript; if(parsedBlocks==null) { Log.errOut("Null parsed blocks in "+s); parsedBlocks = new Triad<DVector,DVector,Integer>(null,null,null); script.setElementAt(si, 3, parsedBlocks); subScript=null; } else if(parsedBlocks.third != null) { if(condition) subScript=parsedBlocks.first; else subScript=parsedBlocks.second; si=parsedBlocks.third.intValue(); si--; // because we want to be pointing at the ENDIF with si++ happens below. foundendif=true; } else subScript=null; int depth=0; boolean ignoreUntilEndScript=false; si++; boolean positiveCondition=true; while((si<script.size()) &&(!foundendif)) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=true; } else if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=false; } else if(ignoreUntilEndScript) { } else if(cmd.equals("ENDIF")&&(depth==0)) { if(tt==null) tt=parseBits(script,si,"C"); parsedBlocks.third=Integer.valueOf(si); foundendif=true; break; } else if(cmd.equals("ELSE")&&(depth==0)) { positiveCondition=false; if(s.substring(4).trim().length()>0) logError(scripted,"ELSE","Syntax"," Decorated ELSE is now illegal!!"); else if(tt==null) tt=parseBits(script,si,"C"); } else { if(cmd.equals("IF")) depth++; else if(cmd.equals("ENDIF")) { if(tt==null) tt=parseBits(script,si,"C"); depth--; } if(positiveCondition) { if(parsedBlocks.first==null) { parsedBlocks.first=new DVector(3); parsedBlocks.first.addElement("",null,null); } if(condition) subScript=parsedBlocks.first; parsedBlocks.first.addSharedElements(script.elementsAt(si)); } else { if(parsedBlocks.second==null) { parsedBlocks.second=new DVector(3); parsedBlocks.second.addElement("",null,null); } if(!condition) subScript=parsedBlocks.second; parsedBlocks.second.addSharedElements(script.elementsAt(si)); } } si++; } if(!foundendif) { logError(scripted,"IF","Syntax"," Without ENDIF!"); tickStatus=Tickable.STATUS_END; return null; } if((subScript != null) &&(subScript.size()>1)) { //source.tell(L("Starting @x1",conditionStr)); //for(int v=0;v<V.size();v++) // source.tell(L("Statement @x1",((String)V.elementAt(v)))); final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } //source.tell(L("Stopping @x1",conditionStr)); } break; } case 93: // "ENDIF", //93 JUST for catching errors... logError(scripted,"ENDIF","Syntax"," Without IF ("+si+")!"); break; case 94: //"ENDSWITCH", //94 JUST for catching errors... logError(scripted,"ENDSWITCH","Syntax"," Without SWITCH ("+si+")!"); break; case 95: //"NEXT", //95 JUST for catching errors... logError(scripted,"NEXT","Syntax"," Without FOR ("+si+")!"); break; case 96: //"CASE" //96 JUST for catching errors... logError(scripted,"CASE","Syntax"," Without SWITCH ("+si+")!"); break; case 97: //"DEFAULT" //97 JUST for catching errors... logError(scripted,"DEFAULT","Syntax"," Without SWITCH ("+si+")!"); break; case 70: // switch { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; if(script.elementAt(si, 3)==null) script.setElementAt(si, 3, new Hashtable<String,Integer>()); } @SuppressWarnings("unchecked") final Map<String,Integer> skipSwitchMap=(Map<String,Integer>)script.elementAt(si, 3); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim(); final DVector subScript=new DVector(3); subScript.addElement("",null,null); int depth=0; boolean foundEndSwitch=false; boolean ignoreUntilEndScript=false; boolean inCase=false; boolean matchedCase=false; si++; String s2=null; if(skipSwitchMap.size()>0) { if(skipSwitchMap.containsKey(var.toUpperCase())) { inCase=true; matchedCase=true; si=skipSwitchMap.get(var.toUpperCase()).intValue(); si++; } else if(skipSwitchMap.containsKey("$FIRSTVAR")) // first variable case { si=skipSwitchMap.get("$FIRSTVAR").intValue(); } else if(skipSwitchMap.containsKey("$DEFAULT")) // the "default" case { inCase=true; matchedCase=true; si=skipSwitchMap.get("$DEFAULT").intValue(); si++; } else if(skipSwitchMap.containsKey("$ENDSWITCH")) // the "endswitch" case { foundEndSwitch=true; si=skipSwitchMap.get("$ENDSWITCH").intValue(); } } while((si<script.size()) &&(!foundEndSwitch)) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=true; } else if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=false; } else if(ignoreUntilEndScript) { // only applies when <SCRIPT> encountered. } else if(cmd.equals("ENDSWITCH")&&(depth==0)) { if(tt==null) { tt=parseBits(script,si,"C"); skipSwitchMap.put("$ENDSWITCH", Integer.valueOf(si)); } foundEndSwitch=true; break; } else if(cmd.equals("CASE")&&(depth==0)) { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; if(tt[1].indexOf('$')>=0) { if(!skipSwitchMap.containsKey("$FIRSTVAR")) skipSwitchMap.put("$FIRSTVAR", Integer.valueOf(si)); } else if(!skipSwitchMap.containsKey(tt[1].toUpperCase())) skipSwitchMap.put(tt[1].toUpperCase(), Integer.valueOf(si)); } if(matchedCase &&inCase &&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done { foundEndSwitch=true; si=skipSwitchMap.get("$ENDSWITCH").intValue(); break; // this is important, otherwise si will get increment and screw stuff up } else { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim(); inCase=var.equalsIgnoreCase(s2); matchedCase=matchedCase||inCase; } } else if(cmd.equals("DEFAULT")&&(depth==0)) { if(tt==null) { tt=parseBits(script,si,"C"); if(!skipSwitchMap.containsKey("$DEFAULT")) skipSwitchMap.put("$DEFAULT", Integer.valueOf(si)); } if(matchedCase &&inCase &&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done { foundEndSwitch=true; si=skipSwitchMap.get("$ENDSWITCH").intValue(); break; // this is important, otherwise si will get increment and screw stuff up } else inCase=!matchedCase; } else { if(inCase) subScript.addSharedElements(script.elementsAt(si)); if(cmd.equals("SWITCH")) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(script.elementAt(si, 3)==null) script.setElementAt(si, 3, new Hashtable<String,Integer>()); } depth++; } else if(cmd.equals("ENDSWITCH")) { if(tt==null) tt=parseBits(script,si,"C"); depth--; } } si++; } if(!foundEndSwitch) { logError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!"); tickStatus=Tickable.STATUS_END; return null; } if(subScript.size()>1) { final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } } break; } case 62: // for x = 1 to 100 { if(tt==null) { tt=parseBits(script,si,"CcccCr"); if(tt==null) return null; } if(tt[5].length()==0) { logError(scripted,"FOR","Syntax","5 parms required!"); tickStatus=Tickable.STATUS_END; return null; } final String varStr=tt[1]; if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1)))) { logError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2.."); tickStatus=Tickable.STATUS_END; return null; } final int whichVar=CMath.s_int(Character.toString(varStr.charAt(1))); if((tmp[whichVar] instanceof String) &&(((String)tmp[whichVar]).length()>0) &&(CMath.isInteger(((String)tmp[whichVar]).trim()))) { logError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!"); tickStatus=Tickable.STATUS_END; return null; } if(!tt[2].equals("=")) { logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!"); tickStatus=Tickable.STATUS_END; return null; } int toAdd=0; if(tt[4].equals("TO<")) toAdd=-1; else if(tt[4].equals("TO>")) toAdd=1; else if(!tt[4].equals("TO")) { logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!"); tickStatus=Tickable.STATUS_END; return null; } final String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim(); final String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]).trim(); if((!CMath.isInteger(from))||(!CMath.isInteger(to))) { logError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!"); tickStatus=Tickable.STATUS_END; return null; } final DVector subScript=new DVector(3); subScript.addElement("",null,null); int depth=0; boolean foundnext=false; boolean ignoreUntilEndScript=false; si++; while(si<script.size()) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=true; } else if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=false; } else if(ignoreUntilEndScript) { } else if(cmd.equals("NEXT")&&(depth==0)) { if(tt==null) tt=parseBits(script,si,"C"); foundnext=true; break; } else { if(cmd.equals("FOR")) { if(tt==null) tt=parseBits(script,si,"CcccCr"); depth++; } else if(cmd.equals("NEXT")) { if(tt==null) tt=parseBits(script,si,"C"); depth--; } subScript.addSharedElements(script.elementsAt(si)); } si++; } if(!foundnext) { logError(scripted,"FOR","Syntax"," Without NEXT!"); tickStatus=Tickable.STATUS_END; return null; } if(subScript.size()>1) { //source.tell(L("Starting @x1",conditionStr)); //for(int v=0;v<V.size();v++) // source.tell(L("Statement @x1",((String)V.elementAt(v)))); final int fromInt=CMath.s_int(from); int toInt=CMath.s_int(to); final int increment=(toInt>=fromInt)?1:-1; String response=null; if(((increment>0)&&(fromInt<=(toInt+toAdd))) ||((increment<0)&&(fromInt>=(toInt+toAdd)))) { toInt+=toAdd; final long tm=System.currentTimeMillis()+(10 * 1000); for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment) { tmp[whichVar]=""+forLoop; response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); if(response!=null) break; if((System.currentTimeMillis()>tm) || (scripted.amDestroyed())) { logError(scripted,"FOR","Runtime","For loop violates 10 second rule: " +s); break; } } tmp[whichVar]=""+toInt; if(response == null) response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); else if(response.equalsIgnoreCase("break")) response=null; } if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } tmp[whichVar]=null; //source.tell(L("Stopping @x1",conditionStr)); } break; } case 50: // break; if(tt==null) tt=parseBits(script,si,"C"); tickStatus=Tickable.STATUS_END; return "BREAK"; case 1: // mpasound { if(tt==null) { tt=parseBits(script,si,"Cp"); if(tt==null) return null; } final String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); //lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo); for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room R2=lastKnownLocation.getRoomInDir(d); final Exit E2=lastKnownLocation.getExitInDir(d); if((R2!=null)&&(E2!=null)&&(E2.isOpen())) R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo); } break; } case 4: // mpjunk { if(tt==null) { tt=parseBits(script,si,"CR"); if(tt==null) return null; } if(tt[1].equals("ALL") && (monster!=null)) { monster.delAllItems(true); } else { final Environmental E=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Item I=null; if(E instanceof Item) I=(Item)E; if((I==null)&&(monster!=null)) I=monster.findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1])); if((I==null)&&(scripted instanceof Room)) I=((Room)scripted).findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1])); if(I!=null) I.destroy(); } break; } case 2: // mpecho { if(tt==null) { tt=parseBits(script,si,"Cp"); if(tt==null) return null; } if(lastKnownLocation!=null) lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1])); break; } case 13: // mpunaffect { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String which=tt[2]; if(newTarget!=null) if(which.equalsIgnoreCase("all")||(which.length()==0)) { for(int a=newTarget.numEffects()-1;a>=0;a--) { final Ability A=newTarget.fetchEffect(a); if(A!=null) A.unInvoke(); } } else { final Ability A2=CMClass.findAbility(which); if(A2!=null) which=A2.ID(); final Ability A=newTarget.fetchEffect(which); if(A!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPUNAFFECTED by "+A.Name()); A.unInvoke(); if(newTarget.fetchEffect(which)==A) newTarget.delEffect(A); } } break; } case 3: // mpslay { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) CMLib.combat().postDeath(monster,(MOB)newTarget,null); break; } case 73: // mpsetinternal { if(tt==null) { tt=parseBits(script,si,"CCr"); if(tt==null) return null; } final String arg2=tt[1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if(arg2.equals("SCOPE")) setVarScope(arg3); else if(arg2.equals("NODELAY")) noDelay=CMath.s_bool(arg3); else if(arg2.equals("ACTIVETRIGGER")||arg2.equals("ACTIVETRIGGERS")) alwaysTriggers=CMath.s_bool(arg3); else if(arg2.equals("DEFAULTQUEST")) registerDefaultQuest(arg3); else if(arg2.equals("SAVABLE")) setSavable(CMath.s_bool(arg3)); else if(arg2.equals("PASSIVE")) this.runInPassiveAreas = CMath.s_bool(arg3); else logError(scripted,"MPSETINTERNAL","Syntax","Unknown stat: "+arg2); break; } case 74: // mpprompt { if(tt==null) { tt=parseBits(script,si,"CCCr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null))) { try { final String value=((MOB)newTarget).session().prompt(promptStr,120000); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<"); setVar(newTarget.Name(),var,value); } catch(final Exception e) { return ""; } } break; } case 75: // mpconfirm { if(tt==null) { tt=parseBits(script,si,"CCCCr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null))) { try { final String value=((MOB)newTarget).session().confirm(promptStr,defaultVal,60000)?"Y":"N"; if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<"); setVar(newTarget.Name(),var,value); } catch(final Exception e) { return ""; } /* * this is how to do non-blocking, which doesn't help stuff waiting * for a response from the original execute method final Session session = ((MOB)newTarget).session(); if(session != null) { try { final int lastLineNum=si; final JScriptEvent continueEvent=new JScriptEvent( this, scripted, source, target, monster, primaryItem, secondaryItem, msg, tmp); ((MOB)newTarget).session().prompt(new InputCallback(InputCallback.Type.PROMPT,"",0) { private final JScriptEvent event=continueEvent; private final int lineNum=lastLineNum; private final String scope=newTarget.Name(); private final String varName=var; private final String promptStrMsg=promptStr; private final DVector lastScript=script; @Override public void showPrompt() { session.promptPrint(promptStrMsg); } @Override public void timedOut() { event.executeEvent(lastScript, lineNum+1); } @Override public void callBack() { final String value=this.input; if((value.trim().length()==0)||(value.indexOf('<')>=0)) return; setVar(scope,varName,value); event.executeEvent(lastScript, lineNum+1); } }); } catch(final Exception e) { return ""; } } */ } break; } case 76: // mpchoose { if(tt==null) { tt=parseBits(script,si,"CCCCCr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String choices=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]); if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null))) { try { final String value=((MOB)newTarget).session().choose(promptStr,choices,defaultVal,60000); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<"); setVar(newTarget.Name(),var,value); } catch(final Exception e) { return ""; } } break; } case 16: // mpset { if(tt==null) { tt=parseBits(script,si,"CCcr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[2]; String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(arg2,arg3); found=true; break; } } if((!found)&&(newTarget instanceof MOB)) { final MOB M=(MOB)newTarget; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } } } if(!found) { for(int i=0;i<M.basePhyStats().getStatCodes().length;i++) { if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1); M.basePhyStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) { for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg2.substring(4),arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().equals("STINK"))) { found=true; if(M.playerStats()!=null) M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT)); } if((!found) &&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,arg2.toUpperCase())!=null)) { found=true; CMLib.coffeeMaker().setAnyGenStat(M, arg2.toUpperCase(), arg3); } } if((!found) &&(newTarget instanceof Item)) { if((!found) &&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,arg2.toUpperCase())!=null)) { found=true; CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3); } } if((!found) &&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,arg2.toUpperCase())!=null)) { found=true; CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3); } if(!found) { logError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverPhyStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverPhyStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 63: // mpargset { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String arg1=tt[1]; final String arg2=tt[2]; if((arg1.length()!=2)||(!arg1.startsWith("$"))) { logError(scripted,"MPARGSET","Syntax","Mangled argument var: "+arg1+" for "+scripted.Name()); break; } Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(O==null) O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((O==null) &&((arg2.length()!=2) ||(arg2.charAt(1)=='g') ||(!arg2.startsWith("$")) ||((!Character.isDigit(arg2.charAt(1))) &&(!Character.isLetter(arg2.charAt(1)))))) O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2); final char c=arg1.charAt(1); if(Character.isDigit(c)) { if((O instanceof String)&&(((String)O).equalsIgnoreCase("null"))) O=null; tmp[CMath.s_int(Character.toString(c))]=O; } else { switch(arg1.charAt(1)) { case 'N': case 'n': if (O instanceof MOB) source = (MOB) O; break; case 'B': case 'b': if (O instanceof Environmental) lastLoaded = (Environmental) O; break; case 'I': case 'i': if (O instanceof PhysicalAgent) scripted = (PhysicalAgent) O; if (O instanceof MOB) monster = (MOB) O; break; case 'T': case 't': if (O instanceof Environmental) target = (Environmental) O; break; case 'O': case 'o': if (O instanceof Item) primaryItem = (Item) O; break; case 'P': case 'p': if (O instanceof Item) secondaryItem = (Item) O; break; case 'd': case 'D': if (O instanceof Room) lastKnownLocation = (Room) O; break; case 'g': case 'G': if (O instanceof String) msg = (String) O; else if((O instanceof Room) &&((((Room)O).roomID().length()>0) || (!"".equals(CMLib.map().getExtendedRoomID((Room)O))))) msg = CMLib.map().getExtendedRoomID((Room)O); else if(O instanceof CMObject) msg=((CMObject)O).name(); else msg=""+O; break; default: logError(scripted, "MPARGSET", "Syntax", "Invalid argument var: " + arg1 + " for " + scripted.Name()); break; } } break; } case 35: // mpgset { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[2]; String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(newTarget.getStatCodes()[i],arg3); found=true; break; } } if(!found) { if(newTarget instanceof MOB) { final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2.toUpperCase().trim()); if(element != null) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))-1); CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,element.name(),arg3); found=true; } if(!found) { final MOB M=(MOB)newTarget; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0)))) M.baseCharStats().setStat(i,arg3.charAt(0)); else M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } } } if(!found) { for(int i=0;i<M.basePhyStats().getStatCodes().length;i++) { if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1); M.basePhyStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) { final String arg4=arg2.substring(4); for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg4)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg4,arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().equals("STINK"))) { found=true; if(M.playerStats()!=null) M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT)); } } } } else if(newTarget instanceof Item) { final GenericBuilder.GenItemCode element = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class,arg2.toUpperCase().trim()); if(element != null) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))-1); CMLib.coffeeMaker().setGenItemStat((Item)newTarget,element.name(),arg3); found=true; } } if((!found) &&(newTarget instanceof Physical)) { if(CMLib.coffeeMaker().isAnyGenStat(newTarget, arg2.toUpperCase())) { CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3); found=true; } } if(!found) { logError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverPhyStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverPhyStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 11: // mpexp { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); int t=CMath.s_int(amtStr); if((newTarget!=null)&&(newTarget instanceof MOB)) { if((amtStr.endsWith("%")) &&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE)) { final int baseLevel=newTarget.basePhyStats().level(); final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1); final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel); t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded, CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0))); } if(t!=0) CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false); } break; } case 86: // mprpexp { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); int t=CMath.s_int(amtStr); if((newTarget!=null)&&(newTarget instanceof MOB)) { if((amtStr.endsWith("%")) &&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE)) { final int baseLevel=newTarget.basePhyStats().level(); final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1); final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel); t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded, CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0))); } if(t!=0) CMLib.leveler().postRPExperience((MOB)newTarget,null,null,t,false); } break; } case 77: // mpmoney { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } Environmental newTarget=getArgumentMOB(tt[1],source,monster,scripted,primaryItem,secondaryItem,msg,tmp); if(newTarget==null) newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String amtStr=tt[2]; amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,amtStr).trim(); final boolean plus=!amtStr.startsWith("-"); if(amtStr.startsWith("+")||amtStr.startsWith("-")) amtStr=amtStr.substring(1).trim(); final String currency = CMLib.english().parseNumPossibleGoldCurrency(source, amtStr); final long amt = CMLib.english().parseNumPossibleGold(source, amtStr); final double denomination = CMLib.english().parseNumPossibleGoldDenomination(source, currency, amtStr); Container container = null; if(newTarget instanceof Item) { container = (newTarget instanceof Container)?(Container)newTarget:null; newTarget = ((Item)newTarget).owner(); } if(newTarget instanceof MOB) { if(plus) CMLib.beanCounter().giveSomeoneMoney((MOB)newTarget, currency, amt * denomination); else CMLib.beanCounter().subtractMoney((MOB)newTarget, currency, amt * denomination); } else { if(!(newTarget instanceof Room)) newTarget=lastKnownLocation; if(plus) CMLib.beanCounter().dropMoney((Room)newTarget, container, currency, amt * denomination); else CMLib.beanCounter().removeMoney((Room)newTarget, container, currency, amt * denomination); } break; } case 59: // mpquestpoints { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget instanceof MOB) { if(CMath.isNumber(val)) { final int ival=CMath.s_int(val); final int aval=ival-((MOB)newTarget).getQuestPoint(); ((MOB)newTarget).setQuestPoint(CMath.s_int(val)); if(aval>0) CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, aval); } else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) { ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim())); CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, CMath.s_int(val.substring(2).trim())); } else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim())); else logError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 65: // MPQSET { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final PhysicalAgent obj=getArgumentItem(tt[3],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final Quest Q=getQuest(qstr); if(Q==null) logError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name()); else if(var.equalsIgnoreCase("QUESTOBJ")) { if(obj==null) logError(scripted,"MPQSET","Syntax","Unknown object "+tt[3]+" for "+scripted.Name()); else { obj.basePhyStats().setDisposition(obj.basePhyStats().disposition()|PhyStats.IS_UNSAVABLE); obj.recoverPhyStats(); Q.runtimeRegisterObject(obj); } } else if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("ACCEPTED"))) CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTACCEPTED); else if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("SUCCESS")||val.equalsIgnoreCase("WON"))) CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSUCCESS); else if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("FAILED"))) CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTFAILED); else { if(val.equals("++")) val=""+(CMath.s_int(Q.getStat(var))+1); if(val.equals("--")) val=""+(CMath.s_int(Q.getStat(var))-1); Q.setStat(var,val); } break; } case 66: // MPLOG { if(tt==null) { tt=parseBits(script,si,"CCcr"); if(tt==null) return null; } final String type=tt[1]; final String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(type.startsWith("E")) Log.errOut("Script","["+head+"] "+val); else if(type.startsWith("I")||type.startsWith("S")) Log.infoOut("Script","["+head+"] "+val); else if(type.startsWith("D")) Log.debugOut("Script","["+head+"] "+val); else logError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name()); break; } case 67: // MPCHANNEL { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final boolean sysmsg=channel.startsWith("!"); if(sysmsg) channel=channel.substring(1); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if(CMLib.channels().getChannelCodeNumber(channel)<0) logError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name()); else CMLib.commands().postChannel(monster,channel,val,sysmsg); break; } case 68: // MPUNLOADSCRIPT { if(tt==null) { tt=parseBits(script,si,"Cc"); if(tt==null) return null; } String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(!new CMFile(Resources.makeFileResourceName(scriptname),null,CMFile.FLAG_FORCEALLOW).exists()) logError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname)); else { final ArrayList<String> delThese=new ArrayList<String>(); scriptname=scriptname.toUpperCase().trim(); final String parmname=scriptname; for(final Iterator<String> k = Resources.findResourceKeys(parmname);k.hasNext();) { final String key=k.next(); if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname))) { delThese.add(key); } } for(int i=0;i<delThese.size();i++) Resources.removeResource(delThese.get(i)); } break; } case 60: // MPTRAINS { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget instanceof MOB) { if(CMath.isNumber(val)) ((MOB)newTarget).setTrains(CMath.s_int(val)); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim())); else logError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 61: // mppracs { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget instanceof MOB) { if(CMath.isNumber(val)) ((MOB)newTarget).setPractices(CMath.s_int(val)); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim())); else logError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 5: // mpmload { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final ArrayList<Environmental> Ms=new ArrayList<Environmental>(); MOB m=CMClass.getMOB(name); if(m!=null) Ms.add(m); if(lastKnownLocation!=null) { if(Ms.size()==0) findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true); for(int i=0;i<Ms.size();i++) { if(Ms.get(i) instanceof MOB) { m=(MOB)((MOB)Ms.get(i)).copyOf(); m.text(); m.recoverPhyStats(); m.recoverCharStats(); m.resetToMaxState(); m.bringToLife(lastKnownLocation,true); lastLoaded=m; } } } break; } case 6: // mpoload { //if not mob Physical addHere; if(scripted instanceof MOB) addHere=monster; else if(scripted instanceof Item) addHere=((Item)scripted).owner(); else if(scripted instanceof Room) addHere=scripted; else addHere=lastKnownLocation; if(addHere!=null) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } this.lastLoaded = null; String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final int containerIndex=name.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { final ArrayList<Environmental> containers=new ArrayList<Environmental>(); findSomethingCalledThis(name.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) { if((containers.get(c) instanceof Container) &&(((Container)containers.get(c)).capacity()>0)) { container=(Container)containers.get(c); name=name.substring(0,containerIndex).trim(); break; } } } final long coins=CMLib.english().parseNumPossibleGold(null,name); if(coins>0) { final String currency=CMLib.english().parseNumPossibleGoldCurrency(scripted,name); final double denom=CMLib.english().parseNumPossibleGoldDenomination(scripted,currency,name); final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); if(addHere instanceof MOB) ((MOB)addHere).addItem(C); else if(addHere instanceof Room) ((Room)addHere).addItem(C, Expire.Monster_EQ); C.putCoinsBack(); } else if(lastKnownLocation!=null) { final ArrayList<Environmental> Is=new ArrayList<Environmental>(); Item m=CMClass.getItem(name); if(m!=null) Is.add(m); else findSomethingCalledThis(name,monster,lastKnownLocation,Is,false); for(int i=0;i<Is.size();i++) { if(Is.get(i) instanceof Item) { m=(Item)Is.get(i); if((m!=null) &&(!(m instanceof ArchonOnly))) { m=(Item)m.copyOf(); m.recoverPhyStats(); m.setContainer(container); if(container instanceof MOB) ((MOB)container.owner()).addItem(m); else if(container instanceof Room) ((Room)container.owner()).addItem(m,ItemPossessor.Expire.Player_Drop); else if(addHere instanceof MOB) ((MOB)addHere).addItem(m); else if(addHere instanceof Room) ((Room)addHere).addItem(m, Expire.Monster_EQ); lastLoaded=m; } } } if(addHere instanceof MOB) { ((MOB)addHere).recoverCharStats(); ((MOB)addHere).recoverMaxState(); } addHere.recoverPhyStats(); lastKnownLocation.recoverRoomStats(); } } break; } case 41: // mpoloadroom { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(lastKnownLocation!=null) { final ArrayList<Environmental> Is=new ArrayList<Environmental>(); final int containerIndex=name.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { final ArrayList<Environmental> containers=new ArrayList<Environmental>(); findSomethingCalledThis(name.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) { if((containers.get(c) instanceof Container) &&(((Container)containers.get(c)).capacity()>0)) { container=(Container)containers.get(c); name=name.substring(0,containerIndex).trim(); break; } } } final long coins=CMLib.english().parseNumPossibleGold(null,name); if(coins>0) { final String currency=CMLib.english().parseNumPossibleGoldCurrency(monster,name); final double denom=CMLib.english().parseNumPossibleGoldDenomination(monster,currency,name); final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); Is.add(C); } else { final Item I=CMClass.getItem(name); if(I!=null) Is.add(I); else findSomethingCalledThis(name,monster,lastKnownLocation,Is,false); } for(int i=0;i<Is.size();i++) { if(Is.get(i) instanceof Item) { Item I=(Item)Is.get(i); if((I!=null) &&(!(I instanceof ArchonOnly))) { I=(Item)I.copyOf(); I.recoverPhyStats(); lastKnownLocation.addItem(I,ItemPossessor.Expire.Monster_EQ); I.setContainer(container); if(I instanceof Coins) ((Coins)I).putCoinsBack(); if(I instanceof RawMaterial) ((RawMaterial)I).rebundle(); lastLoaded=I; } } } lastKnownLocation.recoverRoomStats(); } break; } case 84: // mpoloadshop { ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted); if((addHere == null)&&(scripted instanceof Item)) addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner()); if((addHere == null)&&(scripted instanceof MOB)) addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location()); if(addHere == null) addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(addHere!=null) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(lastKnownLocation!=null) { final ArrayList<Environmental> Is=new ArrayList<Environmental>(); int price=-1; if((price = name.indexOf(" PRICE="))>=0) { final String rest = name.substring(price+7).trim(); name=name.substring(0,price).trim(); if(CMath.isInteger(rest)) price=CMath.s_int(rest); } Item I=CMClass.getItem(name); if(I!=null) Is.add(I); else findSomethingCalledThis(name,monster,lastKnownLocation,Is,false); for(int i=0;i<Is.size();i++) { if(Is.get(i) instanceof Item) { I=(Item)Is.get(i); if((I!=null) &&(!(I instanceof ArchonOnly))) { I=(Item)I.copyOf(); I.recoverPhyStats(); final CoffeeShop shop = addHere.getShop(); if(shop != null) { final Environmental E=shop.addStoreInventory(I,1,price); if(E!=null) setShopPrice(addHere, E, tmp); } I.destroy(); } } } lastKnownLocation.recoverRoomStats(); } } break; } case 85: // mpmloadshop { ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted); if((addHere == null)&&(scripted instanceof Item)) addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner()); if((addHere == null)&&(scripted instanceof MOB)) addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location()); if(addHere == null) addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(addHere!=null) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } this.lastLoaded = null; String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); int price=-1; if((price = name.indexOf(" PRICE="))>=0) { final String rest = name.substring(price+7).trim(); name=name.substring(0,price).trim(); if(CMath.isInteger(rest)) price=CMath.s_int(rest); } final ArrayList<Environmental> Ms=new ArrayList<Environmental>(); MOB m=CMClass.getMOB(name); if(m!=null) Ms.add(m); if(lastKnownLocation!=null) { if(Ms.size()==0) findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true); for(int i=0;i<Ms.size();i++) { if(Ms.get(i) instanceof MOB) { m=(MOB)((MOB)Ms.get(i)).copyOf(); m.text(); m.recoverPhyStats(); m.recoverCharStats(); m.resetToMaxState(); final CoffeeShop shop = addHere.getShop(); if(shop != null) { final Environmental E=shop.addStoreInventory(m,1,price); if(E!=null) setShopPrice(addHere, E, tmp); } m.destroy(); } } } } break; } case 42: // mphide { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()|PhyStats.IS_NOT_SEEN); newTarget.recoverPhyStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 58: // mpreset { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(arg.equalsIgnoreCase("area")) { if(lastKnownLocation!=null) CMLib.map().resetArea(lastKnownLocation.getArea()); } else if(arg.equalsIgnoreCase("room")) { if(lastKnownLocation!=null) CMLib.map().resetRoom(lastKnownLocation, true); } else { final Room R=CMLib.map().getRoom(arg); if(R!=null) CMLib.map().resetRoom(R, true); else { final Area A=CMLib.map().findArea(arg); if(A!=null) CMLib.map().resetArea(A); else { final Physical newTarget=getArgumentItem(arg,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget == null) logError(scripted,"MPRESET","Syntax","Unknown location or item: "+arg+" for "+scripted.Name()); else if(newTarget instanceof Item) { final Item I=(Item)newTarget; I.setContainer(null); if(I.subjectToWearAndTear()) I.setUsesRemaining(100); I.recoverPhyStats(); } else if(newTarget instanceof MOB) { final MOB M=(MOB)newTarget; M.resetToMaxState(); M.recoverMaxState(); M.recoverCharStats(); M.recoverPhyStats(); } } } } break; } case 71: // mprejuv { if(tt==null) { final String rest=CMParms.getPastBitClean(s,1); if(rest.equals("item")||rest.equals("items")) tt=parseBits(script,si,"Ccr"); else if(rest.equals("mob")||rest.equals("mobs")) tt=parseBits(script,si,"Ccr"); else tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String next=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); String rest=""; if(tt.length>2) rest=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); int tickID=-1; if(rest.equalsIgnoreCase("item")||rest.equalsIgnoreCase("items")) tickID=Tickable.TICKID_ROOM_ITEM_REJUV; else if(rest.equalsIgnoreCase("mob")||rest.equalsIgnoreCase("mobs")) tickID=Tickable.TICKID_MOB; if(next.equalsIgnoreCase("area")) { if(lastKnownLocation!=null) for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) CMLib.threads().rejuv(e.nextElement(),tickID); } else if(next.equalsIgnoreCase("room")) { if(lastKnownLocation!=null) CMLib.threads().rejuv(lastKnownLocation,tickID); } else { final Room R=CMLib.map().getRoom(next); if(R!=null) CMLib.threads().rejuv(R,tickID); else { final Area A=CMLib.map().findArea(next); if(A!=null) { for(final Enumeration<Room> e=A.getProperMap();e.hasMoreElements();) CMLib.threads().rejuv(e.nextElement(),tickID); } else logError(scripted,"MPREJUV","Syntax","Unknown location: "+next+" for "+scripted.Name()); } } break; } case 56: // mpstop { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final List<MOB> V=new ArrayList<MOB>(); final String who=tt[1]; if(who.equalsIgnoreCase("all")) { for(int i=0;i<lastKnownLocation.numInhabitants();i++) V.add(lastKnownLocation.fetchInhabitant(i)); } else { final Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget instanceof MOB) V.add((MOB)newTarget); } for(int v=0;v<V.size();v++) { final Environmental newTarget=V.get(v); if(newTarget instanceof MOB) { final MOB mob=(MOB)newTarget; Ability A=null; for(int a=mob.numEffects()-1;a>=0;a--) { A=mob.fetchEffect(a); if((A!=null) &&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL) &&(A.canBeUninvoked()) &&(!A.isAutoInvoked())) A.unInvoke(); } mob.makePeace(false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } } break; } case 43: // mpunhide { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(CMath.bset(newTarget.basePhyStats().disposition(),PhyStats.IS_NOT_SEEN))) { newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()-PhyStats.IS_NOT_SEEN); newTarget.recoverPhyStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 44: // mpopen { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasADoor())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 45: // mpclose { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit) &&(((Exit)newTarget).hasADoor()) &&(((Exit)newTarget).isOpen())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container) &&(((Container)newTarget).hasADoor()) &&(((Container)newTarget).isOpen())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 46: // mplock { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit) &&(((Exit)newTarget).hasALock())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container) &&(((Container)newTarget).hasALock())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 47: // mpunlock { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit) &&(((Exit)newTarget).isLocked())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container) &&(((Container)newTarget).isLocked())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 48: // return if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } tickStatus=Tickable.STATUS_END; return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); case 87: // mea case 7: // mpechoat { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final String parm=tt[1]; final Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { if(newTarget==monster) lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); else lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]),CMMsg.NO_EFFECT,null); } else if(parm.equalsIgnoreCase("world")) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } } else if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null)) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } } else if(CMLib.map().getRoom(parm)!=null) CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); else if(CMLib.map().findArea(parm)!=null) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); for(final Enumeration<Room> e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } } break; } case 88: // mer case 8: // mpechoaround { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } break; } case 9: // mpcast { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null) &&(A!=null)) { A.setProficiency(100); if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster,newTarget,false,0); } break; } case 89: // mpcastexp { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String args=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null) &&(A!=null)) { A.setProficiency(100); final List<String> commands = CMParms.parse(args); if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster, commands, newTarget, false, 0); } break; } case 30: // mpaffect { if(tt==null) { tt=parseBits(script,si,"Cccp"); if(tt==null) return null; } final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null)&&(A!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPAFFECTED by "+A.Name()); A.setMiscText(m2); if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY) newTarget.addNonUninvokableEffect(A); else { if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster,CMParms.parse(m2),newTarget,true,0); } } break; } case 80: // mpspeak { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String language=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final Ability A=CMClass.getAbility(language); if((A instanceof Language)&&(newTarget instanceof MOB)) { ((Language)A).setProficiency(100); ((Language)A).autoInvocation((MOB)newTarget, false); final Ability langA=((MOB)newTarget).fetchEffect(A.ID()); if(langA!=null) { if(((MOB)newTarget).isMonster()) langA.setProficiency(100); langA.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0); } else A.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0); } break; } case 81: // mpsetclan { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String clan=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String roleStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Clan C=CMLib.clans().getClan(clan); if(C==null) C=CMLib.clans().findClan(clan); if((newTarget instanceof MOB)&&(C!=null)) { int role=Integer.MIN_VALUE; if(CMath.isInteger(roleStr)) role=CMath.s_int(roleStr); else for(int i=0;i<C.getRolesList().length;i++) { if(roleStr.equalsIgnoreCase(C.getRolesList()[i])) role=i; } if(role!=Integer.MIN_VALUE) { if(((MOB)newTarget).isPlayer()) C.addMember((MOB)newTarget, role); else ((MOB)newTarget).setClan(C.clanID(), role); } } break; } case 31: // mpbehave { if(tt==null) { tt=parseBits(script,si,"Cccp"); if(tt==null) return null; } String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Behavior B=null; final Behavior B2=(cast==null)?null:CMClass.findBehavior(cast); if(B2!=null) cast=B2.ID(); if((cast!=null)&&(newTarget!=null)) { B=newTarget.fetchBehavior(cast); if(B==null) B=CMClass.getBehavior(cast); } if((newTarget!=null)&&(B!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPBEHAVED with "+B.name()); B.setParms(m2); if(newTarget.fetchBehavior(B.ID())==null) { newTarget.addBehavior(B); if((defaultQuestName()!=null)&&(defaultQuestName().length()>0)) B.registerDefaultQuest(defaultQuestName()); } } break; } case 72: // mpscript { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final PhysicalAgent newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); boolean proceed=true; boolean savable=false; boolean execute=false; String scope=getVarScope(); while(proceed) { proceed=false; if(m2.toUpperCase().startsWith("SAVABLE ")) { savable=true; m2=m2.substring(8).trim(); proceed=true; } else if(m2.toUpperCase().startsWith("EXECUTE ")) { execute=true; m2=m2.substring(8).trim(); proceed=true; } else if(m2.toUpperCase().startsWith("GLOBAL ")) { scope=""; proceed=true; m2=m2.substring(6).trim(); } else if(m2.toUpperCase().startsWith("INDIVIDUAL ")||m2.equals("*")) { scope="*"; proceed=true; m2=m2.substring(10).trim(); } } if((newTarget!=null)&&(m2.length()>0)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPSCRIPTED: "+defaultQuestName); final ScriptingEngine S=(ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine"); S.setSavable(savable); S.setVarScope(scope); S.setScript(m2); if((defaultQuestName()!=null)&&(defaultQuestName().length()>0)) S.registerDefaultQuest(defaultQuestName()); newTarget.addScript(S); if(execute) { S.tick(newTarget,Tickable.TICKID_MOB); for(int i=0;i<5;i++) S.dequeResponses(); newTarget.delScript(S); } } break; } case 32: // mpunbehave { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(cast!=null)) { Behavior B=CMClass.findBehavior(cast); if(B!=null) cast=B.ID(); B=newTarget.fetchBehavior(cast); if(B!=null) newTarget.delBehavior(B); if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(B!=null)) Log.sysOut("Scripting",newTarget.Name()+" was MPUNBEHAVED with "+B.name()); } break; } case 33: // mptattoo { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB)) { final MOB themob=(MOB)newTarget; final boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName); final Tattoo T=themob.findTattoo(pT.getTattooName()); if(T!=null) { if(tattooMinus) themob.delTattoo(T); } else if(!tattooMinus) themob.addTattoo(pT); } break; } case 83: // mpacctattoo { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if((newTarget!=null) &&(tattooName.length()>0) &&(newTarget instanceof MOB) &&(((MOB)newTarget).playerStats()!=null) &&(((MOB)newTarget).playerStats().getAccount()!=null)) { final Tattooable themob=((MOB)newTarget).playerStats().getAccount(); final boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName); final Tattoo T=themob.findTattoo(pT.getTattooName()); if(T!=null) { if(tattooMinus) themob.delTattoo(T); } else if(!tattooMinus) themob.addTattoo(pT); } break; } case 92: // mpput { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { if(tt[2].equalsIgnoreCase("NULL")||tt[2].equalsIgnoreCase("NONE")) { if(newTarget instanceof Item) ((Item)newTarget).setContainer(null); if(newTarget instanceof Rider) ((Rider)newTarget).setRiding(null); } else { final Physical newContainer=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newContainer!=null) { if((newTarget instanceof Item) &&(newContainer instanceof Container)) ((Item)newTarget).setContainer((Container)newContainer); if((newTarget instanceof Rider) &&(newContainer instanceof Rideable)) ((Rider)newTarget).setRiding((Rideable)newContainer); } } newTarget.recoverPhyStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 55: // mpnotrigger { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); int triggerCode=-1; for(int i=0;i<progs.length;i++) { if(trigger.equalsIgnoreCase(progs[i])) triggerCode=i; } if(triggerCode<0) logError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name."); else if(!CMath.isInteger(time.trim())) logError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time."); else { noTrigger.remove(Integer.valueOf(triggerCode)); noTrigger.put(Integer.valueOf(triggerCode),Long.valueOf(System.currentTimeMillis()+CMath.s_long(time.trim()))); } break; } case 54: // mpfaction { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim(); final Faction F=CMLib.factions().getFaction(faction); if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB)) { final MOB themob=(MOB)newTarget; int curFaction = themob.fetchFaction(F.factionID()); if((curFaction == Integer.MAX_VALUE)||(curFaction == Integer.MIN_VALUE)) curFaction = F.findDefault(themob); if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim()))) { final int amt=CMath.s_int(range.substring(2).trim()); if(amt < 0) themob.tell(L("You gain @x1 faction with @x2.",""+(-amt),F.name())); else themob.tell(L("You lose @x1 faction with @x2.",""+amt,F.name())); range=""+(curFaction-amt); } else if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim()))) { final int amt=CMath.s_int(range.substring(1).trim()); if(amt < 0) themob.tell(L("You lose @x1 faction with @x2.",""+(-amt),F.name())); else themob.tell(L("You gain @x1 faction with @x2.",""+amt,F.name())); range=""+(curFaction+amt); } else if(CMath.isInteger(range)) themob.tell(L("Your faction with @x1 is now @x2.",F.name(),""+CMath.s_int(range.trim()))); if(CMath.isInteger(range)) themob.addFaction(F.factionID(),CMath.s_int(range.trim())); else { Faction.FRange FR=null; final Enumeration<Faction.FRange> e=CMLib.factions().getRanges(CMLib.factions().getAlignmentID()); if(e!=null) for(;e.hasMoreElements();) { final Faction.FRange FR2=e.nextElement(); if(FR2.name().equalsIgnoreCase(range)) { FR = FR2; break; } } if(FR==null) logError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+"."); else { themob.tell(L("Your faction with @x1 is now @x2.",F.name(),FR.name())); themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2)); } } } break; } case 49: // mptitle { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String titleStr=varify(monster, newTarget, scripted, monster, secondaryItem, secondaryItem, msg, tmp, tt[2]); if((newTarget!=null)&&(titleStr.length()>0)&&(newTarget instanceof MOB)) { final MOB themob=(MOB)newTarget; final boolean tattooMinus=titleStr.startsWith("-"); if(tattooMinus) titleStr=titleStr.substring(1); if(themob.playerStats()!=null) { if(themob.playerStats().getTitles().contains(titleStr)) { if(tattooMinus) themob.playerStats().getTitles().remove(titleStr); } else if(!tattooMinus) themob.playerStats().getTitles().add(0,titleStr); } } break; } case 10: // mpkill { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null) &&(newTarget instanceof MOB) &&(monster!=null)) monster.setVictim((MOB)newTarget); break; } case 51: // mpsetclandata { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((newTarget!=null)&&(newTarget instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)newTarget); if(C==null) C=((MOB)newTarget).clans().iterator().hasNext()?((MOB)newTarget).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); } else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String clanvar=tt[2]; final String clanval=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final Clan C=CMLib.clans().getClan(clanID); if(C!=null) { if(!C.isStat(clanvar)) logError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable."); else { C.setStat(clanvar,clanval.trim()); if(C.getStat(clanvar).equalsIgnoreCase(clanval)) C.update(); } } break; } case 52: // mpplayerclass { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) { final Vector<String> V=CMParms.parse(tt[2]); for(int i=0;i<V.size();i++) { if(CMath.isInteger(V.elementAt(i).trim())) ((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(V.elementAt(i).trim())); else { final CharClass C=CMClass.findCharClass(V.elementAt(i)); if((C!=null)&&(C.availabilityCode()!=0)) ((MOB)newTarget).baseCharStats().setCurrentClass(C); } } ((MOB)newTarget).recoverCharStats(); } break; } case 12: // mppurge { if(lastKnownLocation!=null) { int flag=0; if(tt==null) { final String s2=CMParms.getCleanBit(s,1).toLowerCase(); if(s2.equals("room")) tt=parseBits(script,si,"Ccr"); else if(s2.equals("my")) tt=parseBits(script,si,"Ccr"); else tt=parseBits(script,si,"Cr"); if(tt==null) return null; } String s2=tt[1]; if(s2.equalsIgnoreCase("room")) { flag=1; s2=tt[2]; } else if(s2.equalsIgnoreCase("my")) { flag=2; s2=tt[2]; } Environmental E=null; if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me")) E=scripted; else if(flag==1) { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2); E=lastKnownLocation.fetchFromRoomFavorItems(null,s2); } else if(flag==2) { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2); if(monster!=null) E=monster.findItem(s2); } else E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(!((MOB)E).isMonster()) { if(((MOB)E).getStartRoom()!=null) ((MOB)E).getStartRoom().bringMobHere((MOB)E,false); ((MOB)E).session().stopSession(false,false,false); } else if(((MOB)E).getStartRoom()!=null) ((MOB)E).killMeDead(false); else ((MOB)E).destroy(); } else if(E instanceof Item) { final ItemPossessor oE=((Item)E).owner(); ((Item)E).destroy(); if(oE!=null) oE.recoverPhyStats(); } } lastKnownLocation.recoverRoomStats(); } break; } case 14: // mpgoto { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String roomID=tt[1].trim(); if((roomID.length()>0)&&(lastKnownLocation!=null)) { Room goHere=null; if(roomID.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(roomID,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomID),lastKnownLocation); if(goHere!=null) { if(scripted instanceof MOB) goHere.bringMobHere((MOB)scripted,true); else if(scripted instanceof Item) goHere.moveItemTo((Item)scripted,ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers); else { goHere.bringMobHere(monster,true); if(!(scripted instanceof MOB)) goHere.delInhabitant(monster); } if(CMLib.map().roomLocation(scripted)==goHere) lastKnownLocation=goHere; } } break; } case 15: // mpat if(lastKnownLocation!=null) { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final Room lastPlace=lastKnownLocation; final String roomName=tt[1]; if(roomName.length()>0) { final String doWhat=tt[2].trim(); Room goHere=null; if(roomName.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(goHere!=null) { goHere.bringMobHere(monster,true); final DVector subScript=new DVector(3); subScript.addElement("",null,null); subScript.addElement(doWhat,null,null); lastKnownLocation=goHere; execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); lastKnownLocation=lastPlace; lastPlace.bringMobHere(monster,true); if(!(scripted instanceof MOB)) { goHere.delInhabitant(monster); lastPlace.delInhabitant(monster); } } } } break; case 17: // mptransfer { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String mobName=tt[1]; String roomName=tt[2].trim(); Room newRoom=null; if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if((roomName.length()==0)&&(lastKnownLocation!=null)) roomName=lastKnownLocation.roomID(); if(roomName.length()>0) { if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(newRoom!=null) { final ArrayList<Environmental> V=new ArrayList<Environmental>(); if(mobName.startsWith("$")) { final Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) V.add(E); } if(V.size()==0) { mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName); if(mobName.equalsIgnoreCase("all")) { if(lastKnownLocation!=null) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { final MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!V.contains(m))) V.add(m); } } } else { MOB findOne=null; Area A=null; if(findOne==null) { if(lastKnownLocation!=null) { findOne=lastKnownLocation.fetchInhabitant(mobName); A=lastKnownLocation.getArea(); if((findOne!=null)&&(findOne!=monster)) V.add(findOne); } } if(findOne==null) { findOne=CMLib.players().getPlayerAllHosts(mobName); if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true))) findOne=null; if((findOne!=null)&&(findOne!=monster)) V.add(findOne); } if((findOne==null)&&(A!=null)) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); findOne=R.fetchInhabitant(mobName); if((findOne!=null)&&(findOne!=monster)) V.add(findOne); } } } } for(int v=0;v<V.size();v++) { if(V.get(v) instanceof MOB) { final MOB mob=(MOB)V.get(v); final Set<MOB> H=mob.getGroupMembers(new HashSet<MOB>()); for (final Object element : H) { final MOB M=(MOB)element; if((!V.contains(M))&&(M.location()==mob.location())) V.add(M); } } } for(int v=0;v<V.size();v++) { if(V.get(v) instanceof MOB) { final MOB follower=(MOB)V.get(v); final Room thisRoom=follower.location(); final int dispmask=(PhyStats.IS_SLEEPING | PhyStats.IS_SITTING); final int dispo1 = follower.basePhyStats().disposition() & dispmask; final int dispo2 = follower.phyStats().disposition() & dispmask; follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() & (~dispmask)); follower.phyStats().setDisposition(follower.phyStats().disposition() & (~dispmask)); // scripting guide calls for NO text -- empty is probably req tho final CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER|CMMsg.MASK_ALWAYS,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMLib.protocol().msp("appear.wav",10)); final CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE|CMMsg.MASK_ALWAYS," "); if((thisRoom!=null) &&thisRoom.okMessage(follower,leaveMsg) &&newRoom.okMessage(follower,enterMsg)) { final boolean alreadyHere = follower.location()==(Room)enterMsg.target(); if(follower.isInCombat()) { CMLib.commands().postFlee(follower,("NOWHERE")); follower.makePeace(true); } thisRoom.send(follower,leaveMsg); if(!alreadyHere) ((Room)enterMsg.target()).bringMobHere(follower,false); ((Room)enterMsg.target()).send(follower,enterMsg); follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1); follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2); if(!CMLib.flags().isSleeping(follower) &&(!alreadyHere)) { follower.tell(CMLib.lang().L("\n\r\n\r")); CMLib.commands().postLook(follower,true); } } else { follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1); follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2); } } else if((V.get(v) instanceof Item) &&(newRoom!=CMLib.map().roomLocation(V.get(v)))) newRoom.moveItemTo((Item)V.get(v),ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers); if((V.get(v)==scripted) &&(scripted instanceof Physical) &&(newRoom.isHere(scripted))) lastKnownLocation=newRoom; } } } break; } case 25: // mpbeacon { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String roomName=tt[1]; Room newRoom=null; if((roomName.length()>0)&&(lastKnownLocation!=null)) { final String beacon=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(newRoom == null) logError(scripted,"MPBEACON","RunTime",tt[1]+" is not a room."); else if(lastKnownLocation!=null) { final List<MOB> V=new ArrayList<MOB>(); if(beacon.equalsIgnoreCase("all")) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { final MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m))) V.add(m); } } else { final MOB findOne=lastKnownLocation.fetchInhabitant(beacon); if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster())) V.add(findOne); } for(int v=0;v<V.size();v++) { final MOB follower=V.get(v); if(!follower.isMonster()) follower.setStartRoom(newRoom); } } } break; } case 18: // mpforce { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String force=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget!=null) { final DVector vscript=new DVector(3); vscript.addElement("FUNCTION_PROG MPFORCE_"+System.currentTimeMillis()+Math.random(),null,null); vscript.addElement(force,null,null); // this can not be permanently parsed because it is variable execute(newTarget, source, target, getMakeMOB(newTarget), primaryItem, secondaryItem, vscript, msg, tmp); } break; } case 79: // mppossess { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final PhysicalAgent newSource=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final PhysicalAgent newTarget=getArgumentMOB(tt[2],source,monster,target,primaryItem,secondaryItem,msg,tmp); if((!(newSource instanceof MOB))||(((MOB)newSource).isMonster())) logError(scripted,"MPPOSSESS","RunTime",tt[1]+" is not a player."); else if((!(newTarget instanceof MOB))||(!((MOB)newTarget).isMonster())||CMSecurity.isASysOp((MOB)newTarget)) logError(scripted,"MPPOSSESS","RunTime",tt[2]+" is not a mob."); else { final MOB mobM=(MOB)newSource; final MOB targetM=(MOB)newTarget; final Session S=mobM.session(); S.setMob(targetM); targetM.setSession(S); targetM.setSoulMate(mobM); mobM.setSession(null); } break; } case 20: // mpsetvar { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } String which=tt[1]; final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(!which.equals("*")) { if(E==null) which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which); else if(E instanceof Room) which=CMLib.map().getExtendedRoomID((Room)E); else which=E.Name(); } if((which.length()>0)&&(arg2.length()>0)) { if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+arg2+")="+arg3+"<"); setVar(which,arg2,arg3); } break; } case 36: // mpsavevar { if(tt==null) { tt=parseBits(script,si,"CcR"); if(tt==null) return null; } String which=tt[1]; String arg2=tt[2]; final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if((which.length()>0)&&(arg2.length()>0)) { final PairList<String,String> vars=getScriptVarSet(which,arg2); for(int v=0;v<vars.size();v++) { which=vars.elementAtFirst(v); arg2=vars.elementAtSecond(v).toUpperCase(); @SuppressWarnings("unchecked") final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+which); String val=""; if(H!=null) { val=H.get(arg2); if(val==null) val=""; } if(val.length()>0) CMLib.database().DBReCreatePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val); else CMLib.database().DBDeletePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); } } break; } case 39: // mploadvar { if(tt==null) { tt=parseBits(script,si,"CcR"); if(tt==null) return null; } String which=tt[1]; final String arg2=tt[2]; final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()>0) { List<PlayerData> V=null; which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(arg2.equals("*")) V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS"); else V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); if((V!=null)&&(V.size()>0)) for(int v=0;v<V.size();v++) { final DatabaseEngine.PlayerData VAR=V.get(v); String varName=VAR.key(); if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_")) varName=varName.substring((which+"_SCRIPTABLEVARS_").length()); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+varName+")="+VAR.xml()+"<"); setVar(which,varName,VAR.xml()); } } break; } case 40: // MPM2I2M { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String arg1=tt[1]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { final String arg2=tt[2]; final String arg3=tt[3]; final CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged"); if(caged!=null) { ((Item)caged).basePhyStats().setAbility(1); ((Item)caged).recoverPhyStats(); } if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null)) { if(arg2.length()>0) ((Item)caged).setName(arg2); if(arg3.length()>0) ((Item)caged).setDisplayText(arg3); lastKnownLocation.addItem(caged,ItemPossessor.Expire.Player_Drop); ((MOB)E).killMeDead(false); } } else if(E instanceof CagedAnimal) { final MOB M=((CagedAnimal)E).unCageMe(); if((M!=null)&&(lastKnownLocation!=null)) { M.bringToLife(lastKnownLocation,true); ((Item)E).destroy(); } } else logError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item."); break; } case 28: // mpdamage { if(tt==null) { tt=parseBits(script,si,"Ccccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); if((newTarget!=null)&&(arg2.length()>0)) { if(newTarget instanceof MOB) { final MOB deadM=(MOB)newTarget; MOB killerM=(MOB)newTarget; if(arg4.equalsIgnoreCase("MEKILL")||arg4.equalsIgnoreCase("ME")) killerM=monster; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); if((dmg>=deadM.curState().getHitPoints()) &&(!arg4.equalsIgnoreCase("KILL")) &&(!arg4.equalsIgnoreCase("MEKILL"))) dmg=deadM.curState().getHitPoints()-1; if(dmg>0) CMLib.combat().postDamage(killerM,deadM,null,dmg,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,-1,null); } } else if(newTarget instanceof Item) { final Item E=(Item)newTarget; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); boolean destroy=false; if(E.subjectToWearAndTear()) { if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill"))) dmg=E.usesRemaining()-1; if(dmg>0) E.setUsesRemaining(E.usesRemaining()-dmg); if(E.usesRemaining()<=0) destroy=true; } else if(arg4.equalsIgnoreCase("kill")) destroy=true; if(destroy) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 is destroyed!",E.name())); E.destroy(); } } } } break; } case 78: // mpheal { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if((newTarget!=null)&&(arg2.length()>0)) { if(newTarget instanceof MOB) { final MOB healedM=(MOB)newTarget; final MOB healerM=(MOB)newTarget; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min); if(amt>0) CMLib.combat().postHealing(healerM,healedM,null,amt,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null); } } else if(newTarget instanceof Item) { final Item E=(Item)newTarget; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min); if(E.subjectToWearAndTear()) { E.setUsesRemaining(E.usesRemaining()+amt); if(E.usesRemaining()>100) E.setUsesRemaining(100); } } } } break; } case 90: // mplink { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final int dir=CMLib.directions().getGoodDirectionCode(dirWord); if(dir < 0) logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction."); else { final String roomID = varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final Room startR=(homeKnownLocation!=null)?homeKnownLocation:CMLib.map().getStartRoom(scripted); final Room R=this.getRoom(roomID, lastKnownLocation); if((R==null)||(lastKnownLocation==null)||(R.getArea()!=lastKnownLocation.getArea())) logError(scripted,"MPLINK","RunTime",roomID+" is not a target room."); else if((startR!=null)&&(startR.getArea()!=lastKnownLocation.getArea())) logError(scripted,"MPLINK","RunTime","mplink from "+roomID+" is an illegal source room."); else { String exitID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); String nameArg=null; final int x=exitID.indexOf(' '); if(x>0) { nameArg=exitID.substring(x+1).trim(); exitID=exitID.substring(0,x); } final Exit E=CMClass.getExit(exitID); if(E==null) logError(scripted,"MPLINK","RunTime",exitID+" is not a exit class."); else if((lastKnownLocation.rawDoors()[dir]==null) &&(lastKnownLocation.getRawExit(dir)==null)) { lastKnownLocation.rawDoors()[dir]=R; lastKnownLocation.setRawExit(dir, E); E.basePhyStats().setSensesMask(E.basePhyStats().sensesMask()|PhyStats.SENSE_ITEMNOWISH); E.setSavable(false); E.recoverPhyStats(); if(nameArg!=null) E.setName(nameArg); } } } break; } case 91: // mpunlink { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final int dir=CMLib.directions().getGoodDirectionCode(dirWord); if(dir < 0) logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction."); else if((lastKnownLocation==null) ||((lastKnownLocation.rawDoors()[dir]!=null)&&(lastKnownLocation.rawDoors()[dir].getArea()!=lastKnownLocation.getArea()))) logError(scripted,"MPLINK","RunTime",dirWord+" is a non-in-area direction."); else if((lastKnownLocation.getRawExit(dir)!=null) &&(lastKnownLocation.getRawExit(dir).isSavable() ||(!CMath.bset(lastKnownLocation.getRawExit(dir).basePhyStats().sensesMask(), PhyStats.SENSE_ITEMNOWISH)))) logError(scripted,"MPLINK","RunTime",dirWord+" is not a legal unlinkable exit."); else { lastKnownLocation.setRawExit(dir, null); lastKnownLocation.rawDoors()[dir]=null; } break; } case 29: // mptrackto { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); if(A.text().length()>0 && A.text().equalsIgnoreCase(arg1)) { // already on the move } else { altStatusTickable=A; A.invoke(monster,CMParms.parse(arg1),null,true,0); altStatusTickable=null; } } break; } case 53: // mpwalkto { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { altStatusTickable=A; if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0); altStatusTickable=null; } break; } case 21: //MPENDQUEST { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final PhysicalAgent newTarget; final String q=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(q); if(Q!=null) { CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSTOP); Q.stopQuest(); } else if((tt[1].length()>0) &&(defaultQuestName!=null) &&(defaultQuestName.length()>0) &&((newTarget=getArgumentMOB(tt[1].trim(),source,monster,target,primaryItem,secondaryItem,msg,tmp))!=null)) { for(int i=newTarget.numScripts()-1;i>=0;i--) { final ScriptingEngine S=newTarget.fetchScript(i); if((S!=null) &&(S.defaultQuestName()!=null) &&(S.defaultQuestName().equalsIgnoreCase(defaultQuestName))) { newTarget.delScript(S); S.endQuest(newTarget, (newTarget instanceof MOB)?((MOB)newTarget):monster, defaultQuestName); } } } else if(q.length()>0) { boolean foundOne=false; for(int i=scripted.numScripts()-1;i>=0;i--) { final ScriptingEngine S=scripted.fetchScript(i); if((S!=null) &&(S.defaultQuestName()!=null) &&(S.defaultQuestName().equalsIgnoreCase(q))) { foundOne=true; S.endQuest(scripted, monster, S.defaultQuestName()); scripted.delScript(S); } } if((!foundOne) &&((defaultQuestName==null)||(!defaultQuestName.equalsIgnoreCase(q)))) logError(scripted,"MPENDQUEST","Unknown","Quest: "+s); } break; } case 69: // MPSTEPQUEST { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(qName); if(Q!=null) Q.stepQuest(); else logError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s); break; } case 23: //MPSTARTQUEST { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(qName); if(Q!=null) Q.startQuest(); else logError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s); break; } case 64: //MPLOADQUESTOBJ { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName); break; } final Object O=Q.getDesignatedObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); if(O==null) { logError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+tt[2]+" for Quest: "+questName); break; } final String varArg=tt[3]; if((varArg.length()!=2)||(!varArg.startsWith("$"))) { logError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name()); break; } final char c=varArg.charAt(1); if(Character.isDigit(c)) tmp[CMath.s_int(Character.toString(c))]=O; else switch(c) { case 'N': case 'n': if (O instanceof MOB) source = (MOB) O; break; case 'I': case 'i': if (O instanceof PhysicalAgent) scripted = (PhysicalAgent) O; if (O instanceof MOB) monster = (MOB) O; break; case 'B': case 'b': if (O instanceof Environmental) lastLoaded = (Environmental) O; break; case 'T': case 't': if (O instanceof Environmental) target = (Environmental) O; break; case 'O': case 'o': if (O instanceof Item) primaryItem = (Item) O; break; case 'P': case 'p': if (O instanceof Item) secondaryItem = (Item) O; break; case 'd': case 'D': if (O instanceof Room) lastKnownLocation = (Room) O; break; default: logError(scripted, "MPLOADQUESTOBJ", "Syntax", "Invalid argument var: " + varArg + " for " + scripted.Name()); break; } break; } case 22: //MPQUESTWIN { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(whoName); if(M==null) M=CMLib.players().getPlayerAllHosts(whoName); if(M!=null) whoName=M.Name(); if(whoName.length()>0) { final Quest Q=getQuest(tt[2]); if(Q!=null) { if(M!=null) CMLib.achievements().possiblyBumpAchievement(M, AchievementLibrary.Event.QUESTOR, 1, Q); Q.declareWinner(whoName); CMLib.players().bumpPrideStat(M,AccountStats.PrideStat.QUESTS_COMPLETED, 1); } else logError(scripted,"MPQUESTWIN","Unknown","Quest: "+s); } break; } case 24: // MPCALLFUNC { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } if(script.elementAt(si, 3) != null) { execute(scripted, source, target, monster, primaryItem, secondaryItem, (DVector)script.elementAt(si, 3), varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2].trim()), tmp); } else { final String named=tt[1]; final String parms=tt[2].trim(); boolean found=false; final List<DVector> scripts=getScripts(); for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); final String[] ttrigger=(String[])script2.elementAt(0,2); if(getTriggerCode(trigger,ttrigger)==17) // function_prog { final String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(named)) { found=true; script.setElementAt(si, 3, script2); execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms), tmp); break; } } } if(!found) { for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); if(trigger.equalsIgnoreCase(named)) { found=true; script.setElementAt(si, 3, script2); execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms), tmp); break; } } } if(!found) logError(scripted,"MPCALLFUNC","Unknown","Function: "+named); } break; } case 27: // MPWHILE { if(tt==null) { final ArrayList<String> V=new ArrayList<String>(); V.add("MPWHILE"); String conditionStr=(s.substring(7).trim()); if(!conditionStr.startsWith("(")) { logError(scripted,"MPWHILE","Syntax"," NO Starting (: "+s); break; } conditionStr=conditionStr.substring(1).trim(); int x=-1; int depth=0; for(int i=0;i<conditionStr.length();i++) { if(conditionStr.charAt(i)=='(') depth++; else if((conditionStr.charAt(i)==')')&&((--depth)<0)) { x=i; break; } } if(x<0) { logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s); break; } final String DO=conditionStr.substring(x+1).trim(); conditionStr=conditionStr.substring(0,x); try { final String[] EVAL=parseEval(conditionStr); V.add("("); V.addAll(Arrays.asList(EVAL)); V.add(")"); V.add(DO); tt=CMParms.toStringArray(V); script.setElementAt(si,2,tt); } catch(final Exception e) { logError(scripted,"MPWHILE","Syntax",e.getMessage()); break; } if(tt==null) return null; } int evalEnd=2; int depth=0; while((evalEnd<tt.length)&&((!tt[evalEnd].equals(")"))||(depth>0))) { if(tt[evalEnd].equals("(")) depth++; else if(tt[evalEnd].equals(")")) depth--; evalEnd++; } if(evalEnd==tt.length) { logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s); break; } final String[] EVAL=new String[evalEnd-2]; for(int y=2;y<evalEnd;y++) EVAL[y-2]=tt[y]; String DO=tt[evalEnd+1]; String[] DOT=null; final int doLen=(tt.length-evalEnd)-1; if(doLen>1) { DOT=new String[doLen]; for(int y=0;y<DOT.length;y++) { DOT[y]=tt[evalEnd+y+1]; if(y>0) DO+=" "+tt[evalEnd+y+1]; } } final String[][] EVALO={EVAL}; final DVector vscript=new DVector(3); vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random(),null,null); vscript.addElement(DO,DOT,null); final long time=System.currentTimeMillis(); while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVALO,0)) &&((System.currentTimeMillis()-time)<4000) &&(!scripted.amDestroyed())) execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp); if(vscript.elementAt(1,2)!=DOT) { final int oldDotLen=(DOT==null)?1:DOT.length; final String[] newDOT=(String[])vscript.elementAt(1,2); final String[] newTT=new String[tt.length-oldDotLen+newDOT.length]; int end=0; for(end=0;end<tt.length-oldDotLen;end++) newTT[end]=tt[end]; for(int y=0;y<newDOT.length;y++) newTT[end+y]=newDOT[y]; tt=newTT; script.setElementAt(si,2,tt); } if(EVALO[0]!=EVAL) { final Vector<String> lazyV=new Vector<String>(); lazyV.addElement("MPWHILE"); lazyV.addElement("("); final String[] newEVAL=EVALO[0]; for (final String element : newEVAL) lazyV.addElement(element); for(int i=evalEnd;i<tt.length;i++) lazyV.addElement(tt[i]); tt=CMParms.toStringArray(lazyV); script.setElementAt(si,2,tt); } if((System.currentTimeMillis()-time)>=4000) { logError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+s); break; } break; } case 26: // MPALARM { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String parms=tt[2].trim(); if(CMath.s_int(time.trim())<=0) { logError(scripted,"MPALARM","Syntax","Bad time "+time); break; } if(parms.length()==0) { logError(scripted,"MPALARM","Syntax","No command!"); break; } final DVector vscript=new DVector(3); vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random(),null,null); vscript.addElement(parms,null,null); prequeResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg); break; } case 37: // mpenable { if(tt==null) { tt=parseBits(script,si,"Ccccp"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); Ability A=null; if(cast!=null) { if(newTarget instanceof MOB) A=((MOB)newTarget).fetchAbility(cast); if(A==null) A=CMClass.getAbility(cast); if(A==null) { final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if(D==null) logError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast); else if((newTarget!=null)&&(newTarget instanceof MOB)) ((MOB)newTarget).addExpertise(D.ID()); } } if((newTarget!=null) &&(A!=null) &&(newTarget instanceof MOB)) { if(!((MOB)newTarget).isMonster()) Log.sysOut("Scripting",newTarget.Name()+" was MPENABLED with "+A.Name()); if(p2.trim().startsWith("++")) p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency()); else if(p2.trim().startsWith("--")) p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2))); A.setProficiency(CMath.s_int(p2.trim())); A.setMiscText(m2); if(((MOB)newTarget).fetchAbility(A.ID())==null) { ((MOB)newTarget).addAbility(A); A.autoInvocation((MOB)newTarget, false); } } break; } case 38: // mpdisable { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if((newTarget!=null)&&(newTarget instanceof MOB)) { final Ability A=((MOB)newTarget).findAbility(cast); if(A!=null) ((MOB)newTarget).delAbility(A); if((!((MOB)newTarget).isMonster())&&(A!=null)) Log.sysOut("Scripting",newTarget.Name()+" was MPDISABLED with "+A.Name()); final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if((newTarget instanceof MOB)&&(D!=null)) ((MOB)newTarget).delExpertise(D.ID()); } break; } case Integer.MIN_VALUE: logError(scripted,cmd.toUpperCase(),"Syntax","Unexpected prog start -- missing '~'?"); break; default: if(cmd.length()>0) { final Vector<String> V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); if((V.size()>0) &&(monster!=null)) monster.doCommand(V,MUDCmdProcessor.METAFLAG_MPFORCED); } break; } } tickStatus=Tickable.STATUS_END; return null; } protected static final Vector<DVector> empty=new ReadOnlyVector<DVector>(); @Override public String getScriptResourceKey() { return scriptKey; } public void bumpUpCache(final String key) { if((key != null) && (key.length()>0) && (!key.equals("*"))) { synchronized(counterCache) { if(!counterCache.containsKey(key)) counterCache.put(key, new AtomicInteger(0)); counterCache.get(key).addAndGet(1); } } } public void bumpUpCache() { synchronized(this) { final Object ref=cachedRef; if((ref != this) &&(this.scriptKey!=null) &&(this.scriptKey.length()>0)) { bumpUpCache(getScriptResourceKey()); bumpUpCache(scope); bumpUpCache(defaultQuestName); cachedRef=this; } } } public boolean bumpDownCache(final String key) { if((key != null) && (key.length()>0) && (!key.equals("*"))) { if((key != null) &&(key.length()>0) &&(!key.equals("*"))) { synchronized(counterCache) { if(counterCache.containsKey(key)) { if(counterCache.get(key).addAndGet(-1) <= 0) { counterCache.remove(key); return true; } } } } } return false; } protected void bumpDownCache() { synchronized(this) { final Object ref=cachedRef; if(ref == this) { if(bumpDownCache(getScriptResourceKey())) { for(final Resources R : Resources.all()) R._removeResource(getScriptResourceKey()); } if(bumpDownCache(scope)) { for(final Resources R : Resources.all()) R._removeResource("VARSCOPE-"+scope.toUpperCase().trim()); } if(bumpDownCache(defaultQuestName)) { for(final Resources R : Resources.all()) R._removeResource("VARSCOPE-"+defaultQuestName.toUpperCase().trim()); } } } } @Override protected void finalize() throws Throwable { bumpDownCache(); super.finalize(); } protected List<DVector> getScripts() { if(CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLE)||CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTING)) return empty; @SuppressWarnings("unchecked") List<DVector> scripts=(List<DVector>)Resources.getResource(getScriptResourceKey()); if(scripts==null) { String scr=getScript(); scr=CMStrings.replaceAll(scr,"`","'"); scripts=parseScripts(scr); Resources.submitResource(getScriptResourceKey(),scripts); } return scripts; } protected boolean match(final String str, final String patt) { if(patt.trim().equalsIgnoreCase("ALL")) return true; if(patt.length()==0) return true; if(str.length()==0) return false; if(str.equalsIgnoreCase(patt)) return true; return false; } private Item makeCheapItem(final Environmental E) { Item product=null; if(E instanceof Item) product=(Item)E; else { product=CMClass.getItem("StdItem"); product.setName(E.Name()); product.setDisplayText(E.displayText()); product.setDescription(E.description()); if(E instanceof Physical) product.setBasePhyStats((PhyStats)((Physical)E).basePhyStats().copyOf()); product.recoverPhyStats(); } return product; } @Override public boolean okMessage(final Environmental host, final CMMsg msg) { if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get()>2)) return true; try { // atomic recurse counter recurseCounter.addAndGet(1); final PhysicalAgent affecting = (PhysicalAgent)host; final List<DVector> scripts=getScripts(); DVector script=null; boolean tryIt=false; String trigger=null; String[] t=null; int triggerCode=0; String str=null; for(int v=0;v<scripts.size();v++) { tryIt=false; script=scripts.get(v); if(script.size()<1) continue; trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); t=(String[])script.elementAt(0,2); triggerCode=getTriggerCode(trigger,t); switch(triggerCode) { case 42: // cnclmsg_prog if(canTrigger(42)) { if(t==null) t=parseBits(script,0,"CCT"); if(t!=null) { final String command=t[1]; boolean chk=false; final int x=command.indexOf('='); if(x>0) { chk=true; boolean minorOnly = false; boolean majorOnly = false; for(int i=0;i<x;i++) { switch(command.charAt(i)) { case 'S': if(majorOnly) chk=chk&&msg.isSourceMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isSourceMinor(command.substring(x+1)); else chk=chk&&msg.isSource(command.substring(x+1)); break; case 'T': if(majorOnly) chk=chk&&msg.isTargetMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isTargetMinor(command.substring(x+1)); else chk=chk&&msg.isTarget(command.substring(x+1)); break; case 'O': if(majorOnly) chk=chk&&msg.isOthersMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isOthersMinor(command.substring(x+1)); else chk=chk&&msg.isOthers(command.substring(x+1)); break; case '<': minorOnly=true; majorOnly=false; break; case '>': majorOnly=true; minorOnly=false; break; case '?': majorOnly=false; minorOnly=false; break; default: chk=false; break; } } } else if(command.startsWith(">")) { final String cmd=command.substring(1); chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd); } else if(command.startsWith("<")) { final String cmd=command.substring(1); chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd); } else if(command.startsWith("?")) { final String cmd=command.substring(1); chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd); } else chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command); if(chk) { str=""; if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" "; if((t[2].length()==0)||(t[2].equals("ALL"))) tryIt=true; else if((t[2].equals("P"))&&(t.length>3)) { if(match(str.trim(),t[3])) tryIt=true; } else for(int i=2;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=(t[i].trim()+" "+str.trim()).trim(); tryIt=true; break; } } } } } break; } if(tryIt) { final MOB monster=getMakeMOB(affecting); if(lastKnownLocation==null) { lastKnownLocation=msg.source().location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return true; final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; String resp=null; if(msg.target() instanceof MOB) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs()); else if(msg.target() instanceof Item) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs()); else resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs()); if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL"))) return false; } } } finally { recurseCounter.addAndGet(-1); } return true; } protected String standardTriggerCheck(final DVector script, String[] t, final Environmental E, final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final Object[] tmp) { if(E==null) return null; final boolean[] dollarChecks; if(t==null) { t=parseBits(script,0,"CT"); dollarChecks=new boolean[t.length]; for(int i=1;i<t.length;i++) dollarChecks[i] = t[i].indexOf('$')>=0; script.setElementAt(0, 3, dollarChecks); } else dollarChecks=(boolean[])script.elementAt(0, 3); final String NAME=E.Name().toUpperCase(); final String ID=E.ID().toUpperCase(); if((t[1].length()==0) ||(t[1].equals("ALL")) ||(t[1].equals("P") &&(t.length==3) &&((t[2].equalsIgnoreCase(NAME)) ||(t[2].equalsIgnoreCase("ALL"))))) return t[1]; for(int i=1;i<t.length;i++) { final String word; if (dollarChecks[i]) word=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i]); else word=t[i]; if(word.equals("P") && (i < t.length-1)) { final String arg; if (dollarChecks[i+1]) arg=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i+1]); else arg=t[i+1]; if( arg.equalsIgnoreCase(NAME) || arg.equalsIgnoreCase(ID) || arg.equalsIgnoreCase("ALL")) return word; i++; } else if(((" "+NAME+" ").indexOf(" "+word+" ")>=0) ||(ID.equalsIgnoreCase(word)) ||(word.equalsIgnoreCase("ALL"))) return word; } return null; } @Override public void executeMsg(final Environmental host, final CMMsg msg) { if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get() > 2)) return; try { // atomic recurse counter recurseCounter.addAndGet(1); final PhysicalAgent affecting = (PhysicalAgent)host; final MOB monster=getMakeMOB(affecting); if(lastKnownLocation==null) { lastKnownLocation=msg.source().location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return; final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; MOB eventMob=monster; if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB)) eventMob=(MOB)defaultItem.owner(); final List<DVector> scripts=getScripts(); if(msg.amITarget(eventMob) &&(!msg.amISource(monster)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.source()!=monster)) lastToHurtMe=msg.source(); DVector script=null; String trigger=null; String[] t=null; for(int v=0;v<scripts.size();v++) { script=scripts.get(v); if(script.size()<1) continue; trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); t=(String[])script.elementAt(0,2); final int triggerCode=getTriggerCode(trigger,t); int targetMinorTrigger=-1; switch(triggerCode) { case 1: // greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&canTrigger(1) &&((!(affecting instanceof MOB))||CMLib.flags().canSenseEnteringLeaving(msg.source(),(MOB)affecting))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 45: // arrive_prog if(((msg.targetMinor()==CMMsg.TYP_ENTER)||(msg.sourceMinor()==CMMsg.TYP_LIFE)) &&(msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&canTrigger(45)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { if((host instanceof Item) &&(((Item)host).owner() instanceof MOB) &&(msg.source()==((Item)host).owner())) { // this is to prevent excessive queing when a player is running full throttle with a scripted item // that pays attention to where it is. for(int i=que.size()-1;i>=0;i--) { try { if(que.get(i).scr == script) que.remove(i); } catch(final Exception e) { } } } enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 2: // all_greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&((!(affecting instanceof MOB)) ||CMLib.flags().canActAtAll(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 47: // speak_prog if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(47) &&(msg.amISource(monster)||(!(affecting instanceof MOB))) &&(!msg.othersMajor(CMMsg.MASK_CHANNEL)) &&((msg.sourceMessage()!=null) ||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null))) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) { t=parseBits(script,0,"CT"); for(int i=0;i<t.length;i++) { if(t[i]!=null) t[i]=t[i].replace('`', '\''); } } String str=null; if(msg.sourceMessage() != null) str=CMStrings.getSayFromMessage(msg.sourceMessage().toUpperCase()); else if(msg.targetMessage() != null) str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()); else if(msg.othersMessage() != null) str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()); if(str != null) { str=(" "+str.replace('`', '\'')+" ").toUpperCase(); str=CMStrings.removeColors(str); str=CMStrings.replaceAll(str,"\n\r"," "); if((t[1].length()==0)||(t[1].equals("ALL"))) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } else if((t[1].equals("P"))&&(t.length>2)) { if(match(str.trim(),t[2])) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } } else for(int i=1;i<t.length;i++) { final int x=str.indexOf(" "+t[i]+" "); if(x>=0) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t); return; } } } } break; case 3: // speech_prog if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3) &&(!msg.amISource(monster)) &&(!msg.othersMajor(CMMsg.MASK_CHANNEL)) &&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE))) ||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null))) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) { t=parseBits(script,0,"CT"); for(int i=0;i<t.length;i++) { if(t[i]!=null) t[i]=t[i].replace('`', '\''); } } String str=null; if(msg.othersMessage() != null) str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()); else if(msg.targetMessage() != null) str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()); if(str != null) { str=(" "+str.replace('`', '\'')+" ").toUpperCase(); str=CMStrings.removeColors(str); str=CMStrings.replaceAll(str,"\n\r"," "); if((t[1].length()==0)||(t[1].equals("ALL"))) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } else if((t[1].equals("P"))&&(t.length>2)) { if(match(str.trim(),t[2])) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } } else for(int i=1;i<t.length;i++) { final int x=str.indexOf(" "+t[i]+" "); if(x>=0) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t); return; } } } } break; case 4: // give_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&canTrigger(4) &&((msg.amITarget(monster)) ||(msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(msg.tool() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,check, t); return; } } break; case 48: // giving_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&canTrigger(48) &&((msg.amISource(monster)) ||(msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(msg.tool() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,script,1,check, t); return; } } break; case 49: // cast_prog if((msg.tool() instanceof Ability) &&canTrigger(49) &&((msg.amITarget(monster)) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(msg.sourceMinor()!=CMMsg.TYP_TEACH) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,defaultItem,null,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,check, t); return; } } break; case 50: // casting_prog if((msg.tool() instanceof Ability) &&canTrigger(50) &&((msg.amISource(monster)) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(msg.sourceMinor()!=CMMsg.TYP_TEACH) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,null,defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t); return; } } break; case 40: // llook_prog if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,null,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t); return; } } break; case 41: // execmsg_prog if(canTrigger(41)) { if(t==null) t=parseBits(script,0,"CCT"); if(t!=null) { final String command=t[1]; boolean chk=false; final int x=command.indexOf('='); if(x>0) { chk=true; boolean minorOnly = false; boolean majorOnly = false; for(int i=0;i<x;i++) { switch(command.charAt(i)) { case 'S': if(majorOnly) chk=chk&&msg.isSourceMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isSourceMinor(command.substring(x+1)); else chk=chk&&msg.isSource(command.substring(x+1)); break; case 'T': if(majorOnly) chk=chk&&msg.isTargetMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isTargetMinor(command.substring(x+1)); else chk=chk&&msg.isTarget(command.substring(x+1)); break; case 'O': if(majorOnly) chk=chk&&msg.isOthersMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isOthersMinor(command.substring(x+1)); else chk=chk&&msg.isOthers(command.substring(x+1)); break; case '<': minorOnly=true; majorOnly=false; break; case '>': majorOnly=true; minorOnly=false; break; case '?': majorOnly=false; minorOnly=false; break; default: chk=false; break; } } } else if(command.startsWith(">")) { final String cmd=command.substring(1); chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd); } else if(command.startsWith("<")) { final String cmd=command.substring(1); chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd); } else if(command.startsWith("?")) { final String cmd=command.substring(1); chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd); } else chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command); if(chk) { String str=""; if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" "; boolean doIt=false; if((t[2].length()==0)||(t[2].equals("ALL"))) doIt=true; else if((t[2].equals("P"))&&(t.length>3)) { if(match(str.trim(),t[3])) doIt=true; } else for(int i=2;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=(t[i].trim()+" "+str.trim()).trim(); doIt=true; break; } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } } } break; case 39: // look_prog if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,script,1,check, t); return; } } break; case 20: // get_prog if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20) &&(msg.amITarget(affecting) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { Item checkInE=(Item)msg.target(); if((msg.tool() instanceof Item) &&(((Item)msg.tool()).container()==msg.target())) checkInE=(Item)msg.tool(); final String check=standardTriggerCheck(script,t,checkInE,affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,script,1,check, t); return; } } break; case 22: // drop_prog if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; if(msg.target() instanceof Coins) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 24: // remove_prog if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 34: // open_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_OPEN; //$FALL-THROUGH$ case 35: // close_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_CLOSE; //$FALL-THROUGH$ case 36: // lock_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_LOCK; //$FALL-THROUGH$ case 37: // unlock_prog { if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_UNLOCK; if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem; final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,I,defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,check, t); return; } } break; } case 25: // consume_prog if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(25) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t); if(check!=null) { if((msg.target() == affecting) &&(affecting instanceof Food)) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 21: // put_prog if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(msg.tool() instanceof Item) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t); return; } } break; case 46: // putting_prog if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(46) &&((msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(msg.tool() instanceof Item) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t); return; } } break; case 27: // buy_prog if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27) &&((!(affecting instanceof ShopKeeper)) ||msg.amITarget(affecting)) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null; final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t); if(check!=null) { final Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t); return; } } break; case 28: // sell_prog if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28) &&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper))) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null; final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t); if(check!=null) { final Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,newObjs()); else enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t); return; } } break; case 23: // wear_prog if(((msg.targetMinor()==CMMsg.TYP_WEAR) ||(msg.targetMinor()==CMMsg.TYP_HOLD) ||(msg.targetMinor()==CMMsg.TYP_WIELD)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(23) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 19: // bribe_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&(msg.amITarget(eventMob)||(!(affecting instanceof MOB))) &&(!msg.amISource(monster))&&canTrigger(19) &&(msg.tool() instanceof Coins) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { if(t[1].startsWith("ANY")||t[1].startsWith("ALL")) t[1]=t[1].trim(); else if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster))) break; double d=0.0; if(CMath.isDouble(t[1])) d=CMath.s_double(t[1]); else d=CMath.s_int(t[1]); if((((Coins)msg.tool()).getTotalValue()>=d) ||(t[1].equals("ALL")) ||(t[1].equals("ANY"))) { enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null, t); return; } } } break; case 8: // entry_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8) &&(msg.amISource(eventMob) ||(msg.target()==affecting) ||(msg.tool()==affecting) ||(affecting instanceof Item)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que); ScriptableResponse SB=null; String roomID=null; if(msg.target()!=null) roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target())); for(int q=0;q<V.size();q++) { SB=V.get(q); if((SB.scr==script)&&(SB.s==msg.source())) { if(que.remove(SB)) execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs()); break; } } enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t); return; } } } break; case 9: // exit_prog if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que); ScriptableResponse SB=null; String roomID=null; if(msg.target()!=null) roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target())); for(int q=0;q<V.size();q++) { SB=V.get(q); if((SB.scr==script)&&(SB.s==msg.source())) { if(que.remove(SB)) execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs()); break; } } enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t); return; } } } break; case 10: // death_prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10) &&(msg.amISource(eventMob)||(!(affecting instanceof MOB)))) { if(t==null) t=parseBits(script,0,"C"); final MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs()); return; } break; case 44: // kill_prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44) &&((msg.tool()==affecting)||(!(affecting instanceof MOB)))) { if(t==null) t=parseBits(script,0,"C"); final MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs()); return; } break; case 26: // damage_prog if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26) &&(msg.amITarget(eventMob)||(msg.tool()==affecting))) { if(t==null) t=parseBits(script,0,"C"); Item I=null; if(msg.tool() instanceof Item) I=(Item)msg.tool(); execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),newObjs()); return; } break; case 29: // login_prog if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LOGIN))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN); registeredEvents.add(Integer.valueOf(CMMsg.TYP_LOGIN)); } if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&(!CMLib.flags().isCloaked(msg.source()))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 32: // level_prog if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LEVEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL); registeredEvents.add(Integer.valueOf(CMMsg.TYP_LEVEL)); } if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&(msg.value() > msg.source().basePhyStats().level()) &&(!CMLib.flags().isCloaked(msg.source()))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { execute(affecting,msg.source(),monster,monster,defaultItem,null,script,null,t); return; } } } break; case 30: // logoff_prog if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&((!CMLib.flags().isCloaked(msg.source()))||(!CMSecurity.isASysOp(msg.source())))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 12: // mask_prog { if(!canTrigger(12)) break; } //$FALL-THROUGH$ case 18: // act_prog if((msg.amISource(monster)) ||((triggerCode==18)&&(!canTrigger(18)))) break; //$FALL-THROUGH$ case 43: // imask_prog if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43))) { if(t==null) { t=parseBits(script,0,"CT"); for(int i=1;i<t.length;i++) t[i]=CMLib.english().stripPunctuation(CMStrings.removeColors(t[i])); } boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); str=CMLib.english().stripPunctuation(CMStrings.removeColors(str)); str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" "; if((t[1].length()==0)||(t[1].equals("ALL"))) doIt=true; else if((t[1].equals("P"))&&(t.length>2)) { if(match(str.trim(),t[2])) doIt=true; } else for(int i=1;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=t[i]; doIt=true; break; } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } break; case 38: // social_prog if(!msg.amISource(monster) &&canTrigger(38) &&(msg.tool() instanceof Social)) { if(t==null) t=parseBits(script,0,"CR"); if((t!=null) &&((Social)msg.tool()).Name().toUpperCase().startsWith(t[1])) { final Item Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,msg.tool().Name(), t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t); return; } } break; case 33: // channel_prog if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_CHANNEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL); registeredEvents.add(Integer.valueOf(CMMsg.TYP_CHANNEL)); } if(!msg.amISource(monster) &&(msg.othersMajor(CMMsg.MASK_CHANNEL)) &&canTrigger(33)) { if(t==null) t=parseBits(script,0,"CCT"); boolean doIt=false; if(t!=null) { final String channel=t[1]; final int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL; String str=null; final CMChannel officialChannel=CMLib.channels().getChannel(channelInt); if(officialChannel==null) Log.errOut("Script","Unknown channel for code '"+channelInt+"': "+msg.othersMessage()); else if(channel.equalsIgnoreCase(officialChannel.name())) { str=msg.sourceMessage(); if(str==null) str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim(); int dex=str.indexOf("["+channel+"]"); if(dex>0) str=str.substring(dex+2+channel.length()).trim(); else { dex=str.indexOf('\''); final int edex=str.lastIndexOf('\''); if(edex>dex) str=str.substring(dex+1,edex); } str=" "+CMStrings.removeColors(str)+" "; str=CMStrings.replaceAll(str,"\n\r"," "); if((t[2].length()==0)||(t[2].equals("ALL"))) doIt=true; else if(t[2].equals("P")&&(t.length>2)) { if(match(str.trim(),t[3])) doIt=true; } else for(int i=2;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=t[i]; doIt=true; break; } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } } break; case 31: // regmask_prog if(!msg.amISource(monster)&&canTrigger(31)) { boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); if(t==null) t=parseBits(script,0,"Cp"); if(t!=null) { if(CMParms.getCleanBit(t[1],0).equalsIgnoreCase("p")) doIt=str.trim().equals(t[1].substring(1).trim()); else { Pattern P=patterns.get(t[1]); if(P==null) { P=Pattern.compile(t[1], Pattern.CASE_INSENSITIVE | Pattern.DOTALL); patterns.put(t[1],P); } final Matcher M=P.matcher(str); doIt=M.find(); if(doIt) str=str.substring(M.start()).trim(); } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } break; } } } finally { recurseCounter.addAndGet(-1); } } protected int getTriggerCode(final String trigger, final String[] ttrigger) { final Integer I; if((ttrigger!=null)&&(ttrigger.length>0)) I=progH.get(ttrigger[0]); else { final int x=trigger.indexOf(' '); if(x<0) I=progH.get(trigger.toUpperCase().trim()); else I=progH.get(trigger.substring(0,x).toUpperCase().trim()); } if(I==null) return 0; return I.intValue(); } @Override public MOB getMakeMOB(final Tickable ticking) { MOB mob=null; if(ticking instanceof MOB) { mob=(MOB)ticking; if(!mob.amDead()) lastKnownLocation=mob.location(); } else if(ticking instanceof Environmental) { final Room R=CMLib.map().roomLocation((Environmental)ticking); if(R!=null) lastKnownLocation=R; if((backupMOB==null) ||(backupMOB.amDestroyed()) ||(backupMOB.amDead())) { backupMOB=CMClass.getMOB("StdMOB"); if(backupMOB!=null) { backupMOB.setName(ticking.name()); backupMOB.setDisplayText(L("@x1 is here.",ticking.name())); backupMOB.setDescription(""); backupMOB.setAgeMinutes(-1); mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) backupMOB.setLocation(lastKnownLocation); } } else { backupMOB.setAgeMinutes(-1); mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) { backupMOB.setLocation(lastKnownLocation); backupMOB.setName(ticking.name()); backupMOB.setDisplayText(L("@x1 is here.",ticking.name())); } } } return mob; } protected boolean canTrigger(final int triggerCode) { final Long L=noTrigger.get(Integer.valueOf(triggerCode)); if(L==null) return true; if(System.currentTimeMillis()<L.longValue()) return false; noTrigger.remove(Integer.valueOf(triggerCode)); return true; } @Override public boolean tick(final Tickable ticking, final int tickID) { final Item defaultItem=(ticking instanceof Item)?(Item)ticking:null; final MOB mob; synchronized(this) // supposedly this will cause a sync between cpus of the object { mob=getMakeMOB(ticking); } if((mob==null)||(lastKnownLocation==null)) { altStatusTickable=null; return true; } final PhysicalAgent affecting=(ticking instanceof PhysicalAgent)?((PhysicalAgent)ticking):null; final List<DVector> scripts=getScripts(); if(!runInPassiveAreas) { final Area A=CMLib.map().areaLocation(ticking); if((A!=null)&&(A.getAreaState() != Area.State.ACTIVE)) { return true; } } if(defaultItem != null) { final ItemPossessor poss=defaultItem.owner(); if(poss instanceof MOB) { final Room R=((MOB)poss).location(); if((R==null)||(R.numInhabitants()==0)) { altStatusTickable=null; return true; } } } int triggerCode=-1; String trigger=""; String[] t=null; for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++) { final DVector script=scripts.get(thisScriptIndex); if(script.size()<2) continue; trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); t=(String[])script.elementAt(0,2); triggerCode=getTriggerCode(trigger,t); tickStatus=Tickable.STATUS_SCRIPT+triggerCode; switch(triggerCode) { case 5: // rand_Prog if((!mob.amDead())&&canTrigger(5)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } } break; case 16: // delay_prog if((!mob.amDead())&&canTrigger(16)) { int targetTick=-1; final Integer thisScriptIndexI=Integer.valueOf(thisScriptIndex); final int[] delayProgCounter; synchronized(thisScriptIndexI) { if(delayTargetTimes.containsKey(thisScriptIndexI)) targetTick=delayTargetTimes.get(thisScriptIndexI).intValue(); else { if(t==null) t=parseBits(script,0,"CCR"); if(t!=null) { final int low=CMath.s_int(t[1]); int high=CMath.s_int(t[2]); if(high<low) high=low; targetTick=CMLib.dice().roll(1,high-low+1,low-1); delayTargetTimes.put(thisScriptIndexI,Integer.valueOf(targetTick)); } } if(delayProgCounters.containsKey(thisScriptIndexI)) delayProgCounter=delayProgCounters.get(thisScriptIndexI); else { delayProgCounter=new int[]{0}; delayProgCounters.put(thisScriptIndexI,delayProgCounter); } } boolean exec=false; synchronized(delayProgCounter) { if(delayProgCounter[0]>=targetTick) { exec=true; delayProgCounter[0]=0; } else delayProgCounter[0]++; } if(exec) execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } break; case 7: // fight_Prog if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs()); } } else if((ticking instanceof Item) &&canTrigger(7) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { final MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs()); } } } break; case 11: // hitprcnt_prog if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),mob.maxState().getHitPoints())); if(mob.curState().getHitPoints()<=floor) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs()); } } else if((ticking instanceof Item) &&canTrigger(11) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { final MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),M.maxState().getHitPoints())); if(M.curState().getHitPoints()<=floor) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs()); } } } break; case 6: // once_prog if(!oncesDone.contains(script)&&canTrigger(6)) { if(t==null) t=parseBits(script,0,"C"); oncesDone.add(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } break; case 14: // time_prog if((mob.location()!=null) &&canTrigger(14) &&(!mob.amDead())) { if(t==null) t=parseBits(script,0,"CT"); int lastTimeProgDone=-1; if(lastTimeProgsDone.containsKey(Integer.valueOf(thisScriptIndex))) lastTimeProgDone=lastTimeProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue(); final int time=mob.location().getArea().getTimeObj().getHourOfDay(); if((t!=null)&&(lastTimeProgDone!=time)) { boolean done=false; for(int i=1;i<t.length;i++) { if(time==CMath.s_int(t[i])) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,""+time,newObjs()); lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex)); lastTimeProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(time)); break; } } if(!done) lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex)); } } break; case 15: // day_prog if((mob.location()!=null)&&canTrigger(15) &&(!mob.amDead())) { if(t==null) t=parseBits(script,0,"CT"); int lastDayProgDone=-1; if(lastDayProgsDone.containsKey(Integer.valueOf(thisScriptIndex))) lastDayProgDone=lastDayProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue(); final int day=mob.location().getArea().getTimeObj().getDayOfMonth(); if((t!=null)&&(lastDayProgDone!=day)) { boolean done=false; for(int i=1;i<t.length;i++) { if(day==CMath.s_int(t[i])) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex)); lastDayProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(day)); break; } } if(!done) lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex)); } } break; case 13: // quest_time_prog if(!oncesDone.contains(script)&&canTrigger(13)) { if(t==null) t=parseBits(script,0,"CCC"); if(t!=null) { final Quest Q=getQuest(t[1]); if((Q!=null) &&(Q.running()) &&(!Q.stopping()) &&(Q.duration()!=0)) { final int time=CMath.s_int(t[2]); if(time>=Q.minsRemaining()) { oncesDone.add(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } } } } break; default: break; } } tickStatus=Tickable.STATUS_SCRIPT+100; dequeResponses(); altStatusTickable=null; return true; } @Override public void initializeClass() { } @Override public int compareTo(final CMObject o) { return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o)); } public void enqueResponse(final PhysicalAgent host, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final DVector script, final int ticks, final String msg, final String[] triggerStr) { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return; if(que.size()>25) { this.logError(monster, "UNK", "SYS", "Attempt to enque more than 25 events (last was "+CMParms.toListString(triggerStr)+" )."); que.clear(); } if(noDelay) execute(host,source,target,monster,primaryItem,secondaryItem,script,msg,newObjs()); else que.add(new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg)); } public void prequeResponse(final PhysicalAgent host, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final DVector script, final int ticks, final String msg) { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return; if(que.size()>25) { this.logError(monster, "UNK", "SYS", "Attempt to pre que more than 25 events."); que.clear(); } que.add(0,new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg)); } @Override public void dequeResponses() { try { tickStatus=Tickable.STATUS_SCRIPT+100; for(int q=que.size()-1;q>=0;q--) { ScriptableResponse SB=null; try { SB=que.get(q); } catch(final ArrayIndexOutOfBoundsException x) { continue; } if(SB.checkTimeToExecute()) { execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs()); que.remove(SB); } } } catch (final Exception e) { Log.errOut("DefaultScriptingEngine", e); } } public String L(final String str, final String ... xs) { return CMLib.lang().fullSessionTranslation(str, xs); } protected static class JScriptEvent extends ScriptableObject { @Override public String getClassName() { return "JScriptEvent"; } static final long serialVersionUID = 43; final PhysicalAgent h; final MOB s; final Environmental t; final MOB m; final Item pi; final Item si; final Object[] objs; Vector<String> scr; final String message; final DefaultScriptingEngine c; public Environmental host() { return h; } public MOB source() { return s; } public Environmental target() { return t; } public MOB monster() { return m; } public Item item() { return pi; } public Item item2() { return si; } public String message() { return message; } public void setVar(final String host, final String var, final String value) { c.setVar(host,var.toUpperCase(),value); } public String getVar(final String host, final String var) { return c.getVar(host, var); } public String toJavaString(final Object O) { return Context.toString(O); } public String getCMType(final Object O) { if(O == null) return "null"; final CMObjectType typ = CMClass.getObjectType(O); if(typ == null) return "unknown"; return typ.name().toLowerCase(); } @Override public Object get(final String name, final Scriptable start) { if (super.has(name, start)) return super.get(name, start); if (methH.containsKey(name) || funcH.containsKey(name) || (name.endsWith("$")&&(funcH.containsKey(name.substring(0,name.length()-1))))) { return new Function() { @Override public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if(methH.containsKey(name)) { final StringBuilder strb=new StringBuilder(name); if(args.length==1) strb.append(" ").append(String.valueOf(args[0])); else for(int i=0;i<args.length;i++) { if(i==args.length-1) strb.append(" ").append(String.valueOf(args[i])); else strb.append(" ").append("'"+String.valueOf(args[i])+"'"); } final DVector DV=new DVector(2); DV.addElement("JS_PROG",null); DV.addElement(strb.toString(),null); return c.execute(h,s,t,m,pi,si,DV,message,objs); } if(name.endsWith("$")) { final StringBuilder strb=new StringBuilder(name.substring(0,name.length()-1)).append("("); if(args.length==1) strb.append(" ").append(String.valueOf(args[0])); else for(int i=0;i<args.length;i++) { if(i==args.length-1) strb.append(" ").append(String.valueOf(args[i])); else strb.append(" ").append("'"+String.valueOf(args[i])+"'"); } strb.append(" ) "); return c.functify(h,s,t,m,pi,si,message,objs,strb.toString()); } final String[] sargs=new String[args.length+3]; sargs[0]=name; sargs[1]="("; for(int i=0;i<args.length;i++) sargs[i+2]=String.valueOf(args[i]); sargs[sargs.length-1]=")"; final String[][] EVAL={sargs}; return Boolean.valueOf(c.eval(h,s,t,m,pi,si,message,objs,EVAL,0)); } @Override public void delete(final String arg0) { } @Override public void delete(final int arg0) { } @Override public Object get(final String arg0, final Scriptable arg1) { return null; } @Override public Object get(final int arg0, final Scriptable arg1) { return null; } @Override public String getClassName() { return null; } @Override public Object getDefaultValue(final Class<?> arg0) { return null; } @Override public Object[] getIds() { return null; } @Override public Scriptable getParentScope() { return null; } @Override public Scriptable getPrototype() { return null; } @Override public boolean has(final String arg0, final Scriptable arg1) { return false; } @Override public boolean has(final int arg0, final Scriptable arg1) { return false; } @Override public boolean hasInstance(final Scriptable arg0) { return false; } @Override public void put(final String arg0, final Scriptable arg1, final Object arg2) { } @Override public void put(final int arg0, final Scriptable arg1, final Object arg2) { } @Override public void setParentScope(final Scriptable arg0) { } @Override public void setPrototype(final Scriptable arg0) { } @Override public Scriptable construct(final Context arg0, final Scriptable arg1, final Object[] arg2) { return null; } }; } return super.get(name, start); } public void executeEvent(final DVector script, final int lineNum) { c.execute(h, s, t, m, pi, si, script, message, objs, lineNum); } public JScriptEvent(final DefaultScriptingEngine scrpt, final PhysicalAgent host, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { c=scrpt; h=host; s=source; t=target; m=monster; pi=primaryItem; si=secondaryItem; message=msg; objs=tmp; } } }
com/planet_ink/coffee_mud/Common/DefaultScriptingEngine.java
package com.planet_ink.coffee_mud.Common; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMClass.CMObjectType; 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.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.Common.interfaces.AccountStats.PrideStat; import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback; 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.ChannelsLibrary.CMChannel; import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData; import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag; 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 org.mozilla.javascript.*; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; /* Copyright 2008-2020 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 DefaultScriptingEngine implements ScriptingEngine { @Override public String ID() { return "DefaultScriptingEngine"; } @Override public String name() { return "Default Scripting Engine"; } protected static final Map<String,Integer> funcH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> methH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> progH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> connH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> gstatH = new Hashtable<String,Integer>(); protected static final Map<String,Integer> signH = new Hashtable<String,Integer>(); protected static final Map<String, AtomicInteger> counterCache= new Hashtable<String, AtomicInteger>(); protected static final Map<String, Pattern> patterns = new Hashtable<String, Pattern>(); protected boolean noDelay = CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLEDELAY); protected String scope = ""; protected int tickStatus = Tickable.STATUS_NOT; protected boolean isSavable = true; protected boolean alwaysTriggers = false; protected MOB lastToHurtMe = null; protected Room lastKnownLocation= null; protected Room homeKnownLocation= null; protected Tickable altStatusTickable= null; protected List<DVector> oncesDone = new Vector<DVector>(); protected Map<Integer,Integer> delayTargetTimes = new Hashtable<Integer,Integer>(); protected Map<Integer,int[]> delayProgCounters= new Hashtable<Integer,int[]>(); protected Map<Integer,Integer> lastTimeProgsDone= new Hashtable<Integer,Integer>(); protected Map<Integer,Integer> lastDayProgsDone = new Hashtable<Integer,Integer>(); protected Set<Integer> registeredEvents = new HashSet<Integer>(); protected Map<Integer,Long> noTrigger = new Hashtable<Integer,Long>(); protected MOB backupMOB = null; protected CMMsg lastMsg = null; protected Resources resources = null; protected Environmental lastLoaded = null; protected String myScript = ""; protected String defaultQuestName = ""; protected String scriptKey = null; protected boolean runInPassiveAreas= true; protected boolean debugBadScripts = false; protected List<ScriptableResponse>que = new Vector<ScriptableResponse>(); protected final AtomicInteger recurseCounter = new AtomicInteger(); protected volatile Object cachedRef = null; public DefaultScriptingEngine() { super(); //CMClass.bumpCounter(this,CMClass.CMObjectType.COMMON);//removed for mem & perf debugBadScripts=CMSecurity.isDebugging(CMSecurity.DbgFlag.BADSCRIPTS); resources = Resources.instance(); } @Override public boolean isSavable() { return isSavable; } @Override public void setSavable(final boolean truefalse) { isSavable = truefalse; } @Override public String defaultQuestName() { return defaultQuestName; } protected Quest defaultQuest() { if(defaultQuestName.length()==0) return null; return CMLib.quests().fetchQuest(defaultQuestName); } @Override public void setVarScope(final String newScope) { if((newScope==null)||(newScope.trim().length()==0)||newScope.equalsIgnoreCase("GLOBAL")) { scope=""; resources=Resources.instance(); } else scope=newScope.toUpperCase().trim(); if(scope.equalsIgnoreCase("*")||scope.equals("INDIVIDUAL")) resources = Resources.newResources(); else { resources=(Resources)Resources.getResource("VARSCOPE-"+scope); if(resources==null) { resources = Resources.newResources(); Resources.submitResource("VARSCOPE-"+scope,resources); } if(cachedRef==this) bumpUpCache(scope); } } @Override public String getVarScope() { return scope; } protected Object[] newObjs() { return new Object[ScriptingEngine.SPECIAL_NUM_OBJECTS]; } @Override public String getLocalVarXML() { if((scope==null)||(scope.length()==0)) return ""; final StringBuffer str=new StringBuffer(""); for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { final String key=k.next(); if(key.startsWith("SCRIPTVAR-")) { str.append("<"+key.substring(10)+">"); @SuppressWarnings("unchecked") final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource(key); for(final Enumeration<String> e=H.keys();e.hasMoreElements();) { final String vn=e.nextElement(); final String val=H.get(vn); str.append("<"+vn+">"+CMLib.xml().parseOutAngleBrackets(val)+"</"+vn+">"); } str.append("</"+key.substring(10)+">"); } } return str.toString(); } @Override public void setLocalVarXML(final String xml) { for(final Iterator<String> k = Resources.findResourceKeys("SCRIPTVAR-");k.hasNext();) { final String key=k.next(); if(key.startsWith("SCRIPTVAR-")) resources._removeResource(key); } final List<XMLLibrary.XMLTag> V=CMLib.xml().parseAllXML(xml); for(int v=0;v<V.size();v++) { final XMLTag piece=V.get(v); if((piece.contents()!=null)&&(piece.contents().size()>0)) { final String kkey="SCRIPTVAR-"+piece.tag(); final Hashtable<String,String> H=new Hashtable<String,String>(); for(int c=0;c<piece.contents().size();c++) { final XMLTag piece2=piece.contents().get(c); H.put(piece2.tag(),piece2.value()); } resources._submitResource(kkey,H); } } } private Quest getQuest(final String named) { if((defaultQuestName.length()>0) &&(named.equals("*")||named.equalsIgnoreCase(defaultQuestName))) return defaultQuest(); Quest Q=null; for(int i=0;i<CMLib.quests().numQuests();i++) { try { Q = CMLib.quests().fetchQuest(i); } catch (final Exception e) { } if(Q!=null) { if(Q.name().equalsIgnoreCase(named)) { if(Q.running()) return Q; } } } return CMLib.quests().fetchQuest(named); } @Override public int getTickStatus() { final Tickable T=altStatusTickable; if(T!=null) return T.getTickStatus(); return tickStatus; } @Override public void registerDefaultQuest(final String qName) { if((qName==null)||(qName.trim().length()==0)) defaultQuestName=""; else { defaultQuestName=qName.trim(); if(cachedRef==this) bumpUpCache(defaultQuestName); } } @Override public CMObject newInstance() { try { return this.getClass().newInstance(); } catch(final Exception e) { Log.errOut(ID(),e); } return new DefaultScriptingEngine(); } @Override public CMObject copyOf() { try { final DefaultScriptingEngine S=(DefaultScriptingEngine)this.clone(); //CMClass.bumpCounter(S,CMClass.CMObjectType.COMMON);//removed for mem & perf S.reset(); return S; } catch(final CloneNotSupportedException e) { return new DefaultScriptingEngine(); } } /* protected void finalize() { CMClass.unbumpCounter(this, CMClass.CMObjectType.COMMON); }// removed for mem & perf */ /* * c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger */ protected String[] parseBits(final DVector script, final int row, final String instructions) { final String line=(String)script.elementAt(row,1); final String[] newLine=parseBits(line,instructions); script.setElementAt(row,2,newLine); return newLine; } protected String[] parseSpecial3PartEval(final String[][] eval, final int t) { String[] tt=eval[0]; final String funcParms=tt[t]; final String[] tryTT=parseBits(funcParms,"ccr"); if(signH.containsKey(tryTT[1])) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ else { String[] parsed=null; if(CMParms.cleanBit(funcParms).equals(funcParms)) parsed=parseBits("'"+funcParms+"' . .","cr"); else parsed=parseBits(funcParms+" . .","cr"); tt=insertStringArray(tt,parsed,t); eval[0]=tt; } return tt; } /* * c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger */ protected String[] parseBits(String line, final String instructions) { String[] newLine=new String[instructions.length()]; for(int i=0;i<instructions.length();i++) { switch(instructions.charAt(i)) { case 'c': newLine[i] = CMParms.getCleanBit(line, i); break; case 'C': newLine[i] = CMParms.getCleanBit(line, i).toUpperCase().trim(); break; case 'r': newLine[i] = CMParms.getPastBitClean(line, i - 1); break; case 'R': newLine[i] = CMParms.getPastBitClean(line, i - 1).toUpperCase().trim(); break; case 'p': newLine[i] = CMParms.getPastBit(line, i - 1); break; case 'P': newLine[i] = CMParms.getPastBit(line, i - 1).toUpperCase().trim(); break; case 'S': line = line.toUpperCase(); //$FALL-THROUGH$ case 's': { final String s = CMParms.getPastBit(line, i - 1); final int numBits = CMParms.numBits(s); final String[] newNewLine = new String[newLine.length - 1 + numBits]; for (int x = 0; x < i; x++) newNewLine[x] = newLine[x]; for (int x = 0; x < numBits; x++) newNewLine[i + x] = CMParms.getCleanBit(s, i - 1); newLine = newNewLine; i = instructions.length(); break; } case 'T': line = line.toUpperCase(); //$FALL-THROUGH$ case 't': { final String s = CMParms.getPastBit(line, i - 1); String[] newNewLine = null; if (CMParms.getCleanBit(s, 0).equalsIgnoreCase("P")) { newNewLine = new String[newLine.length + 1]; for (int x = 0; x < i; x++) newNewLine[x] = newLine[x]; newNewLine[i] = "P"; newNewLine[i + 1] = CMParms.getPastBitClean(s, 0); } else { final int numNewBits = (s.trim().length() == 0) ? 1 : CMParms.numBits(s); newNewLine = new String[newLine.length - 1 + numNewBits]; for (int x = 0; x < i; x++) newNewLine[x] = newLine[x]; for (int x = 0; x < numNewBits; x++) newNewLine[i + x] = CMParms.getCleanBit(s, x); } newLine = newNewLine; i = instructions.length(); break; } } } return newLine; } protected String[] insertStringArray(final String[] oldS, final String[] inS, final int where) { final String[] newLine=new String[oldS.length+inS.length-1]; for(int i=0;i<where;i++) newLine[i]=oldS[i]; for(int i=0;i<inS.length;i++) newLine[where+i]=inS[i]; for(int i=where+1;i<oldS.length;i++) newLine[inS.length+i-1]=oldS[i]; return newLine; } /* * c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger */ protected String[] parseBits(final String[][] oldBits, final int start, final String instructions) { final String[] tt=oldBits[0]; final String parseMe=tt[start]; final String[] parsed=parseBits(parseMe,instructions); if(parsed.length==1) { tt[start]=parsed[0]; return tt; } final String[] newLine=insertStringArray(tt,parsed,start); oldBits[0]=newLine; return newLine; } @Override public boolean endQuest(final PhysicalAgent hostObj, final MOB mob, final String quest) { if(mob!=null) { final List<DVector> scripts=getScripts(); if(!mob.amDead()) { lastKnownLocation=mob.location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } String trigger=""; String[] tt=null; for(int v=0;v<scripts.size();v++) { final DVector script=scripts.get(v); if(script.size()>0) { trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); tt=(String[])script.elementAt(0,2); if((getTriggerCode(trigger,tt)==13) //questtimeprog quest_time_prog &&(!oncesDone.contains(script))) { if(tt==null) tt=parseBits(script,0,"CCC"); if((tt!=null) &&((tt[1].equals(quest)||(tt[1].equals("*")))) &&(CMath.s_int(tt[2])<0)) { oncesDone.add(script); execute(hostObj,mob,mob,mob,null,null,script,null,newObjs()); return true; } } } } } return false; } @Override public List<String> externalFiles() { final Vector<String> xmlfiles=new Vector<String>(); parseLoads(getScript(), 0, xmlfiles, null); return xmlfiles; } protected String getVarHost(final Environmental E, String rawHost, final MOB source, final Environmental target, final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { if(!rawHost.equals("*")) { if(E==null) rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost); else if(E instanceof Room) rawHost=CMLib.map().getExtendedRoomID((Room)E); else rawHost=E.Name(); } return rawHost; } @SuppressWarnings("unchecked") @Override public boolean isVar(final String host, String var) { if(host.equalsIgnoreCase("*")) { String val=null; Hashtable<String,String> H=null; String key=null; var=var.toUpperCase(); for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { key=k.next(); if(key.startsWith("SCRIPTVAR-")) { H=(Hashtable<String,String>)resources._getResource(key); val=H.get(var); if(val!=null) return true; } } return false; } final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host); String val=null; if(H!=null) val=H.get(var.toUpperCase()); return (val!=null); } public String getVar(final Environmental E, final String rawHost, final String var, final MOB source, final Environmental target, final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var); } @Override public String getVar(final String host, final String var) { String varVal = getVar(resources,host,var,null); if(varVal != null) return varVal; if((this.defaultQuestName!=null)&&(this.defaultQuestName.length()>0)) { final Resources questResources=(Resources)Resources.getResource("VARSCOPE-"+this.defaultQuestName); if((questResources != null)&&(resources!=questResources)) { varVal = getVar(questResources,host,var,null); if(varVal != null) return varVal; } } if(resources == Resources.instance()) return ""; return getVar(Resources.instance(),host,var,""); } @SuppressWarnings("unchecked") public String getVar(final Resources resources, final String host, String var, final String defaultVal) { if(host.equalsIgnoreCase("*")) { if(var.equals("COFFEEMUD_SYSTEM_INTERNAL_NONFILENAME_SCRIPT")) { final StringBuffer str=new StringBuffer(""); parseLoads(getScript(),0,null,str); return str.toString(); } String val=null; Hashtable<String,String> H=null; String key=null; var=var.toUpperCase(); for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { key=k.next(); if(key.startsWith("SCRIPTVAR-")) { H=(Hashtable<String,String>)resources._getResource(key); val=H.get(var); if(val!=null) return val; } } return defaultVal; } Resources.instance(); final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host); String val=null; if(H!=null) val=H.get(var.toUpperCase()); else if((defaultQuestName!=null)&&(defaultQuestName.length()>0)) { final MOB M=CMLib.players().getPlayerAllHosts(host); if(M!=null) { for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null) &&(SE!=this) &&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName())) &&(SE.isVar(host,var))) return SE.getVar(host,var); } } } if(val==null) return defaultVal; return val; } private StringBuffer getResourceFileData(final String named, final boolean showErrors) { final Quest Q=getQuest("*"); if(Q!=null) return Q.getResourceFileData(named, showErrors); return new CMFile(Resources.makeFileResourceName(named),null,CMFile.FLAG_LOGERRORS).text(); } @Override public String getScript() { return myScript; } public void reset() { que = new Vector<ScriptableResponse>(); lastToHurtMe = null; lastKnownLocation= null; homeKnownLocation=null; altStatusTickable= null; oncesDone = new Vector<DVector>(); delayTargetTimes = new Hashtable<Integer,Integer>(); delayProgCounters= new Hashtable<Integer,int[]>(); lastTimeProgsDone= new Hashtable<Integer,Integer>(); lastDayProgsDone = new Hashtable<Integer,Integer>(); registeredEvents = new HashSet<Integer>(); noTrigger = new Hashtable<Integer,Long>(); backupMOB = null; lastMsg = null; bumpUpCache(); } @Override public void setScript(String newParms) { newParms=CMStrings.replaceAll(newParms,"'","`"); if(newParms.startsWith("+")) { final String superParms=getScript(); Resources.removeResource(getScriptResourceKey()); newParms=superParms+";"+newParms.substring(1); } myScript=newParms; if(myScript.length()>100) scriptKey="PARSEDPRG: "+myScript.substring(0,100)+myScript.length()+myScript.hashCode(); else scriptKey="PARSEDPRG: "+myScript; reset(); } public boolean isFreeToBeTriggered(final Tickable affecting) { if(alwaysTriggers) return CMLib.flags().canActAtAll(affecting); else return CMLib.flags().canFreelyBehaveNormal(affecting); } protected String parseLoads(final String text, final int depth, final Vector<String> filenames, final StringBuffer nonFilenameScript) { final StringBuffer results=new StringBuffer(""); String parse=text; if(depth>10) return ""; // no including off to infinity String p=null; while(parse.length()>0) { final int y=parse.toUpperCase().indexOf("LOAD="); if(y>=0) { p=parse.substring(0,y).trim(); if((!p.endsWith(";")) &&(!p.endsWith("\n")) &&(!p.endsWith("~")) &&(!p.endsWith("\r")) &&(p.length()>0)) { if(nonFilenameScript!=null) nonFilenameScript.append(parse.substring(0,y+1)); results.append(parse.substring(0,y+1)); parse=parse.substring(y+1); continue; } results.append(p+"\n"); int z=parse.indexOf('~',y); while((z>0)&&(parse.charAt(z-1)=='\\')) z=parse.indexOf('~',z+1); if(z>0) { final String filename=parse.substring(y+5,z).trim(); parse=parse.substring(z+1); if((filenames!=null)&&(!filenames.contains(filename))) filenames.addElement(filename); results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null)); } else { final String filename=parse.substring(y+5).trim(); if((filenames!=null)&&(!filenames.contains(filename))) filenames.addElement(filename); results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null)); break; } } else { if(nonFilenameScript!=null) nonFilenameScript.append(parse); results.append(parse); break; } } return results.toString(); } protected void buildHashes() { if(funcH.size()==0) { synchronized(funcH) { if(funcH.size()==0) { for(int i=0;i<funcs.length;i++) funcH.put(funcs[i],Integer.valueOf(i+1)); for(int i=0;i<methods.length;i++) methH.put(methods[i],Integer.valueOf(i+1)); for(int i=0;i<progs.length;i++) progH.put(progs[i],Integer.valueOf(i+1)); for(int i=0;i<progs.length;i++) methH.put(progs[i],Integer.valueOf(Integer.MIN_VALUE)); for(int i=0;i<CONNECTORS.length;i++) connH.put(CONNECTORS[i],Integer.valueOf(i)); for(int i=0;i<SIGNS.length;i++) signH.put(SIGNS[i],Integer.valueOf(i)); } } } } protected List<DVector> parseScripts(String text) { buildHashes(); while((text.length()>0) &&(Character.isWhitespace(text.charAt(0)))) text=text.substring(1); boolean staticSet=false; if((text.length()>10) &&(text.substring(0,10).toUpperCase().startsWith("STATIC="))) { staticSet=true; text=text.substring(7); } text=parseLoads(text,0,null,null); if(staticSet) { text=CMStrings.replaceAll(text,"'","`"); myScript=text; reset(); } final List<List<String>> V = CMParms.parseDoubleDelimited(text,'~',';'); final Vector<DVector> V2=new Vector<DVector>(3); for(final List<String> ls : V) { final DVector DV=new DVector(3); for(final String s : ls) DV.addElement(s,null,null); V2.add(DV); } return V2; } protected Room getRoom(final String thisName, final Room imHere) { if(thisName.length()==0) return null; if((imHere!=null) &&(imHere.roomID().equalsIgnoreCase(thisName))) return imHere; if((imHere!=null)&&(thisName.startsWith("#"))&&(CMath.isLong(thisName.substring(1)))) return CMLib.map().getRoom(imHere.getArea().Name()+thisName); final Room room=CMLib.map().getRoom(thisName); if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName))) { if(CMath.bset(room.getArea().flags(),Area.FLAG_INSTANCE_PARENT) &&(imHere!=null) &&(CMath.bset(imHere.getArea().flags(),Area.FLAG_INSTANCE_CHILD)) &&(imHere.getArea().Name().endsWith("_"+room.getArea().Name())) &&(thisName.indexOf('#')>=0)) { final Room otherRoom=CMLib.map().getRoom(imHere.getArea().Name()+thisName.substring(thisName.indexOf('#'))); if((otherRoom!=null)&&(otherRoom.roomID().endsWith(thisName))) return otherRoom; } return room; } List<Room> rooms=new Vector<Room>(1); if((imHere!=null)&&(imHere.getArea()!=null)) rooms=CMLib.map().findAreaRoomsLiberally(null, imHere.getArea(), thisName, "RIEPM",100); if(rooms.size()==0) { if(debugBadScripts) Log.debugOut("ScriptingEngine","World room search called for: "+thisName); rooms=CMLib.map().findWorldRoomsLiberally(null,thisName, "RIEPM",100,2000); } if(rooms.size()>0) return rooms.get(CMLib.dice().roll(1,rooms.size(),-1)); if(room == null) { final int x=thisName.indexOf('@'); if(x>0) { Room R=CMLib.map().getRoom(thisName.substring(x+1)); if((R==null)||(R==imHere)) { final Area A=CMLib.map().getArea(thisName.substring(x+1)); R=(A!=null)?A.getRandomMetroRoom():null; } if((R!=null)&&(R!=imHere)) return getRoom(thisName.substring(0,x),R); } } return room; } protected void logError(final Environmental scripted, final String cmdName, final String errType, final String errMsg) { if(scripted!=null) { final Room R=CMLib.map().roomLocation(scripted); String scriptFiles=CMParms.toListString(externalFiles()); if((scriptFiles == null)||(scriptFiles.trim().length()==0)) scriptFiles=CMStrings.limit(this.getScript(),80); if((scriptFiles == null)||(scriptFiles.trim().length()==0)) Log.errOut(new Exception("Scripting Error")); if((scriptFiles == null)||(scriptFiles.trim().length()==0)) scriptFiles=getScriptResourceKey(); Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg+"/"+scriptFiles); if(R!=null) R.showHappens(CMMsg.MSG_OK_VISUAL,L("Scripting Error: @x1/@x2/@x3/@x4/@x5/@x6",scripted.name(),CMLib.map().getExtendedRoomID(R),cmdName,errType,errMsg,scriptFiles)); } else Log.errOut("Scripting","*/*/"+CMParms.toListString(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg); } protected boolean simpleEvalStr(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName) { final int x=arg1.compareToIgnoreCase(arg2); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (x == 0); case SIGN_EQGT: case SIGN_GTEQ: return (x == 0) || (x > 0); case SIGN_EQLT: case SIGN_LTEQ: return (x == 0) || (x < 0); case SIGN_GRAT: return (x > 0); case SIGN_LEST: return (x < 0); case SIGN_NTEQ: return (x != 0); default: return (x == 0); } } protected boolean simpleEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName) { final long val1=CMath.s_long(arg1.trim()); final long val2=CMath.s_long(arg2.trim()); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (val1 == val2); case SIGN_EQGT: case SIGN_GTEQ: return val1 >= val2; case SIGN_EQLT: case SIGN_LTEQ: return val1 <= val2; case SIGN_GRAT: return (val1 > val2); case SIGN_LEST: return (val1 < val2); case SIGN_NTEQ: return (val1 != val2); default: return (val1 == val2); } } protected boolean simpleExpressionEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName) { final double val1=CMath.s_parseMathExpression(arg1.trim()); final double val2=CMath.s_parseMathExpression(arg2.trim()); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (val1 == val2); case SIGN_EQGT: case SIGN_GTEQ: return val1 >= val2; case SIGN_EQLT: case SIGN_LTEQ: return val1 <= val2; case SIGN_GRAT: return (val1 > val2); case SIGN_LEST: return (val1 < val2); case SIGN_NTEQ: return (val1 != val2); default: return (val1 == val2); } } protected List<MOB> loadMobsFromFile(final Environmental scripted, String filename) { filename=filename.trim(); @SuppressWarnings("unchecked") List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMMONSTERS-"+filename); if(monsters!=null) return monsters; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); monsters=new Vector<MOB>(); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"MOBS")!=null) { final String error=CMLib.coffeeMaker().addMOBsFromXML(xml,monsters,null); if(error.length()>0) { logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'"); return null; } if(monsters.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMMONSTERS-"+filename,monsters); for(final Object O : monsters) { if(O instanceof MOB) CMLib.threads().deleteAllTicks((MOB)O); } } else { logError(scripted,"XMLLOAD","?","No MOBs in XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName); return null; } return monsters; } protected List<MOB> generateMobsFromFile(final Environmental scripted, String filename, final String tagName, final String rest) { filename=filename.trim(); @SuppressWarnings("unchecked") List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest); if(monsters!=null) return monsters; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); monsters=new Vector<MOB>(); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null) { final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>(); final Map<String,String> eqParms=new HashMap<String,String>(); eqParms.putAll(CMParms.parseEQParms(rest.trim())); final String idName=tagName.toUpperCase(); try { CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>()); if((!(definedIDs.get(idName) instanceof XMLTag)) ||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("MOB"))) { logError(scripted,"XMLLOAD","?","Non-MOB tag '"+idName+"' for XML file: '"+filename+"' in "+thangName); return null; } final XMLTag piece=(XMLTag)definedIDs.get(idName); definedIDs.putAll(eqParms); try { CMLib.percolator().checkRequirements(piece, definedIDs); } catch(final CMException cme) { logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage()); return null; } CMLib.percolator().preDefineReward(piece, definedIDs); CMLib.percolator().defineReward(piece,definedIDs); monsters.addAll(CMLib.percolator().findMobs(piece, definedIDs)); CMLib.percolator().postProcess(definedIDs); if(monsters.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } Resources.submitResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest,monsters); } catch(final CMException cex) { logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage()); return null; } } else { logError(scripted,"XMLLOAD","?","Invalid GEN XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName); return null; } return monsters; } protected List<Item> loadItemsFromFile(final Environmental scripted, String filename) { filename=filename.trim(); @SuppressWarnings("unchecked") List<Item> items=(List<Item>)Resources.getResource("RANDOMITEMS-"+filename); if(items!=null) return items; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } items=new Vector<Item>(); final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"ITEMS")!=null) { final String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null); if(error.length()>0) { logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"' in "+thangName); return null; } if(items.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'"); return null; } for(final Object O : items) { if(O instanceof Item) CMLib.threads().deleteTick((Item)O, -1); } Resources.submitResource("RANDOMITEMS-"+filename,items); } else { logError(scripted,"XMLLOAD","?","No ITEMS in XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Empty or invalid XML file: '"+filename+"' in "+thangName); return null; } return items; } protected List<Item> generateItemsFromFile(final Environmental scripted, String filename, final String tagName, final String rest) { filename=filename.trim(); @SuppressWarnings("unchecked") List<Item> items=(List<Item>)Resources.getResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest); if(items!=null) return items; final StringBuffer buf=getResourceFileData(filename, true); String thangName="null"; final Room R=CMLib.map().roomLocation(scripted); if(R!=null) thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted); else if(scripted!=null) thangName=scripted.name(); if((buf==null)||(buf.length()<20)) { logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName); return null; } items=new Vector<Item>(); final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString()); if(xml!=null) { if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null) { final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>(); final Map<String,String> eqParms=new HashMap<String,String>(); eqParms.putAll(CMParms.parseEQParms(rest.trim())); final String idName=tagName.toUpperCase(); try { CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>()); if((!(definedIDs.get(idName) instanceof XMLTag)) ||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("ITEM"))) { logError(scripted,"XMLLOAD","?","Non-ITEM tag '"+idName+"' for XML file: '"+filename+"' in "+thangName); return null; } final XMLTag piece=(XMLTag)definedIDs.get(idName); definedIDs.putAll(eqParms); try { CMLib.percolator().checkRequirements(piece, definedIDs); } catch(final CMException cme) { logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage()); return null; } CMLib.percolator().preDefineReward(piece, definedIDs); CMLib.percolator().defineReward(piece,definedIDs); items.addAll(CMLib.percolator().findItems(piece, definedIDs)); CMLib.percolator().postProcess(definedIDs); if(items.size()<=0) { logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"' in "+thangName); return null; } Resources.submitResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest,items); } catch(final CMException cex) { logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage()); return null; } } else { logError(scripted,"XMLLOAD","?","Not a GEN XML file: '"+filename+"' in "+thangName); return null; } } else { logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName); return null; } return items; } @SuppressWarnings("unchecked") protected Environmental findSomethingCalledThis(final String thisName, final MOB meMOB, final Room imHere, List<Environmental> OBJS, final boolean mob) { if(thisName.length()==0) return null; Environmental thing=null; Environmental areaThing=null; if(thisName.toUpperCase().trim().startsWith("FROMFILE ")) { try { List<? extends Environmental> V=null; if(mob) V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1)); else V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1)); if(V!=null) { final String name=CMParms.getPastBitClean(thisName,1); if(name.equalsIgnoreCase("ALL")) OBJS=(List<Environmental>)V; else if(name.equalsIgnoreCase("ANY")) { if(V.size()>0) areaThing=V.get(CMLib.dice().roll(1,V.size(),-1)); } else { areaThing=CMLib.english().fetchEnvironmental(V,name,true); if(areaThing==null) areaThing=CMLib.english().fetchEnvironmental(V,name,false); } } } catch(final Exception e) { } } else if(thisName.toUpperCase().trim().startsWith("FROMGENFILE ")) { try { List<? extends Environmental> V=null; final String filename=CMParms.getCleanBit(thisName, 1); final String name=CMParms.getCleanBit(thisName, 2); final String tagName=CMParms.getCleanBit(thisName, 3); final String theRest=CMParms.getPastBitClean(thisName,3); if(mob) V=generateMobsFromFile(null,filename, tagName, theRest); else V=generateItemsFromFile(null,filename, tagName, theRest); if(V!=null) { if(name.equalsIgnoreCase("ALL")) OBJS=(List<Environmental>)V; else if(name.equalsIgnoreCase("ANY")) { if(V.size()>0) areaThing=V.get(CMLib.dice().roll(1,V.size(),-1)); } else { areaThing=CMLib.english().fetchEnvironmental(V,name,true); if(areaThing==null) areaThing=CMLib.english().fetchEnvironmental(V,name,false); } } } catch(final Exception e) { } } else { if(!mob) areaThing=(meMOB!=null)?meMOB.findItem(thisName):null; try { if(areaThing==null) { final Area A=imHere.getArea(); final Vector<Environmental> all=new Vector<Environmental>(); if(mob) { all.addAll(CMLib.map().findInhabitants(A.getProperMap(),null,thisName,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(A.getProperMap(), null, thisName,100)); for(int a=all.size()-1;a>=0;a--) { if(!(all.elementAt(a) instanceof MOB)) all.removeElementAt(a); } if(all.size()>0) areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); else { all.addAll(CMLib.map().findInhabitantsFavorExact(CMLib.map().rooms(),null,thisName,false,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null, thisName,100)); for(int a=all.size()-1;a>=0;a--) { if(!(all.elementAt(a) instanceof MOB)) all.removeElementAt(a); } if(all.size()>0) thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); } } if(all.size()==0) { all.addAll(CMLib.map().findRoomItems(A.getProperMap(), null,thisName,true,100)); if(all.size()==0) all.addAll(CMLib.map().findInventory(A.getProperMap(), null,thisName,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(A.getProperMap(), null,thisName,100)); if(all.size()>0) areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); else { all.addAll(CMLib.map().findRoomItems(CMLib.map().rooms(), null,thisName,true,100)); if(all.size()==0) all.addAll(CMLib.map().findInventory(CMLib.map().rooms(), null,thisName,100)); if(all.size()==0) all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null,thisName,100)); if(all.size()>0) thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1)); } } } } catch(final NoSuchElementException nse) { } } if(areaThing!=null) OBJS.add(areaThing); else if(thing!=null) OBJS.add(thing); if(OBJS.size()>0) return OBJS.get(0); return null; } protected PhysicalAgent getArgumentMOB(final String str, final MOB source, final MOB monster, final Environmental target, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp); } protected PhysicalAgent getArgumentItem(String str, final MOB source, final MOB monster, final PhysicalAgent scripted, final Environmental target, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { if(str.length()<2) return null; if(str.charAt(0)=='$') { if(Character.isDigit(str.charAt(1))) { Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))]; if(O instanceof PhysicalAgent) return (PhysicalAgent)O; else if((O instanceof List)&&(str.length()>3)&&(str.charAt(2)=='.')) { final List<?> V=(List<?>)O; String back=str.substring(2); if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length())&&(Character.isDigit(back.charAt(x)))) x++; final int y=CMath.s_int(back.substring(1,x).trim()); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) return null; O=V.get(y); if(O instanceof PhysicalAgent) return (PhysicalAgent)O; } str=O.toString(); // will fall through } } else if(O!=null) str=O.toString(); // will fall through else return null; } else switch(str.charAt(1)) { case 'a': return (lastKnownLocation != null) ? lastKnownLocation.getArea() : null; case 'B': case 'b': return (lastLoaded instanceof PhysicalAgent) ? (PhysicalAgent) lastLoaded : null; case 'N': case 'n': return ((source == backupMOB) && (backupMOB != null) && (monster != scripted)) ? scripted : source; case 'I': case 'i': return scripted; case 'T': case 't': return ((target == backupMOB) && (backupMOB != null) && (monster != scripted)) ? scripted : (target instanceof PhysicalAgent) ? (PhysicalAgent) target : null; case 'O': case 'o': return primaryItem; case 'P': case 'p': return secondaryItem; case 'd': case 'D': return lastKnownLocation; case 'F': case 'f': if ((monster != null) && (monster.amFollowing() != null)) return monster.amFollowing(); return null; case 'r': case 'R': return getRandPC(monster, tmp, lastKnownLocation); case 'c': case 'C': return getRandAnyone(monster, tmp, lastKnownLocation); case 'w': return primaryItem != null ? primaryItem.owner() : null; case 'W': return secondaryItem != null ? secondaryItem.owner() : null; case 'x': case 'X': if (lastKnownLocation != null) { if ((str.length() > 2) && (CMLib.directions().getGoodDirectionCode("" + str.charAt(2)) >= 0)) return lastKnownLocation.getExitInDir(CMLib.directions().getGoodDirectionCode("" + str.charAt(2))); int i = 0; Exit E = null; while (((++i) < 100) || (E != null)) E = lastKnownLocation.getExitInDir(CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1)); return E; } return null; case '[': { final int x = str.substring(2).indexOf(']'); if (x >= 0) { String mid = str.substring(2).substring(0, x); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) return Q.getQuestItem(num); } } break; } case '{': { final int x = str.substring(2).indexOf('}'); if (x >= 0) { String mid = str.substring(2).substring(0, x).trim(); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) { final MOB M=Q.getQuestMob(num); return M; } } } break; } } } if(lastKnownLocation!=null) { str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str); Environmental E=null; if(str.indexOf('#')>0) E=CMLib.map().getRoom(str); if(E==null) E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str); if(E==null) E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Wearable.FILTER_ANY); if(E==null) E=lastKnownLocation.findItem(str); if((E==null)&&(monster!=null)) E=monster.findItem(str); if(E==null) E=CMLib.players().getPlayerAllHosts(str); if((E==null)&&(source!=null)) E=source.findItem(str); if(E instanceof PhysicalAgent) return (PhysicalAgent)E; } return null; } private String makeNamedString(final Object O) { if(O instanceof List) return makeParsableString((List<?>)O); else if(O instanceof Room) return ((Room)O).displayText(null); else if(O instanceof Environmental) return ((Environmental)O).Name(); else if(O!=null) return O.toString(); return ""; } private String makeParsableString(final List<?> V) { if((V==null)||(V.size()==0)) return ""; if(V.get(0) instanceof String) return CMParms.combineQuoted(V,0); final StringBuffer ret=new StringBuffer(""); String S=null; for(int v=0;v<V.size();v++) { S=makeNamedString(V.get(v)).trim(); if(S.length()==0) ret.append("? "); else if(S.indexOf(' ')>=0) ret.append("\""+S+"\" "); else ret.append(S+" "); } return ret.toString(); } @Override public String varify(final MOB source, final Environmental target, final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp, String varifyable) { int t=varifyable.indexOf('$'); if((monster!=null)&&(monster.location()!=null)) lastKnownLocation=monster.location(); if(lastKnownLocation==null) { lastKnownLocation=source.location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } else if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; MOB randMOB=null; while((t>=0)&&(t<varifyable.length()-1)) { final char c=varifyable.charAt(t+1); String middle=""; final String front=varifyable.substring(0,t); String back=varifyable.substring(t+2); if(Character.isDigit(c)) middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]); else switch(c) { case '@': if ((t < varifyable.length() - 2) && (Character.isLetter(varifyable.charAt(t + 2))||Character.isDigit(varifyable.charAt(t + 2)))) { final Environmental E = getArgumentItem("$" + varifyable.charAt(t + 2), source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(back.length()>0) back=back.substring(1); middle = (E == null) ? "null" : "" + E; } break; case 'a': if (lastKnownLocation != null) middle = lastKnownLocation.getArea().name(); break; // case 'a': case 'A': // unnecessary, since, in coffeemud, this is part of the // name break; case 'b': middle = lastLoaded != null ? lastLoaded.name() : ""; break; case 'B': middle = lastLoaded != null ? lastLoaded.displayText() : ""; break; case 'c': case 'C': randMOB = getRandAnyone(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.name(); break; case 'd': middle = (lastKnownLocation != null) ? lastKnownLocation.displayText(monster) : ""; break; case 'D': middle = (lastKnownLocation != null) ? lastKnownLocation.description(monster) : ""; break; case 'e': if (source != null) middle = source.charStats().heshe(); break; case 'E': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().heshe(); break; case 'f': if ((monster != null) && (monster.amFollowing() != null)) middle = monster.amFollowing().name(); break; case 'F': if ((monster != null) && (monster.amFollowing() != null)) middle = monster.amFollowing().charStats().heshe(); break; case 'g': middle = ((msg == null) ? "" : msg.toLowerCase()); break; case 'G': middle = ((msg == null) ? "" : msg); break; case 'h': if (monster != null) middle = monster.charStats().himher(); break; case 'H': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.charStats().himher(); break; case 'i': if (monster != null) middle = monster.name(); break; case 'I': if (monster != null) middle = monster.displayText(); break; case 'j': if (monster != null) middle = monster.charStats().heshe(); break; case 'J': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.charStats().heshe(); break; case 'k': if (monster != null) middle = monster.charStats().hisher(); break; case 'K': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.charStats().hisher(); break; case 'l': if (lastKnownLocation != null) { final StringBuffer str = new StringBuffer(""); for (int i = 0; i < lastKnownLocation.numInhabitants(); i++) { final MOB M = lastKnownLocation.fetchInhabitant(i); if ((M != null) && (M != monster) && (CMLib.flags().canBeSeenBy(M, monster))) str.append("\"" + M.name() + "\" "); } middle = str.toString(); } break; case 'L': if (lastKnownLocation != null) { final StringBuffer str = new StringBuffer(""); for (int i = 0; i < lastKnownLocation.numItems(); i++) { final Item I = lastKnownLocation.getItem(i); if ((I != null) && (I.container() == null) && (CMLib.flags().canBeSeenBy(I, monster))) str.append("\"" + I.name() + "\" "); } middle = str.toString(); } break; case 'm': if (source != null) middle = source.charStats().hisher(); break; case 'M': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().hisher(); break; case 'n': case 'N': if (source != null) middle = source.name(); break; case 'o': case 'O': if (primaryItem != null) middle = primaryItem.name(); break; case 'p': case 'P': if (secondaryItem != null) middle = secondaryItem.name(); break; case 'r': case 'R': randMOB = getRandPC(monster, tmp, lastKnownLocation); if (randMOB != null) middle = randMOB.name(); break; case 's': if (source != null) middle = source.charStats().himher(); break; case 'S': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().himher(); break; case 't': case 'T': if (target != null) middle = target.name(); break; case 'w': middle = primaryItem != null ? primaryItem.owner().Name() : middle; break; case 'W': middle = secondaryItem != null ? secondaryItem.owner().Name() : middle; break; case 'x': case 'X': if (lastKnownLocation != null) { middle = ""; Exit E = null; int dir = -1; if ((t < varifyable.length() - 2) && (CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2)) >= 0)) { dir = CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2)); E = lastKnownLocation.getExitInDir(dir); } else { int i = 0; while (((++i) < 100) || (E != null)) { dir = CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1); E = lastKnownLocation.getExitInDir(dir); } } if ((dir >= 0) && (E != null)) { if (c == 'x') middle = CMLib.directions().getDirectionName(dir); else middle = E.name(); } } break; case 'y': if (source != null) middle = source.charStats().sirmadam(); break; case 'Y': if ((target != null) && (target instanceof MOB)) middle = ((MOB) target).charStats().sirmadam(); break; case '<': { final int x = back.indexOf('>'); if (x >= 0) { String mid = back.substring(0, x); final int y = mid.indexOf(' '); Environmental E = null; String arg1 = ""; if (y >= 0) { arg1 = mid.substring(0, y).trim(); E = getArgumentItem(arg1, source, monster, monster, target, primaryItem, secondaryItem, msg, tmp); mid = mid.substring(y + 1).trim(); } if (arg1.length() > 0) middle = getVar(E, arg1, mid, source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp); back = back.substring(x + 1); } break; } case '[': { middle = ""; final int x = back.indexOf(']'); if (x >= 0) { String mid = back.substring(0, x); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) middle = Q.getQuestItemName(num); } back = back.substring(x + 1); } break; } case '{': { middle = ""; final int x = back.indexOf('}'); if (x >= 0) { String mid = back.substring(0, x).trim(); final int y = mid.indexOf(' '); if (y > 0) { final int num = CMath.s_int(mid.substring(0, y).trim()); mid = mid.substring(y + 1).trim(); final Quest Q = getQuest(mid); if (Q != null) middle = Q.getQuestMobName(num); } back = back.substring(x + 1); } break; } case '%': { middle = ""; final int x = back.indexOf('%'); if (x >= 0) { middle = functify(scripted, source, target, monster, primaryItem, secondaryItem, msg, tmp, back.substring(0, x).trim()); back = back.substring(x + 1); } break; } } if((back.startsWith(".")) &&(back.length()>1)) { if(back.charAt(1)=='$') back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back); if(back.startsWith(".LENGTH#")) { middle=""+CMParms.parse(middle).size(); back=back.substring(8); } else if((back.length()>1)&&Character.isDigit(back.charAt(1))) { int x=1; while((x<back.length()) &&(Character.isDigit(back.charAt(x)))) x++; final int y=CMath.s_int(back.substring(1,x).trim()); back=back.substring(x); final boolean rest=back.startsWith(".."); if(rest) back=back.substring(2); final Vector<String> V=CMParms.parse(middle); if((V.size()>0)&&(y>=0)) { if(y>=V.size()) middle=""; else if(rest) middle=CMParms.combine(V,y); else middle=V.elementAt(y); } } } varifyable=front+middle+back; t=varifyable.indexOf('$'); } return varifyable; } protected PairList<String,String> getScriptVarSet(final String mobname, final String varname) { final PairList<String,String> set=new PairVector<String,String>(); if(mobname.equals("*")) { for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();) { final String key=k.next(); if(key.startsWith("SCRIPTVAR-")) { @SuppressWarnings("unchecked") final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource(key); if(varname.equals("*")) { if(H!=null) { for(final Enumeration<String> e=H.keys();e.hasMoreElements();) { final String vn=e.nextElement(); set.add(key.substring(10),vn); } } } else set.add(key.substring(10),varname); } } } else { @SuppressWarnings("unchecked") final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource("SCRIPTVAR-"+mobname); if(varname.equals("*")) { if(H!=null) { for(final Enumeration<String> e=H.keys();e.hasMoreElements();) { final String vn=e.nextElement(); set.add(mobname,vn); } } } else set.add(mobname,varname); } return set; } protected String getStatValue(final Environmental E, final String arg2) { boolean found=false; String val=""; final String uarg2=arg2.toUpperCase().trim(); for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equals(uarg2)) { val=E.getStat(uarg2); found=true; break; } } if((!found)&&(E instanceof MOB)) { final MOB M=(MOB)E; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2)) { val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); //yes, this is right found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } } } if(!found) { for(int i=0;i<M.phyStats().getStatCodes().length;i++) { if(M.phyStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(uarg2.startsWith("BASE"))) { for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } } if((!found)&&(uarg2.equals("STINK"))) { found=true; val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT); } if((!found) &&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,uarg2)!=null)) { found=true; val=CMLib.coffeeMaker().getAnyGenStat(M, uarg2); } } if((!found) &&(E instanceof Item) &&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,uarg2)!=null)) { found=true; val=CMLib.coffeeMaker().getAnyGenStat((Item)E, uarg2); } if((!found) &&(E instanceof Physical) &&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,uarg2)!=null)) { found=true; val=CMLib.coffeeMaker().getAnyGenStat((Physical)E, uarg2); } if(!found) return null; return val; } protected String getGStatValue(final Environmental E, String arg2) { if(E==null) return null; boolean found=false; String val=""; for(int i=0;i<E.getStatCodes().length;i++) { if(E.getStatCodes()[i].equalsIgnoreCase(arg2)) { val=E.getStat(arg2); found=true; break; } } if(!found) if(E instanceof MOB) { arg2=arg2.toUpperCase().trim(); final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2); if(element != null) { val=CMLib.coffeeMaker().getGenMobStat((MOB)E,element.name()); found=true; } if(!found) { final MOB M=(MOB)E; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equals(arg2)||CharStats.CODES.DESC(i).equals(arg2)) { val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equals(arg2)) { val=M.curState().getStat(M.curState().getStatCodes()[i]); found=true; break; } } } if(!found) { for(int i=0;i<M.phyStats().getStatCodes().length;i++) { if(M.phyStats().getStatCodes()[i].equals(arg2)) { val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equals(arg2)) { val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]); found=true; break; } } } if((!found)&&(arg2.startsWith("BASE"))) { final String arg4=arg2.substring(4); for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equals(arg4)) { val=M.baseState().getStat(M.baseState().getStatCodes()[i]); found=true; break; } } if(!found) { for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equals(arg4)||CharStats.CODES.DESC(i).equals(arg4)) { val=""+M.baseCharStats().getStat(CharStats.CODES.NAME(i)); found=true; break; } } } } if((!found)&&(arg2.equals("STINK"))) { found=true; val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT); } } } else if(E instanceof Item) { final GenericBuilder.GenItemCode code = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class, arg2.toUpperCase().trim()); if(code != null) { val=CMLib.coffeeMaker().getGenItemStat((Item)E,code.name()); found=true; } } if((!found) &&(E instanceof Physical)) { if(CMLib.coffeeMaker().isAnyGenStat((Physical)E, arg2.toUpperCase().trim())) return CMLib.coffeeMaker().getAnyGenStat((Physical)E, arg2.toUpperCase().trim()); if((!found)&&(arg2.startsWith("BASE"))) { final String arg4=arg2.substring(4); for(int i=0;i<((Physical)E).basePhyStats().getStatCodes().length;i++) { if(((Physical)E).basePhyStats().getStatCodes()[i].equals(arg4)) { val=((Physical)E).basePhyStats().getStat(((Physical)E).basePhyStats().getStatCodes()[i]); found=true; break; } } } } if(found) return val; return null; } @Override public void setVar(final String baseName, String key, String val) { final PairList<String,String> vars=getScriptVarSet(baseName,key); for(int v=0;v<vars.size();v++) { final String name=vars.elementAtFirst(v); key=vars.elementAtSecond(v).toUpperCase(); @SuppressWarnings("unchecked") Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+name); if((H==null)&&(defaultQuestName!=null)&&(defaultQuestName.length()>0)) { final MOB M=CMLib.players().getPlayerAllHosts(name); if(M!=null) { for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null) &&(SE!=this) &&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName())) &&(SE.isVar(name,key))) { SE.setVar(name,key,val); return; } } } } if(H==null) { if(val.length()==0) continue; H=new Hashtable<String,String>(); resources._submitResource("SCRIPTVAR-"+name,H); } if(val.length()>0) { switch(val.charAt(0)) { case '+': if(val.equals("++")) { String num=H.get(key); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())+1); } else { String num=H.get(key); // add via +number form if(CMath.isNumber(val.substring(1).trim())) { if(num==null) num="0"; val=val.substring(1); final int amount=CMath.s_int(val.trim()); val=Integer.toString(CMath.s_int(num.trim())+amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; } break; case '-': if(val.equals("--")) { String num=H.get(key); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())-1); } else { // subtract -number form String num=H.get(key); if(CMath.isNumber(val.substring(1).trim())) { val=val.substring(1); final int amount=CMath.s_int(val.trim()); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())-amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; } break; case '*': { // multiply via *number form String num=H.get(key); if(CMath.isNumber(val.substring(1).trim())) { val=val.substring(1); final int amount=CMath.s_int(val.trim()); if(num==null) num="0"; val=Integer.toString(CMath.s_int(num.trim())*amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; break; } case '/': { // divide /number form String num=H.get(key); if(CMath.isNumber(val.substring(1).trim())) { val=val.substring(1); final int amount=CMath.s_int(val.trim()); if(num==null) num="0"; if(amount==0) Log.errOut("Scripting","Scripting SetVar error: Division by 0: "+name+"/"+key+"="+val); else val=Integer.toString(CMath.s_int(num.trim())/amount); } else if((num!=null)&&(CMath.isNumber(num))) val=num; break; } default: break; } } if(H.containsKey(key)) H.remove(key); if(val.trim().length()>0) H.put(key,val); if(H.size()==0) resources._removeResource("SCRIPTVAR-"+name); } } @Override public String[] parseEval(final String evaluable) throws ScriptParseException { final int STATE_MAIN=0; final int STATE_INFUNCTION=1; final int STATE_INFUNCQUOTE=2; final int STATE_POSTFUNCTION=3; final int STATE_POSTFUNCEVAL=4; final int STATE_POSTFUNCQUOTE=5; final int STATE_MAYFUNCTION=6; buildHashes(); final List<String> V=new ArrayList<String>(); if((evaluable==null)||(evaluable.trim().length()==0)) return new String[]{}; final char[] evalC=evaluable.toCharArray(); int state=0; int dex=0; char lastQuote='\0'; String s=null; int depth=0; for(int c=0;c<evalC.length;c++) { switch(state) { case STATE_MAIN: { if(Character.isWhitespace(evalC[c])) { s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) { s=s.toUpperCase(); V.add(s); dex=c+1; if(funcH.containsKey(s)) state=STATE_MAYFUNCTION; else if(!connH.containsKey(s)) throw new ScriptParseException("Unknown keyword: "+s); } } else if(Character.isLetter(evalC[c]) ||(Character.isDigit(evalC[c]) &&(c>0)&&Character.isLetter(evalC[c-1]) &&(c<evalC.length-1) &&Character.isLetter(evalC[c+1]))) { /* move along */ } else { switch(evalC[c]) { case '!': { if(c==evalC.length-1) throw new ScriptParseException("Bad Syntax on last !"); V.add("NOT"); dex=c+1; break; } case '(': { s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) { s=s.toUpperCase(); V.add(s); V.add("("); dex=c+1; if(funcH.containsKey(s)) state=STATE_INFUNCTION; else if(connH.containsKey(s)) state=STATE_MAIN; else throw new ScriptParseException("Unknown keyword: "+s); } else { V.add("("); depth++; dex=c+1; } break; } case ')': s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) throw new ScriptParseException("Bad syntax before ) at: "+s); if(depth==0) throw new ScriptParseException("Unmatched ) character"); V.add(")"); depth--; dex=c+1; break; default: throw new ScriptParseException("Unknown character at: "+new String(evalC,dex,c-dex+1).trim()+": "+evaluable); } } break; } case STATE_MAYFUNCTION: { if(evalC[c]=='(') { V.add("("); dex=c+1; state=STATE_INFUNCTION; } else if(!Character.isWhitespace(evalC[c])) throw new ScriptParseException("Expected ( at "+evalC[c]+": "+evaluable); break; } case STATE_POSTFUNCTION: { if(!Character.isWhitespace(evalC[c])) { switch(evalC[c]) { case '=': case '>': case '<': case '!': { if(c==evalC.length-1) throw new ScriptParseException("Bad Syntax on last "+evalC[c]); if(!Character.isWhitespace(evalC[c+1])) { s=new String(evalC,c,2); if((!signH.containsKey(s))&&(evalC[c]!='!')) s=""+evalC[c]; } else s=""+evalC[c]; if(!signH.containsKey(s)) { c=dex-1; state=STATE_MAIN; break; } V.add(s); dex=c+(s.length()); c=c+(s.length()-1); state=STATE_POSTFUNCEVAL; break; } default: c=dex-1; state=STATE_MAIN; break; } } break; } case STATE_INFUNCTION: { if(evalC[c]==')') { V.add(new String(evalC,dex,c-dex)); V.add(")"); dex=c+1; state=STATE_POSTFUNCTION; } else if((evalC[c]=='\'')||(evalC[c]=='`')) { lastQuote=evalC[c]; state=STATE_INFUNCQUOTE; } break; } case STATE_INFUNCQUOTE: { if((evalC[c]==lastQuote) &&((c==evalC.length-1) ||((!Character.isLetter(evalC[c-1])) ||(!Character.isLetter(evalC[c+1]))))) state=STATE_INFUNCTION; break; } case STATE_POSTFUNCQUOTE: { if(evalC[c]==lastQuote) { if((V.size()>2) &&(signH.containsKey(V.get(V.size()-1))) &&(V.get(V.size()-2).equals(")"))) { final String sign=V.get(V.size()-1); V.remove(V.size()-1); V.remove(V.size()-1); final String prev=V.get(V.size()-1); if(prev.equals("(")) s=sign+" "+new String(evalC,dex+1,c-dex); else { V.remove(V.size()-1); s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex); } V.add(s); V.add(")"); dex=c+1; state=STATE_MAIN; } else throw new ScriptParseException("Bad postfunc Eval somewhere"); } break; } case STATE_POSTFUNCEVAL: { if(Character.isWhitespace(evalC[c])) { s=new String(evalC,dex,c-dex).trim(); if(s.length()>0) { if((V.size()>1) &&(signH.containsKey(V.get(V.size()-1))) &&(V.get(V.size()-2).equals(")"))) { final String sign=V.get(V.size()-1); V.remove(V.size()-1); V.remove(V.size()-1); final String prev=V.get(V.size()-1); if(prev.equals("(")) s=sign+" "+new String(evalC,dex+1,c-dex); else { V.remove(V.size()-1); s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex); } V.add(s); V.add(")"); dex=c+1; state=STATE_MAIN; } else throw new ScriptParseException("Bad postfunc Eval somewhere"); } } else if(Character.isLetterOrDigit(evalC[c])) { /* move along */ } else if((evalC[c]=='\'')||(evalC[c]=='`')) { s=new String(evalC,dex,c-dex).trim(); if(s.length()==0) { lastQuote=evalC[c]; state=STATE_POSTFUNCQUOTE; } } break; } } } if((state==STATE_POSTFUNCQUOTE) ||(state==STATE_INFUNCQUOTE)) throw new ScriptParseException("Unclosed "+lastQuote+" in "+evaluable); if(depth>0) throw new ScriptParseException("Unclosed ( in "+evaluable); return CMParms.toStringArray(V); } public void pushEvalBoolean(final List<Object> stack, boolean trueFalse) { if(stack.size()>0) { final Object O=stack.get(stack.size()-1); if(O instanceof Integer) { final int connector=((Integer)O).intValue(); stack.remove(stack.size()-1); if((stack.size()>0) &&((stack.get(stack.size()-1) instanceof Boolean))) { final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue(); stack.remove(stack.size()-1); switch(connector) { case CONNECTOR_AND: trueFalse = preTrueFalse && trueFalse; break; case CONNECTOR_OR: trueFalse = preTrueFalse || trueFalse; break; case CONNECTOR_ANDNOT: trueFalse = preTrueFalse && (!trueFalse); break; case CONNECTOR_NOT: case CONNECTOR_ORNOT: trueFalse = preTrueFalse || (!trueFalse); break; } } else switch(connector) { case CONNECTOR_ANDNOT: case CONNECTOR_NOT: case CONNECTOR_ORNOT: trueFalse = !trueFalse; break; default: break; } } else if(O instanceof Boolean) { final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue(); stack.remove(stack.size()-1); trueFalse=preTrueFalse&&trueFalse; } } stack.add(trueFalse?Boolean.TRUE:Boolean.FALSE); } /** * Returns the index, in the given string vector, of the given string, starting * from the given index. If the string to search for contains more than one * "word", where a word is defined in space-delimited terms respecting double-quotes, * then it will return the index at which all the words in the parsed search string * are found in the given string list. * @param V the string list to search in * @param str the string to search for * @param start the index to start at (0 is good) * @return the index at which the search string was found in the string list, or -1 */ private static int strIndex(final Vector<String> V, final String str, final int start) { int x=V.indexOf(str,start); if(x>=0) return x; final List<String> V2=CMParms.parse(str); if(V2.size()==0) return -1; x=V.indexOf(V2.get(0),start); boolean found=false; while((x>=0)&&((x+V2.size())<=V.size())&&(!found)) { found=true; for(int v2=1;v2<V2.size();v2++) { if(!V.get(x+v2).equals(V2.get(v2))) { found=false; break; } } if(!found) x=V.indexOf(V2.get(0),x+1); } if(found) return x; return -1; } /** * Weird method. Accepts a string list, a combiner (see below), a string buffer to search for, * and a previously found index. The stringbuffer is always cleared during this call. * If the stringbuffer was empty, the previous found index is returned. Otherwise: * If the combiner is '&', the first index of the given stringbuffer in the string list is returned (or -1). * If the combiner is '|', the previous index is returned if it was found, otherwise the first index * of the given stringbuffer in the string list is returned (or -1). * If the combiner is '&gt;', then the previous index is returned if it was not found (-1), otherwise the * next highest found stringbuffer since the last string list search is returned, or (-1) if no more found. * If the combiner is '&lt;', then the previous index is returned if it was not found (-1), otherwise the * first found stringbuffer index is returned if it is lower than the previously found index. * Other combiners return -1. * @param V the string list to search * @param combiner the combiner, either &,|,&lt;,or &gt;. * @param buf the stringbuffer to search for, which is always cleared * @param lastIndex the previously found index * @return the result of the search */ private static int stringContains(final Vector<String> V, final char combiner, final StringBuffer buf, int lastIndex) { final String str=buf.toString().trim(); if(str.length()==0) return lastIndex; buf.setLength(0); switch (combiner) { case '&': lastIndex = strIndex(V, str, 0); return lastIndex; case '|': if (lastIndex >= 0) return lastIndex; return strIndex(V, str, 0); case '>': if (lastIndex < 0) return lastIndex; return strIndex(V, str, lastIndex + 1); case '<': { if (lastIndex < 0) return lastIndex; final int newIndex = strIndex(V, str, 0); if (newIndex < lastIndex) return newIndex; return -1; } } return -1; } /** * Main workhorse of the stringcontains mobprog function. * @param V parsed string to search * @param str the coded search function * @param index a 1-dim array of the index in the coded search str to start the search at * @param depth the number of close parenthesis to expect * @return the last index in the coded search function evaluated */ private static int stringContains(final Vector<String> V, final char[] str, final int[] index, final int depth) { final StringBuffer buf=new StringBuffer(""); int lastIndex=0; boolean quoteMode=false; char combiner='&'; for(int i=index[0];i<str.length;i++) { switch(str[i]) { case ')': if((depth>0)&&(!quoteMode)) { index[0]=i; return stringContains(V,combiner,buf,lastIndex); } buf.append(str[i]); break; case ' ': buf.append(str[i]); break; case '&': case '|': case '>': case '<': if(quoteMode) buf.append(str[i]); else { lastIndex=stringContains(V,combiner,buf,lastIndex); combiner=str[i]; } break; case '(': if(!quoteMode) { lastIndex=stringContains(V,combiner,buf,lastIndex); index[0]=i+1; final int newIndex=stringContains(V,str,index,depth+1); i=index[0]; switch(combiner) { case '&': if((lastIndex<0)||(newIndex<0)) lastIndex=-1; break; case '|': if(newIndex>=0) lastIndex=newIndex; break; case '>': if(newIndex<=lastIndex) lastIndex=-1; else lastIndex=newIndex; break; case '<': if((newIndex<0)||(newIndex>=lastIndex)) lastIndex=-1; else lastIndex=newIndex; break; } } else buf.append(str[i]); break; case '\"': quoteMode=(!quoteMode); break; case '\\': if(i<str.length-1) { buf.append(str[i+1]); i++; } break; default: if(Character.isLetter(str[i])) buf.append(Character.toLowerCase(str[i])); else buf.append(str[i]); break; } } return stringContains(V,combiner,buf,lastIndex); } /** * As the name implies, this is the implementation of the stringcontains mobprog function * @param str1 the string to search in * @param str2 the coded search expression * @return the index of the found string in the first string */ protected final static int stringContainsFunctionImpl(final String str1, final String str2) { final StringBuffer buf1=new StringBuffer(str1.toLowerCase()); for(int i=buf1.length()-1;i>=0;i--) { switch(buf1.charAt(i)) { case ' ': case '\"': case '`': break; case '\'': buf1.setCharAt(i, '`'); break; default: if(!Character.isLetterOrDigit(buf1.charAt(i))) buf1.setCharAt(i,' '); break; } } final StringBuffer buf2=new StringBuffer(str2.toLowerCase()); for(int i=buf2.length()-1;i>=0;i--) { switch(buf2.charAt(i)) { case ' ': case '\"': case '`': break; case '\'': buf2.setCharAt(i, '`'); break; default: if(!Character.isLetterOrDigit(buf2.charAt(i))) buf2.setCharAt(i,' '); break; } } final Vector<String> V=CMParms.parse(buf1.toString()); return stringContains(V,buf2.toString().toCharArray(),new int[]{0},0); } @Override public boolean eval(final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, Object[] tmp, final String[][] eval, final int startEval) { String[] tt=eval[0]; if(tmp == null) tmp = newObjs(); final List<Object> stack=new ArrayList<Object>(); for(int t=startEval;t<tt.length;t++) { if(tt[t].equals("(")) stack.add(tt[t]); else if(tt[t].equals(")")) { if(stack.size()>0) { if((!(stack.get(stack.size()-1) instanceof Boolean)) ||(stack.size()==1) ||(!(stack.get(stack.size()-2)).equals("("))) { logError(scripted,"EVAL","SYNTAX",") Format error: "+CMParms.toListString(tt)); return false; } final boolean b=((Boolean)stack.get(stack.size()-1)).booleanValue(); stack.remove(stack.size()-1); stack.remove(stack.size()-1); pushEvalBoolean(stack,b); } } else if(connH.containsKey(tt[t])) { Integer curr=connH.get(tt[t]); if((stack.size()>0) &&(stack.get(stack.size()-1) instanceof Integer)) { final int old=((Integer)stack.get(stack.size()-1)).intValue(); stack.remove(stack.size()-1); curr=Integer.valueOf(CONNECTOR_MAP[old][curr.intValue()]); } stack.add(curr); } else if(funcH.containsKey(tt[t])) { final Integer funcCode=funcH.get(tt[t]); if((t==tt.length-1) ||(!tt[t+1].equals("("))) { logError(scripted,"EVAL","SYNTAX","No ( for fuction "+tt[t]+": "+CMParms.toListString(tt)); return false; } t+=2; int tlen=0; while(((t+tlen)<tt.length)&&(!tt[t+tlen].equals(")"))) tlen++; if((t+tlen)==tt.length) { logError(scripted,"EVAL","SYNTAX","No ) for fuction "+tt[t-1]+": "+CMParms.toListString(tt)); return false; } tickStatus=Tickable.STATUS_MISC+funcCode.intValue(); final String funcParms=tt[t]; boolean returnable=false; switch(funcCode.intValue()) { case 1: // rand { String num=funcParms; if(num.endsWith("%")) num=num.substring(0,num.length()-1); final int arg=CMath.s_int(num); if(CMLib.dice().rollPercentage()<arg) returnable=true; else returnable=false; break; } case 2: // has { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HAS","Syntax",eval[0][t]); return returnable; } if(E==null) returnable=false; else { if((E instanceof MOB) &&(((MOB)E).findItem(arg2)!=null)) returnable = true; else if((E instanceof Room) &&(((Room)E).findItem(arg2)!=null)) returnable=true; else { final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { if(E2!=null) returnable=((MOB)E).isMine(E2); else returnable=(((MOB)E).findItem(arg2)!=null); } else if(E instanceof Item) returnable=CMLib.english().containsString(E.name(),arg2); else if(E instanceof Room) { if(E2 instanceof Item) returnable=((Room)E).isContent((Item)E2); else returnable=(((Room)E).findItem(null,arg2)!=null); } else returnable=false; } } break; } case 74: // hasnum { if (tlen == 1) tt = parseBits(eval, t, "cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=tt[t+2]; final String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((value.length()==0)||(item.length()==0)||(cmp.length()==0)) { logError(scripted,"HASNUM","Syntax",funcParms); return returnable; } Item I=null; int num=0; if(E==null) returnable=false; else if(E instanceof MOB) { final MOB M=(MOB)E; for(int i=0;i<M.numItems();i++) { I=M.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else if(E instanceof Room) { final Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM"); } else returnable=false; break; } case 67: // hastitle { if (tlen == 1) tt = parseBits(eval, t, "cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASTITLE","Syntax",funcParms); return returnable; } if(E instanceof MOB) { final MOB M=(MOB)E; returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2)); } else returnable=false; break; } case 3: // worn { if (tlen == 1) tt = parseBits(eval, t, "cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"WORN","Syntax",funcParms); return returnable; } if(E==null) returnable=false; else if(E instanceof MOB) returnable=(((MOB)E).fetchItem(null,Wearable.FILTER_WORNONLY,arg2)!=null); else if(E instanceof Item) returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Wearable.IN_INVENTORY))); else returnable=false; break; } case 4: // isnpc { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isMonster(); break; } case 87: // isbirthday { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else { final MOB mob=(MOB)E; if(mob.playerStats()==null) returnable=false; else { final TimeClock C=CMLib.time().localClock(mob.getStartRoom()); final int month=C.getMonth(); final int day=C.getDayOfMonth(); final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY]; final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH]; if((C.getYear()==mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_LASTYEARCELEBRATED]) &&((month==bmonth)&&(day==bday))) returnable=true; else returnable=false; } } break; } case 5: // ispc { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=!((MOB)E).isMonster(); break; } case 6: // isgood { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().isGood(P); break; } case 8: // isevil { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().isEvil(P); break; } case 9: // isneutral { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().isNeutral(P); break; } case 54: // isalive { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) returnable=true; else returnable=false; break; } case 58: // isable { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) returnable=((MOB)E).fetchExpertise(X.ID())!=null; else returnable=((MOB)E).findAbility(arg2)!=null; } else returnable=false; break; } case 112: // cansee { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(!(MP instanceof MOB)) returnable=false; else { final MOB M=(MOB)MP; final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().canBeSeenBy(P, M); } break; } case 113: // canhear { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(!(MP instanceof MOB)) returnable=false; else { final MOB M=(MOB)MP; final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else returnable=CMLib.flags().canBeHeardMovingBy(P, M); } break; } case 59: // isopen { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); returnable=false; if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } break; } case 60: // islocked { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); returnable=false; if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isLocked(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isLocked(); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isLocked(); } break; } case 10: // isfight { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=((MOB)E).isInCombat(); break; } case 11: // isimmort { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,CMSecurity.SecFlag.IMMORT); break; } case 12: // ischarmed { final String arg1=CMParms.cleanBit(funcParms); final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0; break; } case 15: // isfollow { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(((MOB)E).amFollowing()==null) returnable=false; else if(((MOB)E).amFollowing().location()!=lastKnownLocation) returnable=false; else returnable=true; break; } case 73: // isservant { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null)) returnable=false; else if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0)) returnable=false; else if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null) returnable=false; else returnable=true; break; } case 95: // isspeaking { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null)) returnable=false; else { final MOB TM=(MOB)E; final Language L=CMLib.utensils().getLanguageSpoken(TM); if((L!=null) &&(!L.ID().equalsIgnoreCase("Common")) &&(L.ID().equalsIgnoreCase(arg2)||L.Name().equalsIgnoreCase(arg2)||arg2.equalsIgnoreCase("any"))) returnable=true; else if(arg2.equalsIgnoreCase("common")||arg2.equalsIgnoreCase("none")) returnable=true; else returnable=false; } break; } case 55: // ispkill { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) returnable=false; else if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL)) returnable=true; else returnable=false; break; } case 7: // isname { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.english().containsString(E.name(),arg2); break; } case 56: // name { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME"); break; } case 75: // currency { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY"); break; } case 61: // strin { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2; if(tt[t+1].equals("$$r")) arg2=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(monster)); else arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final List<String> V=CMParms.parse(arg1.toUpperCase()); returnable=V.contains(arg2.toUpperCase()); break; } case 62: // callfunc { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); String found=null; boolean validFunc=false; final List<DVector> scripts=getScripts(); String trigger=null; String[] ttrigger=null; for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); ttrigger=(String[])script2.elementAt(0,2); if(getTriggerCode(trigger,ttrigger)==17) { final String fnamed= (ttrigger!=null) ?ttrigger[1] :CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) logError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else if(found!=null) returnable=!(found.trim().length()==0); else returnable=false; break; } case 14: // affected { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else { final Ability A=CMClass.findAbility(arg2); if(A!=null) arg2=A.ID(); returnable=(P.fetchEffect(arg2)!=null); } break; } case 69: // isbehave { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final PhysicalAgent P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P==null) returnable=false; else { final Behavior B=CMClass.findBehavior(arg2); if(B!=null) arg2=B.ID(); returnable=(P.fetchBehavior(arg2)!=null); } break; } case 70: // ipaddress { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster())) returnable=false; else returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS"); break; } case 28: // questwinner { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) arg1=E.Name(); if(arg2.equalsIgnoreCase("previous")) { returnable=true; final String quest=defaultQuestName(); if((quest!=null) &&(quest.length()>0)) { ScriptingEngine prevE=null; final List<ScriptingEngine> list=new LinkedList<ScriptingEngine>(); for(final Enumeration<ScriptingEngine> e = scripted.scripts();e.hasMoreElements();) list.add(e.nextElement()); for(final Enumeration<Behavior> b=scripted.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B instanceof ScriptingEngine) list.add((ScriptingEngine)B); } for(final ScriptingEngine engine : list) { if((engine!=null) &&(engine.defaultQuestName()!=null) &&(engine.defaultQuestName().length()>0)) { if(engine == this) { if(prevE != null) { final Quest Q=CMLib.quests().fetchQuest(prevE.defaultQuestName()); if(Q != null) returnable=Q.wasWinner(arg1); } break; } prevE=engine; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=Q.wasWinner(arg1); } break; } case 93: // questscripted { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[t+1]; if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { if(E!=null) { for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B instanceof ScriptingEngine) { final ScriptingEngine SE=(ScriptingEngine)B; if((SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } } } } } } else { final Quest Q=getQuest(arg2); returnable=false; if((Q!=null)&&(E!=null)) { for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();) { final Behavior B=b.nextElement(); if(B instanceof ScriptingEngine) { final ScriptingEngine SE=(ScriptingEngine)B; if((SE.defaultQuestName().equalsIgnoreCase(Q.name()))) returnable=true; } } } } break; } case 94: // questroom { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.getQuestRoomIndex(arg1)>=0); break; } case 114: // questarea { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { int num=1; Environmental E=Q.getQuestRoom(num); returnable = false; final Area parent=CMLib.map().getArea(arg1); if(parent == null) logError(scripted,"QUESTAREA","NoArea",funcParms); else while(E!=null) { final Area A=CMLib.map().areaLocation(E); if((A==parent)||(parent.isChild(A))||(A.isChild(parent))) { returnable=true; break; } num++; E=Q.getQuestRoom(num); } } break; } case 29: // questmob { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { if(E!=null) { if(Q.isObjectInUse(E)) { returnable=true; break; } } else if(Q.getQuestMobIndex(arg1)>=0) { returnable=true; break; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.getQuestMobIndex(arg1)>=0); } break; } case 31: // isquestmobalive { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { MOB M=null; if(CMath.s_int(arg1.trim())>0) M=Q.getQuestMob(CMath.s_int(arg1.trim())); else M=Q.getQuestMob(Q.getQuestMobIndex(arg1)); if(M!=null) { returnable=!M.amDead(); break; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else { MOB M=null; if(CMath.s_int(arg1.trim())>0) M=Q.getQuestMob(CMath.s_int(arg1.trim())); else M=Q.getQuestMob(Q.getQuestMobIndex(arg1)); if(M==null) returnable=false; else returnable=!M.amDead(); } } break; } case 111: // itemcount { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); if(arg2.length()==0) { logError(scripted,"ITEMCOUNT","Syntax",funcParms); return returnable; } if(E==null) returnable=false; else { int num=0; if(E instanceof Container) { num++; for(final Item I : ((Container)E).getContents()) num+=I.numberOfItems(); } else if(E instanceof Item) num=((Item)E).numberOfItems(); else if(E instanceof MOB) { for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Room) { for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Area) { for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();) { for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } } else returnable=false; returnable=simpleEval(scripted,""+num,arg3,arg2,"ITEMCOUNT"); } break; } case 32: // nummobsinarea { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; MaskingLibrary.CompiledZMask MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(arg1.equals("*")) num+=R.numInhabitants(); else { for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA"); break; } case 33: // nummobs { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; MaskingLibrary.CompiledZMask MASK=null; if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("=")))) { arg3=arg3.substring(4).trim(); arg3=arg3.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg3); } try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } catch (final NoSuchElementException nse) { } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS"); break; } case 34: // numracesinarea { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; Room R=null; MOB M=null; for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA"); break; } case 35: // numraces { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase(); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); int num=0; try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } } catch (final NoSuchElementException nse) { } returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES"); break; } case 30: // questobj { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final PhysicalAgent E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.equalsIgnoreCase("ALL")) { returnable=false; for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();) { final Quest Q=q.nextElement(); if(Q.running()) { if(E!=null) { if(Q.isObjectInUse(E)) { returnable=true; break; } } else if(Q.getQuestItemIndex(arg1)>=0) { returnable=true; break; } } } } else { final Quest Q=getQuest(arg2); if(Q==null) returnable=false; else returnable=(Q.getQuestItemIndex(arg1)>=0); } break; } case 85: // islike { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else returnable=CMLib.masking().maskCheck(arg2, E,false); break; } case 86: // strcontains { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); returnable=stringContainsFunctionImpl(arg1,arg2)>=0; break; } case 92: // isodd { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } returnable = isodd; break; } case 16: // hitprcnt { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"HITPRCNT","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); final int val1=(int)Math.round(hitPctD*100.0); returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT"); } break; } case 50: // isseason { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); returnable=false; if(monster.location()!=null) { arg1=arg1.toUpperCase(); for(final TimeClock.Season season : TimeClock.Season.values()) { if(season.toString().startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getTimeObj().getSeasonCode()==season)) { returnable=true; break; } } } break; } case 51: // isweather { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); returnable=false; if(monster.location()!=null) for(int a=0;a<Climate.WEATHER_DESCS.length;a++) { if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase()) &&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a)) { returnable = true; break; } } break; } case 57: // ismoon { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); returnable=false; if(monster.location()!=null) { if(arg1.length()==0) returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location()); else { arg1=arg1.toUpperCase(); for(final TimeClock.MoonPhase phase : TimeClock.MoonPhase.values()) { if(phase.toString().startsWith(arg1) &&(monster.location().getArea().getTimeObj().getMoonPhase(monster.location())==phase)) { returnable=true; break; } } } } break; } case 110: // ishour { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim(); if(monster.location()==null) returnable=false; else if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1))) returnable=true; else returnable=false; break; } case 38: // istime { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim(); if(monster.location()==null) returnable=false; else if(("daytime").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAY)) returnable=true; else if(("dawn").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAWN)) returnable=true; else if(("dusk").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DUSK)) returnable=true; else if(("nighttime").startsWith(arg1) &&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.NIGHT)) returnable=true; else if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1))) returnable=true; else returnable=false; break; } case 39: // isday { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 103: // ismonth { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getMonth()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 104: // isyear { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getYear()==CMath.s_int(arg1.trim()))) returnable=true; else returnable=false; break; } case 105: // isrlhour { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 106: // isrlday { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.DATE) == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 107: // isrlmonth { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.MONTH)+1 == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 108: // isrlyear { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(Calendar.getInstance().get(Calendar.YEAR) == CMath.s_int(arg1.trim())) returnable=true; else returnable=false; break; } case 45: // nummobsroom { if(tlen==1) { if(CMParms.numBits(funcParms)>2) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ else tt=parseBits(eval,t,"cr"); /* tt[t+0] */ } int num=0; int startbit=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); if(signH.containsKey(tt[t+1])) { String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); startbit++; if(!name.equalsIgnoreCase("*")) { num=0; MaskingLibrary.CompiledZMask MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { final boolean usePreCompiled = (name.equals(tt[t+0])); name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=usePreCompiled?CMLib.masking().getPreCompiledMask(name): CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { final MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } } else if(!signH.containsKey(tt[t+0])) { logError(scripted,"NUMMOBSROOM","Syntax","No SIGN found: "+funcParms); return returnable; } final String comp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit+1]); if(lastKnownLocation!=null) returnable=simpleEval(scripted,""+num,arg2,comp,"NUMMOBSROOM"); break; } case 63: // numpcsroom { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Room R=lastKnownLocation; if(R!=null) { int num=0; for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if((M!=null)&&(!M.isMonster())) num++; } returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSROOM"); } break; } case 79: // numpcsarea { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); if(lastKnownLocation!=null) { int num=0; for(final Session S : CMLib.sessions().localOnlineIterable()) { if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA"); } break; } case 115: // expertise { // mob ability type > 10 if(tlen==1) tt=parseBits(eval,t,"ccccr"); /* tt[t+0] */ final Physical P=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); final MOB M; if(P instanceof MOB) M=(MOB)P; else { returnable=false; logError(scripted,"EXPLORED","Unknown MOB",tt[t+0]); return returnable; } final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); Ability A=M.fetchAbility(arg2); if(A==null) A=CMClass.getAbility(arg2); if(A==null) { returnable=false; logError(scripted,"EXPLORED","Unknown Ability on MOB '"+M.name()+"'",tt[t+1]); return returnable; } final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim()); if(experFlag == null) { returnable=false; logError(scripted,"EXPLORED","Unknown Exper Flag",tt[t+2]); return returnable; } final int num=CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag); final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final String arg5=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+4]); if(lastKnownLocation!=null) { returnable=simpleEval(scripted,""+num,arg5,arg4,"EXPERTISE"); } break; } case 77: // explored { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) { logError(scripted,"EXPLORED","Unknown Code",whom); return returnable; } Area A=null; if(!where.equalsIgnoreCase("world")) { A=CMLib.map().getArea(where); if(A==null) { final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2 != null) A=CMLib.map().areaLocation(E2); } if(A==null) { logError(scripted,"EXPLORED","Unknown Area",where); return returnable; } } if(lastKnownLocation!=null) { int pct=0; final MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED"); } break; } case 72: // faction { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp); final Faction F=CMLib.factions().getFaction(arg1); if((E==null)||(!(E instanceof MOB))) { logError(scripted,"FACTION","Unknown Code",whom); return returnable; } if(F==null) { logError(scripted,"FACTION","Unknown Faction",arg1); return returnable; } final MOB M=(MOB)E; String value=null; if(!M.hasFaction(F.factionID())) value=""; else { final int myfac=M.fetchFaction(F.factionID()); if(CMath.isNumber(arg2.trim())) value=Integer.toString(myfac); else { final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),myfac); if(FR==null) value=""; else value=FR.name(); } } if(lastKnownLocation!=null) returnable=simpleEval(scripted,value,arg2,cmp,"FACTION"); break; } case 46: // numitemsroom { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); int ct=0; if(lastKnownLocation!=null) { for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } } returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM"); break; } case 47: //mobitem { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); MOB M=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else M=lastKnownLocation.fetchInhabitant(arg1.trim()); } Item which=null; int ct=1; if(M!=null) { for(int i=0;i<M.numItems();i++) { final Item I=M.getItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which = I; break; } ct++; } } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg3) ||CMLib.english().containsString(which.Name(),arg3) ||CMLib.english().containsString(which.displayText(),arg3)); break; } case 49: // hastattoo { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASTATTOO","Syntax",funcParms); break; } else if((E!=null)&&(E instanceof MOB)) returnable=(((MOB)E).findTattoo(arg2)!=null); else returnable=false; break; } case 109: // hastattootime { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String cmp=tt[t+2]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASTATTOO","Syntax",funcParms); break; } else if((E!=null)&&(E instanceof MOB)) { final Tattoo T=((MOB)E).findTattoo(arg2); if(T==null) returnable=false; else returnable=simpleEval(scripted,""+T.getTickDown(),arg3,cmp,"ISTATTOOTIME"); } else returnable=false; break; } case 99: // hasacctattoo { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"HASACCTATTOO","Syntax",funcParms); break; } else if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null)) returnable=((MOB)E).playerStats().getAccount().findTattoo(arg2)!=null; else returnable=false; break; } case 48: // numitemsmob { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); MOB which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); } int ct=0; if(which!=null) { for(int i=0;i<which.numItems();i++) { final Item I=which.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } } returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB"); break; } case 101: // numitemsshop { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); PhysicalAgent which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); if(which == null) which=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(which == null) which=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); } int ct=0; if(which!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next()) { ct++; } } } } returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSSHOP"); break; } case 100: // shopitem { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); } Environmental which=null; int ct=1; if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();) { final Environmental E=i.next(); if(ct==CMath.s_int(arg2.trim())) { which = E; break; } ct++; } } } if(which==null) returnable=false; else { returnable=(CMLib.english().containsString(which.name(),arg3) ||CMLib.english().containsString(which.Name(),arg3) ||CMLib.english().containsString(which.displayText(),arg3)); if(returnable) setShopPrice(shopHere,which,tmp); } } else returnable=false; break; } case 102: // shophas { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp); } returnable=false; if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { final Environmental E=shop.getStock(arg2.trim(), null); returnable = (E!=null); if(returnable) setShopPrice(shopHere,E,tmp); } } } break; } case 43: // roommob { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); Environmental which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1.trim()); } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 44: // roomitem { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); Environmental which=null; int ct=1; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg1.trim())) { which = I; break; } ct++; } } if(which==null) returnable=false; else returnable=(CMLib.english().containsString(which.name(),arg2) ||CMLib.english().containsString(which.Name(),arg2) ||CMLib.english().containsString(which.displayText(),arg2)); break; } case 36: // ishere { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((arg1.length()>0)&&(lastKnownLocation!=null)) returnable=((lastKnownLocation.findItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null)); else returnable=false; break; } case 17: // inroom { if(tlen==1) tt=parseSpecial3PartEval(eval,t); String comp="=="; Environmental E=monster; String arg2; if(signH.containsKey(tt[t+1])) { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=tt[t+1]; arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); } else arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); Room R=null; if(arg2.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { final Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM"); } break; } case 90: // inarea { if(tlen==1) tt=parseSpecial3PartEval(eval,t); String comp="=="; Environmental E=monster; String arg3; if(signH.containsKey(tt[t+1])) { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=tt[t+1]; arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); } else arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); Room R=null; if(arg3.startsWith("$")) R=CMLib.map().roomLocation(this.getArgumentItem(arg3,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) { try { final String lnAstr=(lastKnownLocation!=null)?lastKnownLocation.getArea().Name():null; if((lnAstr!=null)&&(lnAstr.equalsIgnoreCase(arg3))) R=lastKnownLocation; if(R==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { final Area A=a.nextElement(); if((A!=null)&&(A.Name().equalsIgnoreCase(arg3))) { if((lnAstr!=null) &&(lnAstr.equals(A.Name()))) R=lastKnownLocation; else if(!A.isProperlyEmpty()) R=A.getRandomProperRoom(); } } } if(R==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { final Area A=a.nextElement(); if((A!=null)&&(CMLib.english().containsString(A.Name(),arg3))) { if((lnAstr!=null) &&(lnAstr.equals(A.Name()))) R=lastKnownLocation; else if(!A.isProperlyEmpty()) R=A.getRandomProperRoom(); } } } } catch (final NoSuchElementException nse) { } } if(R==null) R=getRoom(arg3,lastKnownLocation); if((R!=null) &&(CMath.bset(R.getArea().flags(),Area.FLAG_INSTANCE_PARENT)) &&(lastKnownLocation!=null) &&(lastKnownLocation.getArea()!=R.getArea()) &&(CMath.bset(lastKnownLocation.getArea().flags(),Area.FLAG_INSTANCE_CHILD)) &&(CMLib.map().getModelArea(lastKnownLocation.getArea())==R.getArea())) R=lastKnownLocation; if(E==null) returnable=false; else { final Room R2=CMLib.map().roomLocation(E); if((R==null)&&((arg3.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA"); } break; } case 89: // isrecall { if(tlen==1) tt=parseSpecial3PartEval(eval,t); String comp="=="; Environmental E=monster; String arg2; if(signH.containsKey(tt[t+1])) { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); comp=tt[t+1]; arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); } else arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); Room R=null; if(arg2.startsWith("$")) R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(R==null) R=getRoom(arg2,lastKnownLocation); if(E==null) returnable=false; else { final Room R2=CMLib.map().getStartRoom(E); if((R==null)&&((arg2.length()==0)||(R2==null))) returnable=true; else if((R==null)||(R2==null)) returnable=false; else returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL"); } break; } case 37: // inlocale { if(tlen==1) { if(CMParms.numBits(funcParms)>1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ else { final int numBits=2; String[] parsed=null; if(CMParms.cleanBit(funcParms).equals(funcParms)) parsed=parseBits("'"+funcParms+"'"+CMStrings.repeat(" .",numBits-1),"cr"); else parsed=parseBits(funcParms+CMStrings.repeat(" .",numBits-1),"cr"); tt=insertStringArray(tt,parsed,t); eval[0]=tt; } } String arg2=null; Environmental E=monster; if(tt[t+1].equals(".")) arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); else { E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); } if(E==null) returnable=false; else if(arg2.length()==0) returnable=true; else { final Room R=CMLib.map().roomLocation(E); if(R==null) returnable=false; else if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0) returnable=true; else returnable=false; } break; } case 18: // sex { if(tlen==1) tt=parseBits(eval,t,"CcR"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; String arg3=tt[t+2]; if(CMath.isNumber(arg3.trim())) { switch(CMath.s_int(arg3.trim())) { case 0: arg3 = "NEUTER"; break; case 1: arg3 = "MALE"; break; case 2: arg3 = "FEMALE"; break; } } final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"SEX","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase(); if(arg2.equals("==")) returnable=arg3.startsWith(sex); else if(arg2.equals("!=")) returnable=!arg3.startsWith(sex); else { logError(scripted,"SEX","Syntax",funcParms); return returnable; } } break; } case 91: // datetime { if(tlen==1) tt=parseBits(eval,t,"Ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.trim()); if(index<0) logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) { String val=null; switch(index) { case 2: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 3: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth(); break; case 4: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getMonth(); break; case 5: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getYear(); break; default: val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay(); break; } returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME"); } break; } case 13: // stat { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"STAT","Syntax",funcParms); break; } if(E==null) returnable=false; else { final String val=getStatValue(E,arg2); if(val==null) { logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"STAT"); } break; } case 52: // gstat { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"GSTAT","Syntax",funcParms); break; } if(E==null) returnable=false; else { final String val=getGStatValue(E,arg2); if(val==null) { logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } if(arg3.equals("==")) returnable=val.equalsIgnoreCase(arg4); else if(arg3.equals("!=")) returnable=!val.equalsIgnoreCase(arg4); else returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT"); } break; } case 19: // position { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"POSITION","Syntax",funcParms); return returnable; } if(P==null) returnable=false; else { String sex="STANDING"; if(CMLib.flags().isSleeping(P)) sex="SLEEPING"; else if(CMLib.flags().isSitting(P)) sex="SITTING"; if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"POSITION","Syntax",funcParms); return returnable; } } break; } case 20: // level { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"LEVEL","Syntax",funcParms); return returnable; } if(P==null) returnable=false; else { final int val1=P.phyStats().level(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL"); } break; } case 80: // questpoints { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"QUESTPOINTS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getQuestPoint(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS"); } break; } case 83: // qvar { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Quest Q=getQuest(arg1); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"QVAR","Syntax",funcParms); return returnable; } if(Q==null) returnable=false; else returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR"); break; } case 84: // math { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); if(!CMath.isMathExpression(arg1)) { logError(scripted,"MATH","Syntax",funcParms); return returnable; } if(!CMath.isMathExpression(arg3)) { logError(scripted,"MATH","Syntax",funcParms); return returnable; } returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH"); break; } case 81: // trains { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"TRAINS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getTrains(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS"); } break; } case 82: // pracs { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"PRACS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getPractices(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS"); } break; } case 66: // clanrank { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLANRANK","Syntax",funcParms); return returnable; } if(!(E instanceof MOB)) returnable=false; else { int val1=-1; Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) val1=((MOB)E).getClanRole(C.clanID()).second.intValue(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK"); } break; } case 64: // deity { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"DEITY","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).getWorshipCharID(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { logError(scripted,"DEITY","Syntax",funcParms); return returnable; } } break; } case 68: // clandata { if(tlen==1) tt=parseBits(eval,t,"cccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLANDATA","Syntax",funcParms); return returnable; } String clanID=null; if((E!=null)&&(E instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); } else { clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); if((scripted instanceof MOB) &&(CMLib.clans().getClanAnyHost(clanID)==null)) { final List<Pair<Clan,Integer>> Cs=CMLib.clans().getClansByCategory((MOB)scripted, clanID); if((Cs!=null)&&(Cs.size()>0)) clanID=Cs.get(0).first.clanID(); } } final Clan C=CMLib.clans().findClan(clanID); if(C!=null) { if(!C.isStat(arg2)) logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); else { final String whichVal=C.getStat(arg2).trim(); if(CMath.isNumber(whichVal)&&CMath.isNumber(arg4.trim())) returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA"); else returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA"); } } break; } case 98: // clanqualifies { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"CLANQUALIFIES","Syntax",funcParms); return returnable; } final Clan C=CMLib.clans().findClan(arg2); if((C!=null)&&(E instanceof MOB)) { final MOB mob=(MOB)E; if(C.isOnlyFamilyApplicants() &&(!CMLib.clans().isFamilyOfMembership(mob,C.getMemberList()))) returnable=false; else if(CMLib.clans().getClansByCategory(mob, C.getCategory()).size()>CMProps.getMaxClansThisCategory(C.getCategory())) returnable=false; if(returnable && (!CMLib.masking().maskCheck(C.getBasicRequirementMask(), mob, true))) returnable=false; else if(returnable && (CMLib.masking().maskCheck(C.getAcceptanceSettings(),mob,true))) returnable=false; } else { logError(scripted,"CLANQUALIFIES","Unknown clan "+arg2+" or "+arg1+" is not a mob",funcParms); return returnable; } break; } case 65: // clan { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"CLAN","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { String clanID=""; Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); if(arg2.equals("==")) returnable=clanID.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!clanID.equalsIgnoreCase(arg3); else if(arg2.equals("in")) returnable=((MOB)E).getClanRole(arg3)!=null; else if(arg2.equals("notin")) returnable=((MOB)E).getClanRole(arg3)==null; else { logError(scripted,"CLAN","Syntax",funcParms); return returnable; } } break; } case 88: // mood { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()==0) { logError(scripted,"MOOD","Syntax",funcParms); return returnable; } if((P==null)||(!(P instanceof MOB))) returnable=false; else { final Ability moodA=P.fetchEffect("Mood"); if(moodA!=null) { final String sex=moodA.text(); if(arg2.equals("==")) returnable=sex.equalsIgnoreCase(arg3); else if(arg2.equals("!=")) returnable=!sex.equalsIgnoreCase(arg3); else { logError(scripted,"MOOD","Syntax",funcParms); return returnable; } } } break; } case 21: // class { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().displayClassName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } } break; } case 22: // baseclass { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"CLASS","Syntax",funcParms); return returnable; } } break; } case 23: // race { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"RACE","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().raceName().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"RACE","Syntax",funcParms); return returnable; } } break; } case 24: //racecat { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"RACECAT","Syntax",funcParms); return returnable; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase(); if(arg2.equals("==")) returnable=sex.startsWith(arg3); else if(arg2.equals("!=")) returnable=!sex.startsWith(arg3); else { logError(scripted,"RACECAT","Syntax",funcParms); return returnable; } } break; } case 25: // goldamt { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"GOLDAMT","Syntax",funcParms); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"GOLDAMT","Syntax",funcParms); return returnable; } returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT"); } break; } case 78: // exp { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"EXP","Syntax",funcParms); break; } if((E==null)||(!(E instanceof MOB))) returnable=false; else { final int val1=((MOB)E).getExperience(); returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP"); } break; } case 76: // value { if(tlen==1) tt=parseBits(eval,t,"cccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]); final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0)) { logError(scripted,"VALUE","Syntax",funcParms); break; } if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); break; } if(E==null) returnable=false; else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase())); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"VALUE","Syntax",funcParms); return returnable; } returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT"); } break; } case 26: // objtype { if(tlen==1) tt=parseBits(eval,t,"ccR"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"OBJTYPE","Syntax",funcParms); return returnable; } if(E==null) returnable=false; else { final String sex=CMClass.classID(E).toUpperCase(); if(arg2.equals("==")) returnable=sex.indexOf(arg3)>=0; else if(arg2.equals("!=")) returnable=sex.indexOf(arg3)<0; else { logError(scripted,"OBJTYPE","Syntax",funcParms); return returnable; } } break; } case 27: // var { if(tlen==1) tt=parseBits(eval,t,"cCcr"); /* tt[t+0] */ final String arg1=tt[t+0]; final String arg2=tt[t+1]; final String arg3=tt[t+2]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"VAR","Syntax",funcParms); return returnable; } final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut("(VAR "+arg1+" "+arg2 +"["+val+"] "+arg3+" "+arg4); if(arg3.equals("==")||arg3.equals("=")) returnable=val.equals(arg4); else if(arg3.equals("!=")||(arg3.contentEquals("<>"))) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { logError(scripted,"VAR","Syntax",funcParms); return returnable; } break; } case 41: // eval { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]); final String arg3=tt[t+1]; final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]); if(arg3.length()==0) { logError(scripted,"EVAL","Syntax",funcParms); return returnable; } if(arg3.equals("==")) returnable=val.equals(arg4); else if(arg3.equals("!=")) returnable=!val.equals(arg4); else if(arg3.equals(">")) returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim()); else if(arg3.equals("<")) returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim()); else if(arg3.equals(">=")) returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim()); else if(arg3.equals("<=")) returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim()); else { logError(scripted,"EVAL","Syntax",funcParms); return returnable; } break; } case 40: // number { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) { if(!Character.isDigit(val.charAt(i))) { isnumber = false; break; } } returnable=isnumber; break; } case 42: // randnum { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s.trim())) arg1=CMath.s_parseIntExpression(arg1s.trim()); else arg1=CMParms.parse(arg1s.trim()).size(); final String arg2=tt[t+1]; final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim(); int arg3=0; if(CMath.isMathExpression(arg3s.trim())) arg3=CMath.s_parseIntExpression(arg3s.trim()); else arg3=CMParms.parse(arg3s.trim()).size(); arg1=CMLib.dice().roll(1,arg1,0); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM"); break; } case 71: // rand0num { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim(); int arg1=0; if(CMath.isMathExpression(arg1s)) arg1=CMath.s_parseIntExpression(arg1s); else arg1=CMParms.parse(arg1s).size(); final String arg2=tt[t+1]; final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim(); int arg3=0; if(CMath.isMathExpression(arg3s)) arg3=CMath.s_parseIntExpression(arg3s); else arg3=CMParms.parse(arg3s).size(); arg1=CMLib.dice().roll(1,arg1,-1); returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM"); break; } case 53: // incontainer { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[t+1]; final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) returnable=false; else if(E instanceof MOB) { if(arg2.length()==0) returnable=(((MOB)E).riding()==null); else if(E2!=null) returnable=(((MOB)E).riding()==E2); else returnable=false; } else if(E instanceof Item) { if(arg2.length()==0) returnable=(((Item)E).container()==null); else if(E2!=null) returnable=(((Item)E).container()==E2); else returnable=false; } else returnable=false; break; } case 96: // iscontents { if(tlen==1) tt=parseBits(eval,t,"cr"); /* tt[t+0] */ final String arg1=tt[t+0]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]); if(E==null) returnable=false; else if(E instanceof Rideable) { if(arg2.length()==0) returnable=((Rideable)E).numRiders()==0; else returnable=CMLib.english().fetchEnvironmental(new XVector<Rider>(((Rideable)E).riders()), arg2, false)!=null; } if(E instanceof Container) { if(arg2.length()==0) returnable=!((Container)E).hasContent(); else returnable=CMLib.english().fetchEnvironmental(((Container)E).getDeepContents(), arg2, false)!=null; } else returnable=false; break; } case 97: // wornon { if(tlen==1) tt=parseBits(eval,t,"ccr"); /* tt[t+0] */ final String arg1=tt[t+0]; final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]); final String arg3=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+2]); if((arg2.length()==0)||(arg3.length()==0)) { logError(scripted,"WORNON","Syntax",funcParms); return returnable; } final int wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim()); returnable=false; if(wornLoc<0) logError(scripted,"EVAL","BAD WORNON LOCATION",arg2); else if(E instanceof MOB) { final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0); if((items.size()==0)&&(arg3.length()==0)) returnable=true; else returnable = CMLib.english().fetchEnvironmental(items, arg3, false)!=null; } break; } default: logError(scripted,"EVAL","UNKNOWN",CMParms.toListString(tt)); return false; } pushEvalBoolean(stack,returnable); while((t<tt.length)&&(!tt[t].equals(")"))) t++; } else { logError(scripted,"EVAL","SYNTAX","BAD CONJUCTOR "+tt[t]+": "+CMParms.toListString(tt)); return false; } } if((stack.size()!=1) ||(!(stack.get(0) instanceof Boolean))) { logError(scripted,"EVAL","SYNTAX","Unmatched (: "+CMParms.toListString(tt)); return false; } return ((Boolean)stack.get(0)).booleanValue(); } protected void setShopPrice(final ShopKeeper shopHere, final Environmental E, final Object[] tmp) { if(shopHere instanceof MOB) { final ShopKeeper.ShopPrice price = CMLib.coffeeShops().sellingPrice((MOB)shopHere, null, E, shopHere, shopHere.getShop(), true); if(price.experiencePrice>0) tmp[SPECIAL_9SHOPHASPRICE] = price.experiencePrice+"xp"; else if(price.questPointPrice>0) tmp[SPECIAL_9SHOPHASPRICE] = price.questPointPrice+"qp"; else tmp[SPECIAL_9SHOPHASPRICE] = CMLib.beanCounter().abbreviatedPrice((MOB)shopHere,price.absoluteGoldPrice); } } @Override public String functify(final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp, final String evaluable) { if(evaluable.length()==0) return ""; final StringBuffer results = new StringBuffer(""); final int y=evaluable.indexOf('('); final int z=evaluable.indexOf(')',y); final String preFab=(y>=0)?evaluable.substring(0,y).toUpperCase().trim():""; Integer funcCode=funcH.get(preFab); if(funcCode==null) funcCode=Integer.valueOf(0); if((y<0)||(z<y)) { logError(scripted,"()","Syntax",evaluable); return ""; } else { tickStatus=Tickable.STATUS_MISC2+funcCode.intValue(); final String funcParms=evaluable.substring(y+1,z).trim(); switch(funcCode.intValue()) { case 1: // rand { results.append(CMLib.dice().rollPercentage()); break; } case 2: // has { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); ArrayList<Item> choices=new ArrayList<Item>(); if(E==null) choices=new ArrayList<Item>(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).numItems();i++) { final Item I=((MOB)E).getItem(i); if((I!=null)&&(I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null)) choices.add(I); } } else if(E instanceof Item) { if(E instanceof Container) choices.addAll(((Container)E).getDeepContents()); else choices.add((Item)E); } else if(E instanceof Room) { for(int i=0;i<((Room)E).numItems();i++) { final Item I=((Room)E).getItem(i); if((I!=null)&&(I.container()==null)) choices.add(I); } } if(choices.size()>0) results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name()); break; } case 74: // hasnum { final String arg1=CMParms.getCleanBit(funcParms,0); final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1)); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((item.length()==0)||(E==null)) logError(scripted,"HASNUM","Syntax",funcParms); else { Item I=null; int num=0; if(E instanceof MOB) { final MOB M=(MOB)E; for(int i=0;i<M.numItems();i++) { I=M.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } else if(E instanceof Item) { num=CMLib.english().containsString(E.name(),item)?1:0; results.append(""+num); } else if(E instanceof Room) { final Room R=(Room)E; for(int i=0;i<R.numItems();i++) { I=R.getItem(i); if(I==null) break; if((item.equalsIgnoreCase("all")) ||(CMLib.english().containsString(I.Name(),item))) num++; } results.append(""+num); } } break; } case 3: // worn { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); ArrayList<Item> choices=new ArrayList<Item>(); if(E==null) choices=new ArrayList<Item>(); else if(E instanceof MOB) { for(int i=0;i<((MOB)E).numItems();i++) { final Item I=((MOB)E).getItem(i); if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null)) choices.add(I); } } else if((E instanceof Item)&&(!(((Item)E).amWearingAt(Wearable.IN_INVENTORY)))) { if(E instanceof Container) choices.addAll(((Container)E).getDeepContents()); else choices.add((Item)E); } if(choices.size()>0) results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name()); break; } case 4: // isnpc case 5: // ispc results.append("[unimplemented function]"); break; case 87: // isbirthday { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null)) { final MOB mob=(MOB)E; final TimeClock C=CMLib.time().localClock(mob.getStartRoom()); final int day=C.getDayOfMonth(); final int month=C.getMonth(); int year=C.getYear(); final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY]; final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH]; if((month>bmonth)||((month==bmonth)&&(day>bday))) year++; final StringBuffer timeDesc=new StringBuffer(""); if(C.getDaysInWeek()>0) { long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth(); x=x+((long)(bmonth-1))*((long)C.getDaysInMonth()); x=x+bmonth; timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", "); } timeDesc.append("the "+bday+CMath.numAppendage(bday)); timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]); if(C.getYearNames().length>0) timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year)); results.append(timeDesc.toString()); } break; } case 6: // isgood { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) { final Faction.FRange FR=CMLib.factions().getRange(CMLib.factions().getAlignmentID(),((MOB)E).fetchFaction(CMLib.factions().getAlignmentID())); if(FR!=null) results.append(FR.name()); else results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID())); } break; } case 8: // isevil { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(CMLib.flags().getAlignmentName(E).toLowerCase()); break; } case 9: // isneutral { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))) results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID())); break; } case 11: // isimmort results.append("[unimplemented function]"); break; case 54: // isalive { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) results.append(((MOB)E).healthText(null)); else if(E!=null) results.append(E.name()+" is dead."); break; } case 58: // isable { final String arg1=CMParms.getCleanBit(funcParms,0); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead())) { final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true); if(X!=null) { final Pair<String,Integer> s=((MOB)E).fetchExpertise(X.ID()); if(s!=null) results.append(s.getKey()+((s.getValue()!=null)?s.getValue().toString():"")); } else { final Ability A=((MOB)E).findAbility(arg2); if(A!=null) results.append(""+A.proficiency()); } } break; } case 59: // isopen { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); boolean returnable=false; if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) returnable=((Container)E).isOpen(); else if((E!=null)&&(E instanceof Exit)) returnable=((Exit)E).isOpen(); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) returnable= E.isOpen(); } results.append(""+returnable); break; } case 60: // islocked { final String arg1=CMParms.cleanBit(funcParms); final int dir=CMLib.directions().getGoodDirectionCode(arg1); if(dir<0) { final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof Container)) results.append(((Container)E).keyName()); else if((E!=null)&&(E instanceof Exit)) results.append(((Exit)E).keyName()); } else if(lastKnownLocation!=null) { final Exit E=lastKnownLocation.getExitInDir(dir); if(E!=null) results.append(E.keyName()); } break; } case 62: // callfunc { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); String found=null; boolean validFunc=false; final List<DVector> scripts=getScripts(); String trigger=null; String[] ttrigger=null; for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); ttrigger=(String[])script2.elementAt(0,2); if(getTriggerCode(trigger,ttrigger)==17) { final String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(arg1)) { validFunc=true; found= execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2), tmp); if(found==null) found=""; break; } } } if(!validFunc) logError(scripted,"CALLFUNC","Unknown","Function: "+arg1); else results.append(found); break; } case 61: // strin { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); final List<String> V=CMParms.parse(arg1.toUpperCase()); results.append(V.indexOf(arg2.toUpperCase())); break; } case 55: // ispkill { final String arg1=CMParms.cleanBit(funcParms); final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||(!(E instanceof MOB))) results.append("false"); else if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL)) results.append("true"); else results.append("false"); break; } case 10: // isfight { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat())) results.append(((MOB)E).getVictim().name()); break; } case 12: // ischarmed { final String arg1=CMParms.cleanBit(funcParms); final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final List<Ability> V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING); for(int v=0;v<V.size();v++) results.append((V.get(v).name())+" "); } break; } case 15: // isfollow { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null) &&(((MOB)E).amFollowing().location()==lastKnownLocation)) results.append(((MOB)E).amFollowing().name()); break; } case 73: // isservant { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0)) results.append(((MOB)E).getLiegeID()); break; } case 95: // isspeaking { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final MOB TM=(MOB)E; final Language L=CMLib.utensils().getLanguageSpoken(TM); if(L!=null) results.append(L.Name()); else results.append("Common"); } break; } case 56: // name case 7: // isname { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(E.name()); break; } case 75: // currency { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(CMLib.beanCounter().getCurrency(E)); break; } case 14: // affected { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E instanceof Physical)&&(((Physical)E).numEffects()>0)) results.append(((Physical)E).effects().nextElement().name()); break; } case 69: // isbehave { final String arg1=CMParms.cleanBit(funcParms); final PhysicalAgent E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if(B!=null) results.append(B.ID()+" "); } } break; } case 70: // ipaddress { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) results.append(((MOB)E).session().getAddress()); break; } case 28: // questwinner { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) { for(int q=0;q<CMLib.quests().numQuests();q++) { final Quest Q=CMLib.quests().fetchQuest(q); if((Q!=null)&&(Q.wasWinner(E.Name()))) results.append(Q.name()+" "); } } break; } case 93: // questscripted { final String arg1=CMParms.cleanBit(funcParms); final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster())) { for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();) { final ScriptingEngine SE=e.nextElement(); if((SE!=null)&&(SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0)) { final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName()); if(Q!=null) results.append(Q.name()+" "); else results.append(SE.defaultQuestName()+" "); } } for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();) { final Behavior B=e.nextElement(); if(B instanceof ScriptingEngine) { final ScriptingEngine SE=(ScriptingEngine)B; if((SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0)) { final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName()); if(Q!=null) results.append(Q.name()+" "); else results.append(SE.defaultQuestName()+" "); } } } } break; } case 30: // questobj { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0)) questName = this.defaultQuestName(); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestItem(num); while(E!=null) { if(E.Name().indexOf(' ')>=0) list.append("\""+E.Name()+"\" "); else list.append(E.Name()+" "); num++; E=Q.getQuestItem(num); } results.append(list.toString().trim()); break; } case 94: // questroom { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestRoom(num); while(E!=null) { final String roomID=CMLib.map().getExtendedRoomID((Room)E); if(roomID.indexOf(' ')>=0) list.append("\""+roomID+"\" "); else list.append(roomID+" "); num++; E=Q.getQuestRoom(num); } results.append(list.toString().trim()); break; } case 114: // questarea { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestRoom(num); while(E!=null) { final String areaName=CMLib.map().areaLocation(E).name(); if(list.indexOf(areaName)<0) { if(areaName.indexOf(' ')>=0) list.append("\""+areaName+"\" "); else list.append(areaName+" "); } num++; E=Q.getQuestRoom(num); } results.append(list.toString().trim()); break; } case 29: // questmob { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0)) questName=this.defaultQuestName(); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; Environmental E=Q.getQuestMob(num); while(E!=null) { if(E.Name().indexOf(' ')>=0) list.append("\""+E.Name()+"\" "); else list.append(E.Name()+" "); num++; E=Q.getQuestMob(num); } results.append(list.toString().trim()); break; } case 31: // isquestmobalive { String questName=CMParms.cleanBit(funcParms); questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName); break; } final StringBuffer list=new StringBuffer(""); int num=1; MOB E=Q.getQuestMob(num); while(E!=null) { if(CMLib.flags().isInTheGame(E,true)) { if(E.Name().indexOf(' ')>=0) list.append("\""+E.Name()+"\" "); else list.append(E.Name()+" "); } num++; E=Q.getQuestMob(num); } results.append(list.toString().trim()); break; } case 49: // hastattoo { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { for(final Enumeration<Tattoo> t = ((MOB)E).tattoos();t.hasMoreElements();) results.append(t.nextElement().ID()).append(" "); } break; } case 109: // hastattootime { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final Tattoo T=((MOB)E).findTattoo(arg2); if(T!=null) results.append(T.getTickDown()); } break; } case 99: // hasacctattoo { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null)) { for(final Enumeration<Tattoo> t = ((MOB)E).playerStats().getAccount().tattoos();t.hasMoreElements();) results.append(t.nextElement().ID()).append(" "); } break; } case 32: // nummobsinarea { String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); int num=0; MaskingLibrary.CompiledZMask MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(arg1.equals("*")) num+=R.numInhabitants(); else { for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } results.append(num); break; } case 33: // nummobs { int num=0; String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); MaskingLibrary.CompiledZMask MASK=null; if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("=")))) { arg1=arg1.substring(4).trim(); arg1=arg1.substring(1).trim(); MASK=CMLib.masking().maskCompile(arg1); } try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.name(),arg1)) num++; } } } catch(final NoSuchElementException nse) { } results.append(num); break; } case 34: // numracesinarea { int num=0; final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Room R=null; MOB M=null; for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } results.append(num); break; } case 35: // numraces { int num=0; final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Room R=null; MOB M=null; try { for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { R=e.nextElement(); for(int m=0;m<R.numInhabitants();m++) { M=R.fetchInhabitant(m); if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1))) num++; } } } catch (final NoSuchElementException nse) { } results.append(num); break; } case 112: // cansee { break; } case 113: // canhear { break; } case 111: // itemcount { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { int num=0; if(E instanceof Container) { num++; for(final Item I : ((Container)E).getContents()) num+=I.numberOfItems(); } else if(E instanceof Item) num=((Item)E).numberOfItems(); else if(E instanceof MOB) { for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Room) { for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } else if(E instanceof Area) { for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();) { for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();) num += i.nextElement().numberOfItems(); } } results.append(""+num); } break; } case 16: // hitprcnt { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints()); final int val1=(int)Math.round(hitPctD*100.0); results.append(val1); } break; } case 50: // isseason { if(monster.location()!=null) results.append(monster.location().getArea().getTimeObj().getSeasonCode().toString()); break; } case 51: // isweather { if(monster.location()!=null) results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]); break; } case 57: // ismoon { if(monster.location()!=null) results.append(monster.location().getArea().getTimeObj().getMoonPhase(monster.location()).toString()); break; } case 38: // istime { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getTODCode().getDesc().toLowerCase()); break; } case 110: // ishour { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getHourOfDay()); break; } case 103: // ismonth { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getMonth()); break; } case 104: // isyear { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().getTimeObj().getYear()); break; } case 105: // isrlhour { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); break; } case 106: // isrlday { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.DATE)); break; } case 107: // isrlmonth { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.MONTH)); break; } case 108: // isrlyear { if(lastKnownLocation!=null) results.append(Calendar.getInstance().get(Calendar.YEAR)); break; } case 39: // isday { if(lastKnownLocation!=null) results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth()); break; } case 43: // roommob { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Environmental which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1.trim()); if(which!=null) { final List<MOB> list=new ArrayList<MOB>(); for(int i=0;i<lastKnownLocation.numInhabitants();i++) { final MOB M=lastKnownLocation.fetchInhabitant(i); if(M!=null) list.add(M); } results.append(CMLib.english().getContextName(list,which)); } } break; } case 44: // roomitem { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); Environmental which=null; int ct=1; if(lastKnownLocation!=null) { final List<Item> list=new ArrayList<Item>(); for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) { list.add(I); if(ct==CMath.s_int(arg1.trim())) { which = I; break; } ct++; } } if(which!=null) results.append(CMLib.english().getContextName(list,which)); } break; } case 45: // nummobsroom { int num=0; if(lastKnownLocation!=null) { num=lastKnownLocation.numInhabitants(); String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if((name.length()>0)&&(!name.equalsIgnoreCase("*"))) { num=0; MaskingLibrary.CompiledZMask MASK=null; if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("=")))) { name=name.substring(4).trim(); name=name.substring(1).trim(); MASK=CMLib.masking().maskCompile(name); } for(int i=0;i<lastKnownLocation.numInhabitants();i++) { final MOB M=lastKnownLocation.fetchInhabitant(i); if(M==null) continue; if(MASK!=null) { if(CMLib.masking().maskCheck(MASK,M,true)) num++; } else if(CMLib.english().containsString(M.Name(),name) ||CMLib.english().containsString(M.displayText(),name)) num++; } } } results.append(""+num); break; } case 63: // numpcsroom { final Room R=lastKnownLocation; if(R!=null) { int num=0; for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); if((M!=null)&&(!M.isMonster())) num++; } results.append(""+num); } break; } case 115: // expertise { // mob ability type > 10 final String arg1=CMParms.getCleanBit(funcParms,0); final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final MOB M; if(P instanceof MOB) { M=(MOB)P; final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1)); Ability A=M.fetchAbility(arg2); if(A==null) A=CMClass.getAbility(arg2); if(A!=null) { final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,1)); final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim()); if(experFlag != null) results.append(""+CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag)); } } break; } case 79: // numpcsarea { if(lastKnownLocation!=null) { int num=0; for(final Session S : CMLib.sessions().localOnlineIterable()) { if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea())) num++; } results.append(""+num); } break; } case 77: // explored { final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1)); final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { Area A=null; if(!where.equalsIgnoreCase("world")) { A=CMLib.map().getArea(where); if(A==null) { final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E2!=null) A=CMLib.map().areaLocation(E2); } } if((lastKnownLocation!=null) &&((A!=null)||(where.equalsIgnoreCase("world")))) { int pct=0; final MOB M=(MOB)E; if(M.playerStats()!=null) pct=M.playerStats().percentVisited(M,A); results.append(""+pct); } } break; } case 72: // faction { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBit(funcParms,0); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); final Faction F=CMLib.factions().getFaction(arg2); if(F==null) logError(scripted,"FACTION","Unknown Faction",arg1); else if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID()))) { final int value=((MOB)E).fetchFaction(F.factionID()); final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),value); if(FR!=null) results.append(FR.name()); } break; } case 46: // numitemsroom { int ct=0; if(lastKnownLocation!=null) for(int i=0;i<lastKnownLocation.numItems();i++) { final Item I=lastKnownLocation.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } results.append(""+ct); break; } case 47: //mobitem { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0)); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); MOB M=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else M=lastKnownLocation.fetchInhabitant(arg1.trim()); } Item which=null; int ct=1; if(M!=null) { for(int i=0;i<M.numItems();i++) { final Item I=M.getItem(i); if((I!=null)&&(I.container()==null)) { if(ct==CMath.s_int(arg2.trim())) { which = I; break; } ct++; } } } if(which!=null) results.append(which.name()); break; } case 100: // shopitem { final String arg1raw=CMParms.getCleanBit(funcParms,0); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp); } Environmental which=null; int ct=1; if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++) { final Environmental E=i.next(); if(ct==CMath.s_int(arg2.trim())) { which = E; setShopPrice(shopHere,E,tmp); break; } } } } } if(which!=null) results.append(which.name()); break; } case 101: // numitemsshop { final String arg1raw = CMParms.cleanBit(funcParms); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw); PhysicalAgent which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); if(which == null) which=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(which == null) which=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp); } int ct=0; if(which!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next()) { ct++; } } } } results.append(""+ct); break; } case 102: // shophas { final String arg1raw=CMParms.cleanBit(funcParms); final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw); PhysicalAgent where=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else where=lastKnownLocation.fetchInhabitant(arg1.trim()); if(where == null) where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp); if(where == null) where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp); } if(where!=null) { ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where); if((shopHere == null)&&(scripted instanceof Item)) shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner()); if((shopHere == null)&&(scripted instanceof MOB)) shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location()); if(shopHere == null) shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(shopHere!=null) { final CoffeeShop shop = shopHere.getShop(); if(shop != null) { int ct=0; for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next()) ct++; final int which=CMLib.dice().roll(1, ct, -1); ct=0; for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++) { final Environmental E=i.next(); if(which == ct) { results.append(E.Name()); setShopPrice(shopHere,E,tmp); break; } } } } } break; } case 48: // numitemsmob { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); MOB which=null; if(lastKnownLocation!=null) { if(CMath.isInteger(arg1.trim())) which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1); else which=lastKnownLocation.fetchInhabitant(arg1); } int ct=0; if(which!=null) { for(int i=0;i<which.numItems();i++) { final Item I=which.getItem(i); if((I!=null)&&(I.container()==null)) ct++; } } results.append(""+ct); break; } case 36: // ishere { if(lastKnownLocation!=null) results.append(lastKnownLocation.getArea().name()); break; } case 17: // inroom { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(CMLib.map().getExtendedRoomID(lastKnownLocation)); else results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E))); break; } case 90: // inarea { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((E==null)||arg1.length()==0) results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name()); else { final Room R=CMLib.map().roomLocation(E); results.append(R==null?"Nowhere":R.getArea().Name()); } break; } case 89: // isrecall { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E))); break; } case 37: // inlocale { final String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); if(parms.trim().length()==0) { if(lastKnownLocation!=null) results.append(lastKnownLocation.name()); } else { final Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final Room R=CMLib.map().roomLocation(E); if(R!=null) results.append(R.name()); } } break; } case 18: // sex { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().genderName()); break; } case 91: // datetime { final String arg1=CMParms.getCleanBit(funcParms,0); final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim()); if(index<0) logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name()); else if(CMLib.map().areaLocation(scripted)!=null) { switch(index) { case 2: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 3: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth()); break; case 4: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth()); break; case 5: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear()); break; default: results.append(CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay()); break; } } break; } case 13: // stat { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final String val=getStatValue(E,arg2); if(val==null) { logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 52: // gstat { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final String val=getGStatValue(E,arg2); if(val==null) { logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name()); break; } results.append(val); break; } break; } case 19: // position { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P!=null) { final String sex; if(CMLib.flags().isSleeping(P)) sex="SLEEPING"; else if(CMLib.flags().isSitting(P)) sex="SITTING"; else sex="STANDING"; results.append(sex); break; } break; } case 20: // level { final String arg1=CMParms.cleanBit(funcParms); final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(P!=null) results.append(P.phyStats().level()); break; } case 80: // questpoints { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getQuestPoint()); break; } case 83: // qvar { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); if((arg1.length()!=0)&&(arg2.length()!=0)) { final Quest Q=getQuest(arg1); if(Q!=null) results.append(Q.getStat(arg2)); } break; } case 84: // math { final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)); results.append(""+Math.round(CMath.s_parseMathExpression(arg1))); break; } case 85: // islike { final String arg1=CMParms.cleanBit(funcParms); results.append(CMLib.masking().maskDesc(arg1)); break; } case 86: // strcontains { results.append("[unimplemented function]"); break; } case 81: // trains { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getTrains()); break; } case 92: // isodd { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(funcParms)).trim(); boolean isodd = false; if( CMath.isLong( val ) ) { isodd = (CMath.s_long(val) %2 == 1); } if( isodd ) { results.append( CMath.s_long( val.trim() ) ); } break; } case 82: // pracs { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) results.append(((MOB)E).getPractices()); break; } case 68: // clandata { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((E!=null)&&(E instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); } else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1); final Clan C=CMLib.clans().findClan(clanID); if(C!=null) { if(!C.isStat(arg2)) logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable."); else results.append(C.getStat(arg2)); } break; } case 98: // clanqualifies { final String arg1=CMParms.cleanBit(funcParms); Clan C=CMLib.clans().getClan(arg1); if(C==null) C=CMLib.clans().findClan(arg1); if(C!=null) { if(C.getAcceptanceSettings().length()>0) results.append(CMLib.masking().maskDesc(C.getAcceptanceSettings())); if(C.getBasicRequirementMask().length()>0) results.append(CMLib.masking().maskDesc(C.getBasicRequirementMask())); if(C.isOnlyFamilyApplicants()) results.append("Must belong to the family."); final int total=CMProps.getMaxClansThisCategory(C.getCategory()); if(C.getCategory().length()>0) results.append("May belong to only "+total+" "+C.getCategory()+" clan. "); else results.append("May belong to only "+total+" standard clan. "); } break; } case 67: // hastitle { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0)); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)) { final MOB M=(MOB)E; results.append(M.playerStats().getActiveTitle()); } break; } case 66: // clanrank { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); Clan C=null; if(E instanceof MOB) { C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; } else C=CMLib.clans().findClan(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1)); if(C!=null) { final Pair<Clan,Integer> p=((MOB)E).getClanRole(C.clanID()); if(p!=null) results.append(p.second.toString()); } break; } case 21: // class { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().displayClassName()); break; } case 64: // deity { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { final String sex=((MOB)E).getWorshipCharID(); results.append(sex); } break; } case 65: // clan { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)E); if(C==null) C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null; if(C!=null) results.append(C.clanID()); } break; } case 88: // mood { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { final Ability moodA=((MOB)E).fetchEffect("Mood"); if(moodA!=null) results.append(CMStrings.capitalizeAndLower(moodA.text())); } break; } case 22: // baseclass { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getCurrentClass().baseClass()); break; } case 23: // race { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().raceName()); break; } case 24: //racecat { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((E!=null)&&(E instanceof MOB)) results.append(((MOB)E).charStats().getMyRace().racialCategory()); break; } case 25: // goldamt { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted))); else if(E instanceof Coins) val1=(int)Math.round(((Coins)E).getTotalValue()); else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"GOLDAMT","Syntax",funcParms); return results.toString(); } results.append(val1); } break; } case 78: // exp { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=((MOB)E).getExperience(); results.append(val1); } break; } case 76: // value { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0); if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase())) { logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency."); return results.toString(); } final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E==null) results.append(false); else { int val1=0; if(E instanceof MOB) val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2)); else if(E instanceof Coins) { if(((Coins)E).getCurrency().equalsIgnoreCase(arg2)) val1=(int)Math.round(((Coins)E).getTotalValue()); } else if(E instanceof Item) val1=((Item)E).value(); else { logError(scripted,"GOLDAMT","Syntax",funcParms); return results.toString(); } results.append(val1); } break; } case 26: // objtype { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { final String sex=CMClass.classID(E).toLowerCase(); results.append(sex); } break; } case 53: // incontainer { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(((MOB)E).riding()!=null) results.append(((MOB)E).riding().Name()); } else if(E instanceof Item) { if(((Item)E).riding()!=null) results.append(((Item)E).riding().Name()); else if(((Item)E).container()!=null) results.append(((Item)E).container().Name()); else if(E instanceof Container) { final List<Item> V=((Container)E).getDeepContents(); for(int v=0;v<V.size();v++) results.append("\""+V.get(v).Name()+"\" "); } } } break; } case 27: // var { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase(); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); results.append(val); break; } case 41: // eval results.append("[unimplemented function]"); break; case 40: // number { final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim(); boolean isnumber=(val.length()>0); for(int i=0;i<val.length();i++) { if(!Character.isDigit(val.charAt(i))) { isnumber = false; break; } } if(isnumber) results.append(CMath.s_long(val.trim())); break; } case 42: // randnum { final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,0)); break; } case 71: // rand0num { final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase(); int arg1=0; if(CMath.isMathExpression(arg1String)) arg1=CMath.s_parseIntExpression(arg1String.trim()); else arg1=CMParms.parse(arg1String.trim()).size(); results.append(CMLib.dice().roll(1,arg1,-1)); break; } case 96: // iscontents { final String arg1=CMParms.cleanBit(funcParms); final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof Rideable) { for(final Enumeration<Rider> r=((Rideable)E).riders();r.hasMoreElements();) results.append(CMParms.quoteIfNecessary(r.nextElement().name())).append(" "); } if(E instanceof Container) { for (final Item item : ((Container)E).getDeepContents()) results.append(CMParms.quoteIfNecessary(item.name())).append(" "); } break; } case 97: // wornon { final String arg1=CMParms.getCleanBit(funcParms,0); final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase(); final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp); int wornLoc=-1; if(arg2.length()>0) wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim()); if(wornLoc<0) logError(scripted,"EVAL","BAD WORNON LOCATION",arg2); else if(E instanceof MOB) { final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0); for(final Item item : items) results.append(CMParms.quoteIfNecessary(item.name())).append(" "); } break; } default: logError(scripted,"Unknown Val",preFab,evaluable); return results.toString(); } } return results.toString(); } protected MOB getRandPC(final MOB monster, final Object[] tmp, final Room room) { if((tmp[SPECIAL_RANDPC]==null)||(tmp[SPECIAL_RANDPC]==monster)) { MOB M=null; if(room!=null) { final List<MOB> choices = new ArrayList<MOB>(); for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if((!M.isMonster())&&(M!=monster)) { final HashSet<MOB> seen=new HashSet<MOB>(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } choices.add(M); } } if(choices.size() > 0) tmp[SPECIAL_RANDPC] = choices.get(CMLib.dice().roll(1,choices.size(),-1)); } } return (MOB)tmp[SPECIAL_RANDPC]; } protected MOB getRandAnyone(final MOB monster, final Object[] tmp, final Room room) { if((tmp[SPECIAL_RANDANYONE]==null)||(tmp[SPECIAL_RANDANYONE]==monster)) { MOB M=null; if(room!=null) { final List<MOB> choices = new ArrayList<MOB>(); for(int p=0;p<room.numInhabitants();p++) { M=room.fetchInhabitant(p); if(M!=monster) { final HashSet<MOB> seen=new HashSet<MOB>(); while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M))) { seen.add(M); M=M.amFollowing(); } choices.add(M); } } if(choices.size() > 0) tmp[SPECIAL_RANDANYONE] = choices.get(CMLib.dice().roll(1,choices.size(),-1)); } } return (MOB)tmp[SPECIAL_RANDANYONE]; } @Override public String execute(final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final DVector script, final String msg, final Object[] tmp) { return execute(scripted,source,target,monster,primaryItem,secondaryItem,script,msg,tmp,1); } public String execute(PhysicalAgent scripted, MOB source, Environmental target, MOB monster, Item primaryItem, Item secondaryItem, final DVector script, String msg, final Object[] tmp, final int startLine) { tickStatus=Tickable.STATUS_START; String s=null; String[] tt=null; String cmd=null; final boolean traceDebugging=CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTTRACE); if(traceDebugging && startLine == 1 && script.size()>0 && script.get(0, 1).toString().trim().length()>0) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": * EXECUTE: "+script.get(0, 1).toString()); for(int si=startLine;si<script.size();si++) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.length()==0) continue; if(traceDebugging) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": "+s); Integer methCode=methH.get(cmd); if((methCode==null)&&(cmd.startsWith("MP"))) { for(int i=0;i<methods.length;i++) { if(methods[i].startsWith(cmd)) methCode=Integer.valueOf(i); } } if(methCode==null) methCode=Integer.valueOf(0); tickStatus=Tickable.STATUS_MISC3+methCode.intValue(); switch(methCode.intValue()) { case 57: // <SCRIPT> { if(tt==null) tt=parseBits(script,si,"C"); final StringBuffer jscript=new StringBuffer(""); while((++si)<script.size()) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); break; } jscript.append(s+"\n"); } if(CMSecurity.isApprovedJScript(jscript)) { final Context cx = Context.enter(); try { final JScriptEvent scope = new JScriptEvent(this,scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp); cx.initStandardObjects(scope); final String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString", "getCMType"}; scope.defineFunctionProperties(names, JScriptEvent.class, ScriptableObject.DONTENUM); cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null); } catch(final Exception e) { Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage()); } Context.exit(); } else if(CMProps.getIntVar(CMProps.Int.JSCRIPTS)==CMSecurity.JSCRIPT_REQ_APPROVAL) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,L("A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script.")); } break; } case 19: // if { if(tt==null) { try { final String[] ttParms=parseEval(s.substring(2)); tt=new String[ttParms.length+1]; tt[0]="IF"; for(int i=0;i<ttParms.length;i++) tt[i+1]=ttParms[i]; script.setElementAt(si,2,tt); script.setElementAt(si, 3, new Triad<DVector,DVector,Integer>(null,null,null)); } catch(final Exception e) { logError(scripted,"IF","Syntax",e.getMessage()); tickStatus=Tickable.STATUS_END; return null; } } final String[][] EVAL={tt}; final boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVAL,1); if(EVAL[0]!=tt) { tt=EVAL[0]; script.setElementAt(si,2,tt); } boolean foundendif=false; @SuppressWarnings({ "unchecked", "rawtypes" }) Triad<DVector,DVector,Integer> parsedBlocks = (Triad)script.elementAt(si, 3); DVector subScript; if(parsedBlocks==null) { Log.errOut("Null parsed blocks in "+s); parsedBlocks = new Triad<DVector,DVector,Integer>(null,null,null); script.setElementAt(si, 3, parsedBlocks); subScript=null; } else if(parsedBlocks.third != null) { if(condition) subScript=parsedBlocks.first; else subScript=parsedBlocks.second; si=parsedBlocks.third.intValue(); si--; // because we want to be pointing at the ENDIF with si++ happens below. foundendif=true; } else subScript=null; int depth=0; boolean ignoreUntilEndScript=false; si++; boolean positiveCondition=true; while((si<script.size()) &&(!foundendif)) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=true; } else if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=false; } else if(ignoreUntilEndScript) { } else if(cmd.equals("ENDIF")&&(depth==0)) { if(tt==null) tt=parseBits(script,si,"C"); parsedBlocks.third=Integer.valueOf(si); foundendif=true; break; } else if(cmd.equals("ELSE")&&(depth==0)) { positiveCondition=false; if(s.substring(4).trim().length()>0) logError(scripted,"ELSE","Syntax"," Decorated ELSE is now illegal!!"); else if(tt==null) tt=parseBits(script,si,"C"); } else { if(cmd.equals("IF")) depth++; else if(cmd.equals("ENDIF")) { if(tt==null) tt=parseBits(script,si,"C"); depth--; } if(positiveCondition) { if(parsedBlocks.first==null) { parsedBlocks.first=new DVector(3); parsedBlocks.first.addElement("",null,null); } if(condition) subScript=parsedBlocks.first; parsedBlocks.first.addSharedElements(script.elementsAt(si)); } else { if(parsedBlocks.second==null) { parsedBlocks.second=new DVector(3); parsedBlocks.second.addElement("",null,null); } if(!condition) subScript=parsedBlocks.second; parsedBlocks.second.addSharedElements(script.elementsAt(si)); } } si++; } if(!foundendif) { logError(scripted,"IF","Syntax"," Without ENDIF!"); tickStatus=Tickable.STATUS_END; return null; } if((subScript != null) &&(subScript.size()>1)) { //source.tell(L("Starting @x1",conditionStr)); //for(int v=0;v<V.size();v++) // source.tell(L("Statement @x1",((String)V.elementAt(v)))); final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } //source.tell(L("Stopping @x1",conditionStr)); } break; } case 93: // "ENDIF", //93 JUST for catching errors... logError(scripted,"ENDIF","Syntax"," Without IF ("+si+")!"); break; case 94: //"ENDSWITCH", //94 JUST for catching errors... logError(scripted,"ENDSWITCH","Syntax"," Without SWITCH ("+si+")!"); break; case 95: //"NEXT", //95 JUST for catching errors... logError(scripted,"NEXT","Syntax"," Without FOR ("+si+")!"); break; case 96: //"CASE" //96 JUST for catching errors... logError(scripted,"CASE","Syntax"," Without SWITCH ("+si+")!"); break; case 97: //"DEFAULT" //97 JUST for catching errors... logError(scripted,"DEFAULT","Syntax"," Without SWITCH ("+si+")!"); break; case 70: // switch { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; if(script.elementAt(si, 3)==null) script.setElementAt(si, 3, new Hashtable<String,Integer>()); } @SuppressWarnings("unchecked") final Map<String,Integer> skipSwitchMap=(Map<String,Integer>)script.elementAt(si, 3); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim(); final DVector subScript=new DVector(3); subScript.addElement("",null,null); int depth=0; boolean foundEndSwitch=false; boolean ignoreUntilEndScript=false; boolean inCase=false; boolean matchedCase=false; si++; String s2=null; if(skipSwitchMap.size()>0) { if(skipSwitchMap.containsKey(var.toUpperCase())) { inCase=true; matchedCase=true; si=skipSwitchMap.get(var.toUpperCase()).intValue(); si++; } else if(skipSwitchMap.containsKey("$FIRSTVAR")) // first variable case { si=skipSwitchMap.get("$FIRSTVAR").intValue(); } else if(skipSwitchMap.containsKey("$DEFAULT")) // the "default" case { inCase=true; matchedCase=true; si=skipSwitchMap.get("$DEFAULT").intValue(); si++; } else if(skipSwitchMap.containsKey("$ENDSWITCH")) // the "endswitch" case { foundEndSwitch=true; si=skipSwitchMap.get("$ENDSWITCH").intValue(); } } while((si<script.size()) &&(!foundEndSwitch)) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=true; } else if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=false; } else if(ignoreUntilEndScript) { // only applies when <SCRIPT> encountered. } else if(cmd.equals("ENDSWITCH")&&(depth==0)) { if(tt==null) { tt=parseBits(script,si,"C"); skipSwitchMap.put("$ENDSWITCH", Integer.valueOf(si)); } foundEndSwitch=true; break; } else if(cmd.equals("CASE")&&(depth==0)) { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; if(tt[1].indexOf('$')>=0) { if(!skipSwitchMap.containsKey("$FIRSTVAR")) skipSwitchMap.put("$FIRSTVAR", Integer.valueOf(si)); } else if(!skipSwitchMap.containsKey(tt[1].toUpperCase())) skipSwitchMap.put(tt[1].toUpperCase(), Integer.valueOf(si)); } if(matchedCase &&inCase &&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done { foundEndSwitch=true; si=skipSwitchMap.get("$ENDSWITCH").intValue(); break; // this is important, otherwise si will get increment and screw stuff up } else { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim(); inCase=var.equalsIgnoreCase(s2); matchedCase=matchedCase||inCase; } } else if(cmd.equals("DEFAULT")&&(depth==0)) { if(tt==null) { tt=parseBits(script,si,"C"); if(!skipSwitchMap.containsKey("$DEFAULT")) skipSwitchMap.put("$DEFAULT", Integer.valueOf(si)); } if(matchedCase &&inCase &&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done { foundEndSwitch=true; si=skipSwitchMap.get("$ENDSWITCH").intValue(); break; // this is important, otherwise si will get increment and screw stuff up } else inCase=!matchedCase; } else { if(inCase) subScript.addSharedElements(script.elementsAt(si)); if(cmd.equals("SWITCH")) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(script.elementAt(si, 3)==null) script.setElementAt(si, 3, new Hashtable<String,Integer>()); } depth++; } else if(cmd.equals("ENDSWITCH")) { if(tt==null) tt=parseBits(script,si,"C"); depth--; } } si++; } if(!foundEndSwitch) { logError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!"); tickStatus=Tickable.STATUS_END; return null; } if(subScript.size()>1) { final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } } break; } case 62: // for x = 1 to 100 { if(tt==null) { tt=parseBits(script,si,"CcccCr"); if(tt==null) return null; } if(tt[5].length()==0) { logError(scripted,"FOR","Syntax","5 parms required!"); tickStatus=Tickable.STATUS_END; return null; } final String varStr=tt[1]; if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1)))) { logError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2.."); tickStatus=Tickable.STATUS_END; return null; } final int whichVar=CMath.s_int(Character.toString(varStr.charAt(1))); if((tmp[whichVar] instanceof String) &&(((String)tmp[whichVar]).length()>0) &&(CMath.isInteger(((String)tmp[whichVar]).trim()))) { logError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!"); tickStatus=Tickable.STATUS_END; return null; } if(!tt[2].equals("=")) { logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!"); tickStatus=Tickable.STATUS_END; return null; } int toAdd=0; if(tt[4].equals("TO<")) toAdd=-1; else if(tt[4].equals("TO>")) toAdd=1; else if(!tt[4].equals("TO")) { logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!"); tickStatus=Tickable.STATUS_END; return null; } final String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim(); final String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]).trim(); if((!CMath.isInteger(from))||(!CMath.isInteger(to))) { logError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!"); tickStatus=Tickable.STATUS_END; return null; } final DVector subScript=new DVector(3); subScript.addElement("",null,null); int depth=0; boolean foundnext=false; boolean ignoreUntilEndScript=false; si++; while(si<script.size()) { s=((String)script.elementAt(si,1)).trim(); tt=(String[])script.elementAt(si,2); if(tt!=null) cmd=tt[0]; else cmd=CMParms.getCleanBit(s,0).toUpperCase(); if(cmd.equals("<SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=true; } else if(cmd.equals("</SCRIPT>")) { if(tt==null) tt=parseBits(script,si,"C"); ignoreUntilEndScript=false; } else if(ignoreUntilEndScript) { } else if(cmd.equals("NEXT")&&(depth==0)) { if(tt==null) tt=parseBits(script,si,"C"); foundnext=true; break; } else { if(cmd.equals("FOR")) { if(tt==null) tt=parseBits(script,si,"CcccCr"); depth++; } else if(cmd.equals("NEXT")) { if(tt==null) tt=parseBits(script,si,"C"); depth--; } subScript.addSharedElements(script.elementsAt(si)); } si++; } if(!foundnext) { logError(scripted,"FOR","Syntax"," Without NEXT!"); tickStatus=Tickable.STATUS_END; return null; } if(subScript.size()>1) { //source.tell(L("Starting @x1",conditionStr)); //for(int v=0;v<V.size();v++) // source.tell(L("Statement @x1",((String)V.elementAt(v)))); final int fromInt=CMath.s_int(from); int toInt=CMath.s_int(to); final int increment=(toInt>=fromInt)?1:-1; String response=null; if(((increment>0)&&(fromInt<=(toInt+toAdd))) ||((increment<0)&&(fromInt>=(toInt+toAdd)))) { toInt+=toAdd; final long tm=System.currentTimeMillis()+(10 * 1000); for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment) { tmp[whichVar]=""+forLoop; response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); if(response!=null) break; if((System.currentTimeMillis()>tm) || (scripted.amDestroyed())) { logError(scripted,"FOR","Runtime","For loop violates 10 second rule: " +s); break; } } tmp[whichVar]=""+toInt; if(response == null) response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); else if(response.equalsIgnoreCase("break")) response=null; } if(response!=null) { tickStatus=Tickable.STATUS_END; return response; } tmp[whichVar]=null; //source.tell(L("Stopping @x1",conditionStr)); } break; } case 50: // break; if(tt==null) tt=parseBits(script,si,"C"); tickStatus=Tickable.STATUS_END; return "BREAK"; case 1: // mpasound { if(tt==null) { tt=parseBits(script,si,"Cp"); if(tt==null) return null; } final String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); //lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo); for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room R2=lastKnownLocation.getRoomInDir(d); final Exit E2=lastKnownLocation.getExitInDir(d); if((R2!=null)&&(E2!=null)&&(E2.isOpen())) R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo); } break; } case 4: // mpjunk { if(tt==null) { tt=parseBits(script,si,"CR"); if(tt==null) return null; } if(tt[1].equals("ALL") && (monster!=null)) { monster.delAllItems(true); } else { final Environmental E=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Item I=null; if(E instanceof Item) I=(Item)E; if((I==null)&&(monster!=null)) I=monster.findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1])); if((I==null)&&(scripted instanceof Room)) I=((Room)scripted).findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1])); if(I!=null) I.destroy(); } break; } case 2: // mpecho { if(tt==null) { tt=parseBits(script,si,"Cp"); if(tt==null) return null; } if(lastKnownLocation!=null) lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1])); break; } case 13: // mpunaffect { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String which=tt[2]; if(newTarget!=null) if(which.equalsIgnoreCase("all")||(which.length()==0)) { for(int a=newTarget.numEffects()-1;a>=0;a--) { final Ability A=newTarget.fetchEffect(a); if(A!=null) A.unInvoke(); } } else { final Ability A2=CMClass.findAbility(which); if(A2!=null) which=A2.ID(); final Ability A=newTarget.fetchEffect(which); if(A!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPUNAFFECTED by "+A.Name()); A.unInvoke(); if(newTarget.fetchEffect(which)==A) newTarget.delEffect(A); } } break; } case 3: // mpslay { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) CMLib.combat().postDeath(monster,(MOB)newTarget,null); break; } case 73: // mpsetinternal { if(tt==null) { tt=parseBits(script,si,"CCr"); if(tt==null) return null; } final String arg2=tt[1]; final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if(arg2.equals("SCOPE")) setVarScope(arg3); else if(arg2.equals("NODELAY")) noDelay=CMath.s_bool(arg3); else if(arg2.equals("ACTIVETRIGGER")||arg2.equals("ACTIVETRIGGERS")) alwaysTriggers=CMath.s_bool(arg3); else if(arg2.equals("DEFAULTQUEST")) registerDefaultQuest(arg3); else if(arg2.equals("SAVABLE")) setSavable(CMath.s_bool(arg3)); else if(arg2.equals("PASSIVE")) this.runInPassiveAreas = CMath.s_bool(arg3); else logError(scripted,"MPSETINTERNAL","Syntax","Unknown stat: "+arg2); break; } case 74: // mpprompt { if(tt==null) { tt=parseBits(script,si,"CCCr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null))) { try { final String value=((MOB)newTarget).session().prompt(promptStr,120000); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<"); setVar(newTarget.Name(),var,value); } catch(final Exception e) { return ""; } } break; } case 75: // mpconfirm { if(tt==null) { tt=parseBits(script,si,"CCCCr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null))) { try { final String value=((MOB)newTarget).session().confirm(promptStr,defaultVal,60000)?"Y":"N"; if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<"); setVar(newTarget.Name(),var,value); } catch(final Exception e) { return ""; } /* * this is how to do non-blocking, which doesn't help stuff waiting * for a response from the original execute method final Session session = ((MOB)newTarget).session(); if(session != null) { try { final int lastLineNum=si; final JScriptEvent continueEvent=new JScriptEvent( this, scripted, source, target, monster, primaryItem, secondaryItem, msg, tmp); ((MOB)newTarget).session().prompt(new InputCallback(InputCallback.Type.PROMPT,"",0) { private final JScriptEvent event=continueEvent; private final int lineNum=lastLineNum; private final String scope=newTarget.Name(); private final String varName=var; private final String promptStrMsg=promptStr; private final DVector lastScript=script; @Override public void showPrompt() { session.promptPrint(promptStrMsg); } @Override public void timedOut() { event.executeEvent(lastScript, lineNum+1); } @Override public void callBack() { final String value=this.input; if((value.trim().length()==0)||(value.indexOf('<')>=0)) return; setVar(scope,varName,value); event.executeEvent(lastScript, lineNum+1); } }); } catch(final Exception e) { return ""; } } */ } break; } case 76: // mpchoose { if(tt==null) { tt=parseBits(script,si,"CCCCCr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String choices=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]); if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null))) { try { final String value=((MOB)newTarget).session().choose(promptStr,choices,defaultVal,60000); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<"); setVar(newTarget.Name(),var,value); } catch(final Exception e) { return ""; } } break; } case 16: // mpset { if(tt==null) { tt=parseBits(script,si,"CCcr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[2]; String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(arg2,arg3); found=true; break; } } if((!found)&&(newTarget instanceof MOB)) { final MOB M=(MOB)newTarget; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } } } if(!found) { for(int i=0;i<M.basePhyStats().getStatCodes().length;i++) { if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1); M.basePhyStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) { for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4))) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg2.substring(4),arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().equals("STINK"))) { found=true; if(M.playerStats()!=null) M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT)); } if((!found) &&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,arg2.toUpperCase())!=null)) { found=true; CMLib.coffeeMaker().setAnyGenStat(M, arg2.toUpperCase(), arg3); } } if((!found) &&(newTarget instanceof Item)) { if((!found) &&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,arg2.toUpperCase())!=null)) { found=true; CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3); } } if((!found) &&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,arg2.toUpperCase())!=null)) { found=true; CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3); } if(!found) { logError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverPhyStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverPhyStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 63: // mpargset { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String arg1=tt[1]; final String arg2=tt[2]; if((arg1.length()!=2)||(!arg1.startsWith("$"))) { logError(scripted,"MPARGSET","Syntax","Mangled argument var: "+arg1+" for "+scripted.Name()); break; } Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp); if(O==null) O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((O==null) &&((arg2.length()!=2) ||(arg2.charAt(1)=='g') ||(!arg2.startsWith("$")) ||((!Character.isDigit(arg2.charAt(1))) &&(!Character.isLetter(arg2.charAt(1)))))) O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2); final char c=arg1.charAt(1); if(Character.isDigit(c)) { if((O instanceof String)&&(((String)O).equalsIgnoreCase("null"))) O=null; tmp[CMath.s_int(Character.toString(c))]=O; } else { switch(arg1.charAt(1)) { case 'N': case 'n': if (O instanceof MOB) source = (MOB) O; break; case 'B': case 'b': if (O instanceof Environmental) lastLoaded = (Environmental) O; break; case 'I': case 'i': if (O instanceof PhysicalAgent) scripted = (PhysicalAgent) O; if (O instanceof MOB) monster = (MOB) O; break; case 'T': case 't': if (O instanceof Environmental) target = (Environmental) O; break; case 'O': case 'o': if (O instanceof Item) primaryItem = (Item) O; break; case 'P': case 'p': if (O instanceof Item) secondaryItem = (Item) O; break; case 'd': case 'D': if (O instanceof Room) lastKnownLocation = (Room) O; break; case 'g': case 'G': if (O instanceof String) msg = (String) O; else if((O instanceof Room) &&((((Room)O).roomID().length()>0) || (!"".equals(CMLib.map().getExtendedRoomID((Room)O))))) msg = CMLib.map().getExtendedRoomID((Room)O); else if(O instanceof CMObject) msg=((CMObject)O).name(); else msg=""+O; break; default: logError(scripted, "MPARGSET", "Syntax", "Invalid argument var: " + arg1 + " for " + scripted.Name()); break; } } break; } case 35: // mpgset { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=tt[2]; String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(newTarget!=null) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3); boolean found=false; for(int i=0;i<newTarget.getStatCodes().length;i++) { if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1); newTarget.setStat(newTarget.getStatCodes()[i],arg3); found=true; break; } } if(!found) { if(newTarget instanceof MOB) { final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2.toUpperCase().trim()); if(element != null) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))-1); CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,element.name(),arg3); found=true; } if(!found) { final MOB M=(MOB)newTarget; for(final int i : CharStats.CODES.ALLCODES()) { if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(M.baseCharStats().getStat(i)+1); if(arg3.equals("--")) arg3=""+(M.baseCharStats().getStat(i)-1); if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0)))) M.baseCharStats().setStat(i,arg3.charAt(0)); else M.baseCharStats().setStat(i,CMath.s_int(arg3.trim())); M.recoverCharStats(); if(arg2.equalsIgnoreCase("RACE")) M.charStats().getMyRace().startRacing(M,false); found=true; break; } } if(!found) { for(int i=0;i<M.curState().getStatCodes().length;i++) { if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1); M.curState().setStat(arg2,arg3); found=true; break; } } } if(!found) { for(int i=0;i<M.basePhyStats().getStatCodes().length;i++) { if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1); M.basePhyStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(M.playerStats()!=null)) { for(int i=0;i<M.playerStats().getStatCodes().length;i++) { if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1); M.playerStats().setStat(arg2,arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().startsWith("BASE"))) { final String arg4=arg2.substring(4); for(int i=0;i<M.baseState().getStatCodes().length;i++) { if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg4)) { if(arg3.equals("++")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1); M.baseState().setStat(arg4,arg3); found=true; break; } } } if((!found)&&(arg2.toUpperCase().equals("STINK"))) { found=true; if(M.playerStats()!=null) M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT)); } } } } else if(newTarget instanceof Item) { final GenericBuilder.GenItemCode element = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class,arg2.toUpperCase().trim()); if(element != null) { if(arg3.equals("++")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))+1); if(arg3.equals("--")) arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))-1); CMLib.coffeeMaker().setGenItemStat((Item)newTarget,element.name(),arg3); found=true; } } if((!found) &&(newTarget instanceof Physical)) { if(CMLib.coffeeMaker().isAnyGenStat(newTarget, arg2.toUpperCase())) { CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3); found=true; } } if(!found) { logError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name()); break; } if(newTarget instanceof MOB) ((MOB)newTarget).recoverCharStats(); newTarget.recoverPhyStats(); if(newTarget instanceof MOB) { ((MOB)newTarget).recoverMaxState(); if(arg2.equalsIgnoreCase("LEVEL")) { CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level()); ((MOB)newTarget).recoverMaxState(); ((MOB)newTarget).recoverCharStats(); ((MOB)newTarget).recoverPhyStats(); ((MOB)newTarget).resetToMaxState(); } } } break; } case 11: // mpexp { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); int t=CMath.s_int(amtStr); if((newTarget!=null)&&(newTarget instanceof MOB)) { if((amtStr.endsWith("%")) &&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE)) { final int baseLevel=newTarget.basePhyStats().level(); final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1); final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel); t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded, CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0))); } if(t!=0) CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false); } break; } case 86: // mprpexp { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); int t=CMath.s_int(amtStr); if((newTarget!=null)&&(newTarget instanceof MOB)) { if((amtStr.endsWith("%")) &&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE)) { final int baseLevel=newTarget.basePhyStats().level(); final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1); final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel); t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded, CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0))); } if(t!=0) CMLib.leveler().postRPExperience((MOB)newTarget,null,null,t,false); } break; } case 77: // mpmoney { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } Environmental newTarget=getArgumentMOB(tt[1],source,monster,scripted,primaryItem,secondaryItem,msg,tmp); if(newTarget==null) newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String amtStr=tt[2]; amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,amtStr).trim(); final boolean plus=!amtStr.startsWith("-"); if(amtStr.startsWith("+")||amtStr.startsWith("-")) amtStr=amtStr.substring(1).trim(); final String currency = CMLib.english().parseNumPossibleGoldCurrency(source, amtStr); final long amt = CMLib.english().parseNumPossibleGold(source, amtStr); final double denomination = CMLib.english().parseNumPossibleGoldDenomination(source, currency, amtStr); Container container = null; if(newTarget instanceof Item) { container = (newTarget instanceof Container)?(Container)newTarget:null; newTarget = ((Item)newTarget).owner(); } if(newTarget instanceof MOB) { if(plus) CMLib.beanCounter().giveSomeoneMoney((MOB)newTarget, currency, amt * denomination); else CMLib.beanCounter().subtractMoney((MOB)newTarget, currency, amt * denomination); } else { if(!(newTarget instanceof Room)) newTarget=lastKnownLocation; if(plus) CMLib.beanCounter().dropMoney((Room)newTarget, container, currency, amt * denomination); else CMLib.beanCounter().removeMoney((Room)newTarget, container, currency, amt * denomination); } break; } case 59: // mpquestpoints { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget instanceof MOB) { if(CMath.isNumber(val)) { final int ival=CMath.s_int(val); final int aval=ival-((MOB)newTarget).getQuestPoint(); ((MOB)newTarget).setQuestPoint(CMath.s_int(val)); if(aval>0) CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, aval); } else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) { ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim())); CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, CMath.s_int(val.substring(2).trim())); } else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim())); else logError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 65: // MPQSET { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final PhysicalAgent obj=getArgumentItem(tt[3],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final Quest Q=getQuest(qstr); if(Q==null) logError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name()); else if(var.equalsIgnoreCase("QUESTOBJ")) { if(obj==null) logError(scripted,"MPQSET","Syntax","Unknown object "+tt[3]+" for "+scripted.Name()); else { obj.basePhyStats().setDisposition(obj.basePhyStats().disposition()|PhyStats.IS_UNSAVABLE); obj.recoverPhyStats(); Q.runtimeRegisterObject(obj); } } else if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("ACCEPTED"))) CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTACCEPTED); else if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("SUCCESS")||val.equalsIgnoreCase("WON"))) CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSUCCESS); else if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("FAILED"))) CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTFAILED); else { if(val.equals("++")) val=""+(CMath.s_int(Q.getStat(var))+1); if(val.equals("--")) val=""+(CMath.s_int(Q.getStat(var))-1); Q.setStat(var,val); } break; } case 66: // MPLOG { if(tt==null) { tt=parseBits(script,si,"CCcr"); if(tt==null) return null; } final String type=tt[1]; final String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(type.startsWith("E")) Log.errOut("Script","["+head+"] "+val); else if(type.startsWith("I")||type.startsWith("S")) Log.infoOut("Script","["+head+"] "+val); else if(type.startsWith("D")) Log.debugOut("Script","["+head+"] "+val); else logError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name()); break; } case 67: // MPCHANNEL { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final boolean sysmsg=channel.startsWith("!"); if(sysmsg) channel=channel.substring(1); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if(CMLib.channels().getChannelCodeNumber(channel)<0) logError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name()); else CMLib.commands().postChannel(monster,channel,val,sysmsg); break; } case 68: // MPUNLOADSCRIPT { if(tt==null) { tt=parseBits(script,si,"Cc"); if(tt==null) return null; } String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(!new CMFile(Resources.makeFileResourceName(scriptname),null,CMFile.FLAG_FORCEALLOW).exists()) logError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname)); else { final ArrayList<String> delThese=new ArrayList<String>(); scriptname=scriptname.toUpperCase().trim(); final String parmname=scriptname; for(final Iterator<String> k = Resources.findResourceKeys(parmname);k.hasNext();) { final String key=k.next(); if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname))) { delThese.add(key); } } for(int i=0;i<delThese.size();i++) Resources.removeResource(delThese.get(i)); } break; } case 60: // MPTRAINS { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget instanceof MOB) { if(CMath.isNumber(val)) ((MOB)newTarget).setTrains(CMath.s_int(val)); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim())); else logError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 61: // mppracs { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget instanceof MOB) { if(CMath.isNumber(val)) ((MOB)newTarget).setPractices(CMath.s_int(val)); else if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim())); else if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim()))) ((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim())); else logError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name()); } break; } case 5: // mpmload { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final ArrayList<Environmental> Ms=new ArrayList<Environmental>(); MOB m=CMClass.getMOB(name); if(m!=null) Ms.add(m); if(lastKnownLocation!=null) { if(Ms.size()==0) findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true); for(int i=0;i<Ms.size();i++) { if(Ms.get(i) instanceof MOB) { m=(MOB)((MOB)Ms.get(i)).copyOf(); m.text(); m.recoverPhyStats(); m.recoverCharStats(); m.resetToMaxState(); m.bringToLife(lastKnownLocation,true); lastLoaded=m; } } } break; } case 6: // mpoload { //if not mob Physical addHere; if(scripted instanceof MOB) addHere=monster; else if(scripted instanceof Item) addHere=((Item)scripted).owner(); else if(scripted instanceof Room) addHere=scripted; else addHere=lastKnownLocation; if(addHere!=null) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } this.lastLoaded = null; String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final int containerIndex=name.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { final ArrayList<Environmental> containers=new ArrayList<Environmental>(); findSomethingCalledThis(name.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) { if((containers.get(c) instanceof Container) &&(((Container)containers.get(c)).capacity()>0)) { container=(Container)containers.get(c); name=name.substring(0,containerIndex).trim(); break; } } } final long coins=CMLib.english().parseNumPossibleGold(null,name); if(coins>0) { final String currency=CMLib.english().parseNumPossibleGoldCurrency(scripted,name); final double denom=CMLib.english().parseNumPossibleGoldDenomination(scripted,currency,name); final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); if(addHere instanceof MOB) ((MOB)addHere).addItem(C); else if(addHere instanceof Room) ((Room)addHere).addItem(C, Expire.Monster_EQ); C.putCoinsBack(); } else if(lastKnownLocation!=null) { final ArrayList<Environmental> Is=new ArrayList<Environmental>(); Item m=CMClass.getItem(name); if(m!=null) Is.add(m); else findSomethingCalledThis(name,monster,lastKnownLocation,Is,false); for(int i=0;i<Is.size();i++) { if(Is.get(i) instanceof Item) { m=(Item)Is.get(i); if((m!=null) &&(!(m instanceof ArchonOnly))) { m=(Item)m.copyOf(); m.recoverPhyStats(); m.setContainer(container); if(container instanceof MOB) ((MOB)container.owner()).addItem(m); else if(container instanceof Room) ((Room)container.owner()).addItem(m,ItemPossessor.Expire.Player_Drop); else if(addHere instanceof MOB) ((MOB)addHere).addItem(m); else if(addHere instanceof Room) ((Room)addHere).addItem(m, Expire.Monster_EQ); lastLoaded=m; } } } if(addHere instanceof MOB) { ((MOB)addHere).recoverCharStats(); ((MOB)addHere).recoverMaxState(); } addHere.recoverPhyStats(); lastKnownLocation.recoverRoomStats(); } } break; } case 41: // mpoloadroom { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(lastKnownLocation!=null) { final ArrayList<Environmental> Is=new ArrayList<Environmental>(); final int containerIndex=name.toUpperCase().indexOf(" INTO "); Container container=null; if(containerIndex>=0) { final ArrayList<Environmental> containers=new ArrayList<Environmental>(); findSomethingCalledThis(name.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false); for(int c=0;c<containers.size();c++) { if((containers.get(c) instanceof Container) &&(((Container)containers.get(c)).capacity()>0)) { container=(Container)containers.get(c); name=name.substring(0,containerIndex).trim(); break; } } } final long coins=CMLib.english().parseNumPossibleGold(null,name); if(coins>0) { final String currency=CMLib.english().parseNumPossibleGoldCurrency(monster,name); final double denom=CMLib.english().parseNumPossibleGoldDenomination(monster,currency,name); final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins); Is.add(C); } else { final Item I=CMClass.getItem(name); if(I!=null) Is.add(I); else findSomethingCalledThis(name,monster,lastKnownLocation,Is,false); } for(int i=0;i<Is.size();i++) { if(Is.get(i) instanceof Item) { Item I=(Item)Is.get(i); if((I!=null) &&(!(I instanceof ArchonOnly))) { I=(Item)I.copyOf(); I.recoverPhyStats(); lastKnownLocation.addItem(I,ItemPossessor.Expire.Monster_EQ); I.setContainer(container); if(I instanceof Coins) ((Coins)I).putCoinsBack(); if(I instanceof RawMaterial) ((RawMaterial)I).rebundle(); lastLoaded=I; } } } lastKnownLocation.recoverRoomStats(); } break; } case 84: // mpoloadshop { ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted); if((addHere == null)&&(scripted instanceof Item)) addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner()); if((addHere == null)&&(scripted instanceof MOB)) addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location()); if(addHere == null) addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(addHere!=null) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(lastKnownLocation!=null) { final ArrayList<Environmental> Is=new ArrayList<Environmental>(); int price=-1; if((price = name.indexOf(" PRICE="))>=0) { final String rest = name.substring(price+7).trim(); name=name.substring(0,price).trim(); if(CMath.isInteger(rest)) price=CMath.s_int(rest); } Item I=CMClass.getItem(name); if(I!=null) Is.add(I); else findSomethingCalledThis(name,monster,lastKnownLocation,Is,false); for(int i=0;i<Is.size();i++) { if(Is.get(i) instanceof Item) { I=(Item)Is.get(i); if((I!=null) &&(!(I instanceof ArchonOnly))) { I=(Item)I.copyOf(); I.recoverPhyStats(); final CoffeeShop shop = addHere.getShop(); if(shop != null) { final Environmental E=shop.addStoreInventory(I,1,price); if(E!=null) setShopPrice(addHere, E, tmp); } I.destroy(); } } } lastKnownLocation.recoverRoomStats(); } } break; } case 85: // mpmloadshop { ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted); if((addHere == null)&&(scripted instanceof Item)) addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner()); if((addHere == null)&&(scripted instanceof MOB)) addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location()); if(addHere == null) addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation); if(addHere!=null) { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } this.lastLoaded = null; String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); int price=-1; if((price = name.indexOf(" PRICE="))>=0) { final String rest = name.substring(price+7).trim(); name=name.substring(0,price).trim(); if(CMath.isInteger(rest)) price=CMath.s_int(rest); } final ArrayList<Environmental> Ms=new ArrayList<Environmental>(); MOB m=CMClass.getMOB(name); if(m!=null) Ms.add(m); if(lastKnownLocation!=null) { if(Ms.size()==0) findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true); for(int i=0;i<Ms.size();i++) { if(Ms.get(i) instanceof MOB) { m=(MOB)((MOB)Ms.get(i)).copyOf(); m.text(); m.recoverPhyStats(); m.recoverCharStats(); m.resetToMaxState(); final CoffeeShop shop = addHere.getShop(); if(shop != null) { final Environmental E=shop.addStoreInventory(m,1,price); if(E!=null) setShopPrice(addHere, E, tmp); } m.destroy(); } } } } break; } case 42: // mphide { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()|PhyStats.IS_NOT_SEEN); newTarget.recoverPhyStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 58: // mpreset { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); if(arg.equalsIgnoreCase("area")) { if(lastKnownLocation!=null) CMLib.map().resetArea(lastKnownLocation.getArea()); } else if(arg.equalsIgnoreCase("room")) { if(lastKnownLocation!=null) CMLib.map().resetRoom(lastKnownLocation, true); } else { final Room R=CMLib.map().getRoom(arg); if(R!=null) CMLib.map().resetRoom(R, true); else { final Area A=CMLib.map().findArea(arg); if(A!=null) CMLib.map().resetArea(A); else { final Physical newTarget=getArgumentItem(arg,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget == null) logError(scripted,"MPRESET","Syntax","Unknown location or item: "+arg+" for "+scripted.Name()); else if(newTarget instanceof Item) { final Item I=(Item)newTarget; I.setContainer(null); if(I.subjectToWearAndTear()) I.setUsesRemaining(100); I.recoverPhyStats(); } else if(newTarget instanceof MOB) { final MOB M=(MOB)newTarget; M.resetToMaxState(); M.recoverMaxState(); M.recoverCharStats(); M.recoverPhyStats(); } } } } break; } case 71: // mprejuv { if(tt==null) { final String rest=CMParms.getPastBitClean(s,1); if(rest.equals("item")||rest.equals("items")) tt=parseBits(script,si,"Ccr"); else if(rest.equals("mob")||rest.equals("mobs")) tt=parseBits(script,si,"Ccr"); else tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String next=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); String rest=""; if(tt.length>2) rest=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); int tickID=-1; if(rest.equalsIgnoreCase("item")||rest.equalsIgnoreCase("items")) tickID=Tickable.TICKID_ROOM_ITEM_REJUV; else if(rest.equalsIgnoreCase("mob")||rest.equalsIgnoreCase("mobs")) tickID=Tickable.TICKID_MOB; if(next.equalsIgnoreCase("area")) { if(lastKnownLocation!=null) for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) CMLib.threads().rejuv(e.nextElement(),tickID); } else if(next.equalsIgnoreCase("room")) { if(lastKnownLocation!=null) CMLib.threads().rejuv(lastKnownLocation,tickID); } else { final Room R=CMLib.map().getRoom(next); if(R!=null) CMLib.threads().rejuv(R,tickID); else { final Area A=CMLib.map().findArea(next); if(A!=null) { for(final Enumeration<Room> e=A.getProperMap();e.hasMoreElements();) CMLib.threads().rejuv(e.nextElement(),tickID); } else logError(scripted,"MPREJUV","Syntax","Unknown location: "+next+" for "+scripted.Name()); } } break; } case 56: // mpstop { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final List<MOB> V=new ArrayList<MOB>(); final String who=tt[1]; if(who.equalsIgnoreCase("all")) { for(int i=0;i<lastKnownLocation.numInhabitants();i++) V.add(lastKnownLocation.fetchInhabitant(i)); } else { final Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget instanceof MOB) V.add((MOB)newTarget); } for(int v=0;v<V.size();v++) { final Environmental newTarget=V.get(v); if(newTarget instanceof MOB) { final MOB mob=(MOB)newTarget; Ability A=null; for(int a=mob.numEffects()-1;a>=0;a--) { A=mob.fetchEffect(a); if((A!=null) &&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL) &&(A.canBeUninvoked()) &&(!A.isAutoInvoked())) A.unInvoke(); } mob.makePeace(false); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } } break; } case 43: // mpunhide { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(CMath.bset(newTarget.basePhyStats().disposition(),PhyStats.IS_NOT_SEEN))) { newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()-PhyStats.IS_NOT_SEEN); newTarget.recoverPhyStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 44: // mpopen { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container)&&(((Container)newTarget).hasADoor())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 45: // mpclose { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit) &&(((Exit)newTarget).hasADoor()) &&(((Exit)newTarget).isOpen())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container) &&(((Container)newTarget).hasADoor()) &&(((Container)newTarget).isOpen())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 46: // mplock { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit) &&(((Exit)newTarget).hasALock())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container) &&(((Container)newTarget).hasALock())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 47: // mpunlock { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget instanceof Exit) &&(((Exit)newTarget).isLocked())) { final Exit E=(Exit)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } else if((newTarget instanceof Container) &&(((Container)newTarget).isLocked())) { final Container E=(Container)newTarget; E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked()); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 48: // return if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } tickStatus=Tickable.STATUS_END; return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); case 87: // mea case 7: // mpechoat { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final String parm=tt[1]; final Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { if(newTarget==monster) lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); else lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]),CMMsg.NO_EFFECT,null); } else if(parm.equalsIgnoreCase("world")) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } } else if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null)) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } } else if(CMLib.map().getRoom(parm)!=null) CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); else if(CMLib.map().findArea(parm)!=null) { lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); for(final Enumeration<Room> e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();) { final Room R=e.nextElement(); if(R.numInhabitants()>0) R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } } break; } case 88: // mer case 8: // mpechoaround { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null)) { lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); } break; } case 9: // mpcast { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null) &&(A!=null)) { A.setProficiency(100); if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster,newTarget,false,0); } break; } case 89: // mpcastexp { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String args=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null) &&(A!=null)) { A.setProficiency(100); final List<String> commands = CMParms.parse(args); if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster, commands, newTarget, false, 0); } break; } case 30: // mpaffect { if(tt==null) { tt=parseBits(script,si,"Cccp"); if(tt==null) return null; } final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Ability A=null; if(cast!=null) A=CMClass.findAbility(cast); if((newTarget!=null)&&(A!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPAFFECTED by "+A.Name()); A.setMiscText(m2); if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY) newTarget.addNonUninvokableEffect(A); else { if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster,CMParms.parse(m2),newTarget,true,0); } } break; } case 80: // mpspeak { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String language=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final Ability A=CMClass.getAbility(language); if((A instanceof Language)&&(newTarget instanceof MOB)) { ((Language)A).setProficiency(100); ((Language)A).autoInvocation((MOB)newTarget, false); final Ability langA=((MOB)newTarget).fetchEffect(A.ID()); if(langA!=null) { if(((MOB)newTarget).isMonster()) langA.setProficiency(100); langA.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0); } else A.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0); } break; } case 81: // mpsetclan { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String clan=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String roleStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Clan C=CMLib.clans().getClan(clan); if(C==null) C=CMLib.clans().findClan(clan); if((newTarget instanceof MOB)&&(C!=null)) { int role=Integer.MIN_VALUE; if(CMath.isInteger(roleStr)) role=CMath.s_int(roleStr); else for(int i=0;i<C.getRolesList().length;i++) { if(roleStr.equalsIgnoreCase(C.getRolesList()[i])) role=i; } if(role!=Integer.MIN_VALUE) { if(((MOB)newTarget).isPlayer()) C.addMember((MOB)newTarget, role); else ((MOB)newTarget).setClan(C.clanID(), role); } } break; } case 31: // mpbehave { if(tt==null) { tt=parseBits(script,si,"Cccp"); if(tt==null) return null; } String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); Behavior B=null; final Behavior B2=(cast==null)?null:CMClass.findBehavior(cast); if(B2!=null) cast=B2.ID(); if((cast!=null)&&(newTarget!=null)) { B=newTarget.fetchBehavior(cast); if(B==null) B=CMClass.getBehavior(cast); } if((newTarget!=null)&&(B!=null)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPBEHAVED with "+B.name()); B.setParms(m2); if(newTarget.fetchBehavior(B.ID())==null) { newTarget.addBehavior(B); if((defaultQuestName()!=null)&&(defaultQuestName().length()>0)) B.registerDefaultQuest(defaultQuestName()); } } break; } case 72: // mpscript { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final PhysicalAgent newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); boolean proceed=true; boolean savable=false; boolean execute=false; String scope=getVarScope(); while(proceed) { proceed=false; if(m2.toUpperCase().startsWith("SAVABLE ")) { savable=true; m2=m2.substring(8).trim(); proceed=true; } else if(m2.toUpperCase().startsWith("EXECUTE ")) { execute=true; m2=m2.substring(8).trim(); proceed=true; } else if(m2.toUpperCase().startsWith("GLOBAL ")) { scope=""; proceed=true; m2=m2.substring(6).trim(); } else if(m2.toUpperCase().startsWith("INDIVIDUAL ")||m2.equals("*")) { scope="*"; proceed=true; m2=m2.substring(10).trim(); } } if((newTarget!=null)&&(m2.length()>0)) { if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())) Log.sysOut("Scripting",newTarget.Name()+" was MPSCRIPTED: "+defaultQuestName); final ScriptingEngine S=(ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine"); S.setSavable(savable); S.setVarScope(scope); S.setScript(m2); if((defaultQuestName()!=null)&&(defaultQuestName().length()>0)) S.registerDefaultQuest(defaultQuestName()); newTarget.addScript(S); if(execute) { S.tick(newTarget,Tickable.TICKID_MOB); for(int i=0;i<5;i++) S.dequeResponses(); newTarget.delScript(S); } } break; } case 32: // mpunbehave { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(cast!=null)) { Behavior B=CMClass.findBehavior(cast); if(B!=null) cast=B.ID(); B=newTarget.fetchBehavior(cast); if(B!=null) newTarget.delBehavior(B); if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(B!=null)) Log.sysOut("Scripting",newTarget.Name()+" was MPUNBEHAVED with "+B.name()); } break; } case 33: // mptattoo { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB)) { final MOB themob=(MOB)newTarget; final boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName); final Tattoo T=themob.findTattoo(pT.getTattooName()); if(T!=null) { if(tattooMinus) themob.delTattoo(T); } else if(!tattooMinus) themob.addTattoo(pT); } break; } case 83: // mpacctattoo { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if((newTarget!=null) &&(tattooName.length()>0) &&(newTarget instanceof MOB) &&(((MOB)newTarget).playerStats()!=null) &&(((MOB)newTarget).playerStats().getAccount()!=null)) { final Tattooable themob=((MOB)newTarget).playerStats().getAccount(); final boolean tattooMinus=tattooName.startsWith("-"); if(tattooMinus) tattooName=tattooName.substring(1); final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName); final Tattoo T=themob.findTattoo(pT.getTattooName()); if(T!=null) { if(tattooMinus) themob.delTattoo(T); } else if(!tattooMinus) themob.addTattoo(pT); } break; } case 92: // mpput { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newTarget!=null) { if(tt[2].equalsIgnoreCase("NULL")||tt[2].equalsIgnoreCase("NONE")) { if(newTarget instanceof Item) ((Item)newTarget).setContainer(null); if(newTarget instanceof Rider) ((Rider)newTarget).setRiding(null); } else { final Physical newContainer=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(newContainer!=null) { if((newTarget instanceof Item) &&(newContainer instanceof Container)) ((Item)newTarget).setContainer((Container)newContainer); if((newTarget instanceof Rider) &&(newContainer instanceof Rideable)) ((Rider)newTarget).setRiding((Rideable)newContainer); } } newTarget.recoverPhyStats(); if(lastKnownLocation!=null) lastKnownLocation.recoverRoomStats(); } break; } case 55: // mpnotrigger { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); int triggerCode=-1; for(int i=0;i<progs.length;i++) { if(trigger.equalsIgnoreCase(progs[i])) triggerCode=i; } if(triggerCode<0) logError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name."); else if(!CMath.isInteger(time.trim())) logError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time."); else { noTrigger.remove(Integer.valueOf(triggerCode)); noTrigger.put(Integer.valueOf(triggerCode),Long.valueOf(System.currentTimeMillis()+CMath.s_long(time.trim()))); } break; } case 54: // mpfaction { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim(); final Faction F=CMLib.factions().getFaction(faction); if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB)) { final MOB themob=(MOB)newTarget; int curFaction = themob.fetchFaction(F.factionID()); if((curFaction == Integer.MAX_VALUE)||(curFaction == Integer.MIN_VALUE)) curFaction = F.findDefault(themob); if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim()))) { final int amt=CMath.s_int(range.substring(2).trim()); if(amt < 0) themob.tell(L("You gain @x1 faction with @x2.",""+(-amt),F.name())); else themob.tell(L("You lose @x1 faction with @x2.",""+amt,F.name())); range=""+(curFaction-amt); } else if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim()))) { final int amt=CMath.s_int(range.substring(1).trim()); if(amt < 0) themob.tell(L("You lose @x1 faction with @x2.",""+(-amt),F.name())); else themob.tell(L("You gain @x1 faction with @x2.",""+amt,F.name())); range=""+(curFaction+amt); } else if(CMath.isInteger(range)) themob.tell(L("Your faction with @x1 is now @x2.",F.name(),""+CMath.s_int(range.trim()))); if(CMath.isInteger(range)) themob.addFaction(F.factionID(),CMath.s_int(range.trim())); else { Faction.FRange FR=null; final Enumeration<Faction.FRange> e=CMLib.factions().getRanges(CMLib.factions().getAlignmentID()); if(e!=null) for(;e.hasMoreElements();) { final Faction.FRange FR2=e.nextElement(); if(FR2.name().equalsIgnoreCase(range)) { FR = FR2; break; } } if(FR==null) logError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+"."); else { themob.tell(L("Your faction with @x1 is now @x2.",F.name(),FR.name())); themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2)); } } } break; } case 49: // mptitle { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String titleStr=varify(monster, newTarget, scripted, monster, secondaryItem, secondaryItem, msg, tmp, tt[2]); if((newTarget!=null)&&(titleStr.length()>0)&&(newTarget instanceof MOB)) { final MOB themob=(MOB)newTarget; final boolean tattooMinus=titleStr.startsWith("-"); if(tattooMinus) titleStr=titleStr.substring(1); if(themob.playerStats()!=null) { if(themob.playerStats().getTitles().contains(titleStr)) { if(tattooMinus) themob.playerStats().getTitles().remove(titleStr); } else if(!tattooMinus) themob.playerStats().getTitles().add(0,titleStr); } } break; } case 10: // mpkill { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null) &&(newTarget instanceof MOB) &&(monster!=null)) monster.setVictim((MOB)newTarget); break; } case 51: // mpsetclandata { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); String clanID=null; if((newTarget!=null)&&(newTarget instanceof MOB)) { Clan C=CMLib.clans().findRivalrousClan((MOB)newTarget); if(C==null) C=((MOB)newTarget).clans().iterator().hasNext()?((MOB)newTarget).clans().iterator().next().first:null; if(C!=null) clanID=C.clanID(); } else clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String clanvar=tt[2]; final String clanval=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final Clan C=CMLib.clans().getClan(clanID); if(C!=null) { if(!C.isStat(clanvar)) logError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable."); else { C.setStat(clanvar,clanval.trim()); if(C.getStat(clanvar).equalsIgnoreCase(clanval)) C.update(); } } break; } case 52: // mpplayerclass { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if((newTarget!=null)&&(newTarget instanceof MOB)) { final Vector<String> V=CMParms.parse(tt[2]); for(int i=0;i<V.size();i++) { if(CMath.isInteger(V.elementAt(i).trim())) ((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(V.elementAt(i).trim())); else { final CharClass C=CMClass.findCharClass(V.elementAt(i)); if((C!=null)&&(C.availabilityCode()!=0)) ((MOB)newTarget).baseCharStats().setCurrentClass(C); } } ((MOB)newTarget).recoverCharStats(); } break; } case 12: // mppurge { if(lastKnownLocation!=null) { int flag=0; if(tt==null) { final String s2=CMParms.getCleanBit(s,1).toLowerCase(); if(s2.equals("room")) tt=parseBits(script,si,"Ccr"); else if(s2.equals("my")) tt=parseBits(script,si,"Ccr"); else tt=parseBits(script,si,"Cr"); if(tt==null) return null; } String s2=tt[1]; if(s2.equalsIgnoreCase("room")) { flag=1; s2=tt[2]; } else if(s2.equalsIgnoreCase("my")) { flag=2; s2=tt[2]; } Environmental E=null; if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me")) E=scripted; else if(flag==1) { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2); E=lastKnownLocation.fetchFromRoomFavorItems(null,s2); } else if(flag==2) { s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2); if(monster!=null) E=monster.findItem(s2); } else E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) { if(E instanceof MOB) { if(!((MOB)E).isMonster()) { if(((MOB)E).getStartRoom()!=null) ((MOB)E).getStartRoom().bringMobHere((MOB)E,false); ((MOB)E).session().stopSession(false,false,false); } else if(((MOB)E).getStartRoom()!=null) ((MOB)E).killMeDead(false); else ((MOB)E).destroy(); } else if(E instanceof Item) { final ItemPossessor oE=((Item)E).owner(); ((Item)E).destroy(); if(oE!=null) oE.recoverPhyStats(); } } lastKnownLocation.recoverRoomStats(); } break; } case 14: // mpgoto { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String roomID=tt[1].trim(); if((roomID.length()>0)&&(lastKnownLocation!=null)) { Room goHere=null; if(roomID.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(roomID,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomID),lastKnownLocation); if(goHere!=null) { if(scripted instanceof MOB) goHere.bringMobHere((MOB)scripted,true); else if(scripted instanceof Item) goHere.moveItemTo((Item)scripted,ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers); else { goHere.bringMobHere(monster,true); if(!(scripted instanceof MOB)) goHere.delInhabitant(monster); } if(CMLib.map().roomLocation(scripted)==goHere) lastKnownLocation=goHere; } } break; } case 15: // mpat if(lastKnownLocation!=null) { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final Room lastPlace=lastKnownLocation; final String roomName=tt[1]; if(roomName.length()>0) { final String doWhat=tt[2].trim(); Room goHere=null; if(roomName.startsWith("$")) goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(goHere==null) goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(goHere!=null) { goHere.bringMobHere(monster,true); final DVector subScript=new DVector(3); subScript.addElement("",null,null); subScript.addElement(doWhat,null,null); lastKnownLocation=goHere; execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp); lastKnownLocation=lastPlace; lastPlace.bringMobHere(monster,true); if(!(scripted instanceof MOB)) { goHere.delInhabitant(monster); lastPlace.delInhabitant(monster); } } } } break; case 17: // mptransfer { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String mobName=tt[1]; String roomName=tt[2].trim(); Room newRoom=null; if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if((roomName.length()==0)&&(lastKnownLocation!=null)) roomName=lastKnownLocation.roomID(); if(roomName.length()>0) { if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(newRoom!=null) { final ArrayList<Environmental> V=new ArrayList<Environmental>(); if(mobName.startsWith("$")) { final Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E!=null) V.add(E); } if(V.size()==0) { mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName); if(mobName.equalsIgnoreCase("all")) { if(lastKnownLocation!=null) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { final MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!V.contains(m))) V.add(m); } } } else { MOB findOne=null; Area A=null; if(findOne==null) { if(lastKnownLocation!=null) { findOne=lastKnownLocation.fetchInhabitant(mobName); A=lastKnownLocation.getArea(); if((findOne!=null)&&(findOne!=monster)) V.add(findOne); } } if(findOne==null) { findOne=CMLib.players().getPlayerAllHosts(mobName); if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true))) findOne=null; if((findOne!=null)&&(findOne!=monster)) V.add(findOne); } if((findOne==null)&&(A!=null)) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); findOne=R.fetchInhabitant(mobName); if((findOne!=null)&&(findOne!=monster)) V.add(findOne); } } } } for(int v=0;v<V.size();v++) { if(V.get(v) instanceof MOB) { final MOB mob=(MOB)V.get(v); final Set<MOB> H=mob.getGroupMembers(new HashSet<MOB>()); for (final Object element : H) { final MOB M=(MOB)element; if((!V.contains(M))&&(M.location()==mob.location())) V.add(M); } } } for(int v=0;v<V.size();v++) { if(V.get(v) instanceof MOB) { final MOB follower=(MOB)V.get(v); final Room thisRoom=follower.location(); final int dispmask=(PhyStats.IS_SLEEPING | PhyStats.IS_SITTING); final int dispo1 = follower.basePhyStats().disposition() & dispmask; final int dispo2 = follower.phyStats().disposition() & dispmask; follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() & (~dispmask)); follower.phyStats().setDisposition(follower.phyStats().disposition() & (~dispmask)); // scripting guide calls for NO text -- empty is probably req tho final CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER|CMMsg.MASK_ALWAYS,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMLib.protocol().msp("appear.wav",10)); final CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE|CMMsg.MASK_ALWAYS," "); if((thisRoom!=null) &&thisRoom.okMessage(follower,leaveMsg) &&newRoom.okMessage(follower,enterMsg)) { final boolean alreadyHere = follower.location()==(Room)enterMsg.target(); if(follower.isInCombat()) { CMLib.commands().postFlee(follower,("NOWHERE")); follower.makePeace(true); } thisRoom.send(follower,leaveMsg); if(!alreadyHere) ((Room)enterMsg.target()).bringMobHere(follower,false); ((Room)enterMsg.target()).send(follower,enterMsg); follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1); follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2); if(!CMLib.flags().isSleeping(follower) &&(!alreadyHere)) { follower.tell(CMLib.lang().L("\n\r\n\r")); CMLib.commands().postLook(follower,true); } } else { follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1); follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2); } } else if((V.get(v) instanceof Item) &&(newRoom!=CMLib.map().roomLocation(V.get(v)))) newRoom.moveItemTo((Item)V.get(v),ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers); if((V.get(v)==scripted) &&(scripted instanceof Physical) &&(newRoom.isHere(scripted))) lastKnownLocation=newRoom; } } } break; } case 25: // mpbeacon { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final String roomName=tt[1]; Room newRoom=null; if((roomName.length()>0)&&(lastKnownLocation!=null)) { final String beacon=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if(roomName.startsWith("$")) newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp)); if(newRoom==null) newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation); if(newRoom == null) logError(scripted,"MPBEACON","RunTime",tt[1]+" is not a room."); else if(lastKnownLocation!=null) { final List<MOB> V=new ArrayList<MOB>(); if(beacon.equalsIgnoreCase("all")) { for(int x=0;x<lastKnownLocation.numInhabitants();x++) { final MOB m=lastKnownLocation.fetchInhabitant(x); if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m))) V.add(m); } } else { final MOB findOne=lastKnownLocation.fetchInhabitant(beacon); if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster())) V.add(findOne); } for(int v=0;v<V.size();v++) { final MOB follower=V.get(v); if(!follower.isMonster()) follower.setStartRoom(newRoom); } } } break; } case 18: // mpforce { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String force=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim(); if(newTarget!=null) { final DVector vscript=new DVector(3); vscript.addElement("FUNCTION_PROG MPFORCE_"+System.currentTimeMillis()+Math.random(),null,null); vscript.addElement(force,null,null); // this can not be permanently parsed because it is variable execute(newTarget, source, target, getMakeMOB(newTarget), primaryItem, secondaryItem, vscript, msg, tmp); } break; } case 79: // mppossess { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final PhysicalAgent newSource=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final PhysicalAgent newTarget=getArgumentMOB(tt[2],source,monster,target,primaryItem,secondaryItem,msg,tmp); if((!(newSource instanceof MOB))||(((MOB)newSource).isMonster())) logError(scripted,"MPPOSSESS","RunTime",tt[1]+" is not a player."); else if((!(newTarget instanceof MOB))||(!((MOB)newTarget).isMonster())||CMSecurity.isASysOp((MOB)newTarget)) logError(scripted,"MPPOSSESS","RunTime",tt[2]+" is not a mob."); else { final MOB mobM=(MOB)newSource; final MOB targetM=(MOB)newTarget; final Session S=mobM.session(); S.setMob(targetM); targetM.setSession(S); targetM.setSoulMate(mobM); mobM.setSession(null); } break; } case 20: // mpsetvar { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } String which=tt[1]; final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if(!which.equals("*")) { if(E==null) which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which); else if(E instanceof Room) which=CMLib.map().getExtendedRoomID((Room)E); else which=E.Name(); } if((which.length()>0)&&(arg2.length()>0)) { if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+arg2+")="+arg3+"<"); setVar(which,arg2,arg3); } break; } case 36: // mpsavevar { if(tt==null) { tt=parseBits(script,si,"CcR"); if(tt==null) return null; } String which=tt[1]; String arg2=tt[2]; final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if((which.length()>0)&&(arg2.length()>0)) { final PairList<String,String> vars=getScriptVarSet(which,arg2); for(int v=0;v<vars.size();v++) { which=vars.elementAtFirst(v); arg2=vars.elementAtSecond(v).toUpperCase(); @SuppressWarnings("unchecked") final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+which); String val=""; if(H!=null) { val=H.get(arg2); if(val==null) val=""; } if(val.length()>0) CMLib.database().DBReCreatePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val); else CMLib.database().DBDeletePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); } } break; } case 39: // mploadvar { if(tt==null) { tt=parseBits(script,si,"CcR"); if(tt==null) return null; } String which=tt[1]; final String arg2=tt[2]; final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(arg2.length()>0) { List<PlayerData> V=null; which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp); if(arg2.equals("*")) V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS"); else V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2); if((V!=null)&&(V.size()>0)) for(int v=0;v<V.size();v++) { final DatabaseEngine.PlayerData VAR=V.get(v); String varName=VAR.key(); if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_")) varName=varName.substring((which+"_SCRIPTABLEVARS_").length()); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS)) Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+varName+")="+VAR.xml()+"<"); setVar(which,varName,VAR.xml()); } } break; } case 40: // MPM2I2M { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String arg1=tt[1]; final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); if(E instanceof MOB) { final String arg2=tt[2]; final String arg3=tt[3]; final CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged"); if(caged!=null) { ((Item)caged).basePhyStats().setAbility(1); ((Item)caged).recoverPhyStats(); } if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null)) { if(arg2.length()>0) ((Item)caged).setName(arg2); if(arg3.length()>0) ((Item)caged).setDisplayText(arg3); lastKnownLocation.addItem(caged,ItemPossessor.Expire.Player_Drop); ((MOB)E).killMeDead(false); } } else if(E instanceof CagedAnimal) { final MOB M=((CagedAnimal)E).unCageMe(); if((M!=null)&&(lastKnownLocation!=null)) { M.bringToLife(lastKnownLocation,true); ((Item)E).destroy(); } } else logError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item."); break; } case 28: // mpdamage { if(tt==null) { tt=parseBits(script,si,"Ccccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); if((newTarget!=null)&&(arg2.length()>0)) { if(newTarget instanceof MOB) { final MOB deadM=(MOB)newTarget; MOB killerM=(MOB)newTarget; if(arg4.equalsIgnoreCase("MEKILL")||arg4.equalsIgnoreCase("ME")) killerM=monster; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); if((dmg>=deadM.curState().getHitPoints()) &&(!arg4.equalsIgnoreCase("KILL")) &&(!arg4.equalsIgnoreCase("MEKILL"))) dmg=deadM.curState().getHitPoints()-1; if(dmg>0) CMLib.combat().postDamage(killerM,deadM,null,dmg,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,-1,null); } } else if(newTarget instanceof Item) { final Item E=(Item)newTarget; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min); boolean destroy=false; if(E.subjectToWearAndTear()) { if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill"))) dmg=E.usesRemaining()-1; if(dmg>0) E.setUsesRemaining(E.usesRemaining()-dmg); if(E.usesRemaining()<=0) destroy=true; } else if(arg4.equalsIgnoreCase("kill")) destroy=true; if(destroy) { if(lastKnownLocation!=null) lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 is destroyed!",E.name())); E.destroy(); } } } } break; } case 78: // mpheal { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); if((newTarget!=null)&&(arg2.length()>0)) { if(newTarget instanceof MOB) { final MOB healedM=(MOB)newTarget; final MOB healerM=(MOB)newTarget; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min); if(amt>0) CMLib.combat().postHealing(healerM,healedM,null,amt,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null); } } else if(newTarget instanceof Item) { final Item E=(Item)newTarget; final int min=CMath.s_int(arg2.trim()); int max=CMath.s_int(arg3.trim()); if(max<min) max=min; if(min>0) { final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min); if(E.subjectToWearAndTear()) { E.setUsesRemaining(E.usesRemaining()+amt); if(E.usesRemaining()>100) E.setUsesRemaining(100); } } } } break; } case 90: // mplink { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final int dir=CMLib.directions().getGoodDirectionCode(dirWord); if(dir < 0) logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction."); else { final String roomID = varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); final Room startR=(homeKnownLocation!=null)?homeKnownLocation:CMLib.map().getStartRoom(scripted); final Room R=this.getRoom(roomID, lastKnownLocation); if((R==null)||(lastKnownLocation==null)||(R.getArea()!=lastKnownLocation.getArea())) logError(scripted,"MPLINK","RunTime",roomID+" is not a target room."); else if((startR!=null)&&(startR.getArea()!=lastKnownLocation.getArea())) logError(scripted,"MPLINK","RunTime","mplink from "+roomID+" is an illegal source room."); else { String exitID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); String nameArg=null; final int x=exitID.indexOf(' '); if(x>0) { nameArg=exitID.substring(x+1).trim(); exitID=exitID.substring(0,x); } final Exit E=CMClass.getExit(exitID); if(E==null) logError(scripted,"MPLINK","RunTime",exitID+" is not a exit class."); else if((lastKnownLocation.rawDoors()[dir]==null) &&(lastKnownLocation.getRawExit(dir)==null)) { lastKnownLocation.rawDoors()[dir]=R; lastKnownLocation.setRawExit(dir, E); E.basePhyStats().setSensesMask(E.basePhyStats().sensesMask()|PhyStats.SENSE_ITEMNOWISH); E.setSavable(false); E.recoverPhyStats(); if(nameArg!=null) E.setName(nameArg); } } } break; } case 91: // mpunlink { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final int dir=CMLib.directions().getGoodDirectionCode(dirWord); if(dir < 0) logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction."); else if((lastKnownLocation==null) ||((lastKnownLocation.rawDoors()[dir]!=null)&&(lastKnownLocation.rawDoors()[dir].getArea()!=lastKnownLocation.getArea()))) logError(scripted,"MPLINK","RunTime",dirWord+" is a non-in-area direction."); else if((lastKnownLocation.getRawExit(dir)!=null) &&(lastKnownLocation.getRawExit(dir).isSavable() ||(!CMath.bset(lastKnownLocation.getRawExit(dir).basePhyStats().sensesMask(), PhyStats.SENSE_ITEMNOWISH)))) logError(scripted,"MPLINK","RunTime",dirWord+" is not a legal unlinkable exit."); else { lastKnownLocation.setRawExit(dir, null); lastKnownLocation.rawDoors()[dir]=null; } break; } case 29: // mptrackto { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); if(A.text().length()>0 && A.text().equalsIgnoreCase(arg1)) { // already on the move } else { altStatusTickable=A; A.invoke(monster,CMParms.parse(arg1),null,true,0); altStatusTickable=null; } } break; } case 53: // mpwalkto { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final Ability A=CMClass.getAbility("Skill_Track"); if(A!=null) { altStatusTickable=A; if((monster != scripted) &&(monster!=null)) monster.resetToMaxState(); A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0); altStatusTickable=null; } break; } case 21: //MPENDQUEST { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final PhysicalAgent newTarget; final String q=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(q); if(Q!=null) { CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSTOP); Q.stopQuest(); } else if((tt[1].length()>0) &&(defaultQuestName!=null) &&(defaultQuestName.length()>0) &&((newTarget=getArgumentMOB(tt[1].trim(),source,monster,target,primaryItem,secondaryItem,msg,tmp))!=null)) { for(int i=newTarget.numScripts()-1;i>=0;i--) { final ScriptingEngine S=newTarget.fetchScript(i); if((S!=null) &&(S.defaultQuestName()!=null) &&(S.defaultQuestName().equalsIgnoreCase(defaultQuestName))) { newTarget.delScript(S); S.endQuest(newTarget, (newTarget instanceof MOB)?((MOB)newTarget):monster, defaultQuestName); } } } else if(q.length()>0) { boolean foundOne=false; for(int i=scripted.numScripts()-1;i>=0;i--) { final ScriptingEngine S=scripted.fetchScript(i); if((S!=null) &&(S.defaultQuestName()!=null) &&(S.defaultQuestName().equalsIgnoreCase(q))) { foundOne=true; S.endQuest(scripted, monster, S.defaultQuestName()); scripted.delScript(S); } } if((!foundOne) &&((defaultQuestName==null)||(!defaultQuestName.equalsIgnoreCase(q)))) logError(scripted,"MPENDQUEST","Unknown","Quest: "+s); } break; } case 69: // MPSTEPQUEST { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(qName); if(Q!=null) Q.stepQuest(); else logError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s); break; } case 23: //MPSTARTQUEST { if(tt==null) { tt=parseBits(script,si,"Cr"); if(tt==null) return null; } final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(qName); if(Q!=null) Q.startQuest(); else logError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s); break; } case 64: //MPLOADQUESTOBJ { if(tt==null) { tt=parseBits(script,si,"Cccr"); if(tt==null) return null; } final String questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim()); final Quest Q=getQuest(questName); if(Q==null) { logError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName); break; } final Object O=Q.getDesignatedObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2])); if(O==null) { logError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+tt[2]+" for Quest: "+questName); break; } final String varArg=tt[3]; if((varArg.length()!=2)||(!varArg.startsWith("$"))) { logError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name()); break; } final char c=varArg.charAt(1); if(Character.isDigit(c)) tmp[CMath.s_int(Character.toString(c))]=O; else switch(c) { case 'N': case 'n': if (O instanceof MOB) source = (MOB) O; break; case 'I': case 'i': if (O instanceof PhysicalAgent) scripted = (PhysicalAgent) O; if (O instanceof MOB) monster = (MOB) O; break; case 'B': case 'b': if (O instanceof Environmental) lastLoaded = (Environmental) O; break; case 'T': case 't': if (O instanceof Environmental) target = (Environmental) O; break; case 'O': case 'o': if (O instanceof Item) primaryItem = (Item) O; break; case 'P': case 'p': if (O instanceof Item) secondaryItem = (Item) O; break; case 'd': case 'D': if (O instanceof Room) lastKnownLocation = (Room) O; break; default: logError(scripted, "MPLOADQUESTOBJ", "Syntax", "Invalid argument var: " + varArg + " for " + scripted.Name()); break; } break; } case 22: //MPQUESTWIN { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); MOB M=null; if(lastKnownLocation!=null) M=lastKnownLocation.fetchInhabitant(whoName); if(M==null) M=CMLib.players().getPlayerAllHosts(whoName); if(M!=null) whoName=M.Name(); if(whoName.length()>0) { final Quest Q=getQuest(tt[2]); if(Q!=null) { if(M!=null) CMLib.achievements().possiblyBumpAchievement(M, AchievementLibrary.Event.QUESTOR, 1, Q); Q.declareWinner(whoName); CMLib.players().bumpPrideStat(M,AccountStats.PrideStat.QUESTS_COMPLETED, 1); } else logError(scripted,"MPQUESTWIN","Unknown","Quest: "+s); } break; } case 24: // MPCALLFUNC { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } if(script.elementAt(si, 3) != null) { execute(scripted, source, target, monster, primaryItem, secondaryItem, (DVector)script.elementAt(si, 3), varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2].trim()), tmp); } else { final String named=tt[1]; final String parms=tt[2].trim(); boolean found=false; final List<DVector> scripts=getScripts(); for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); final String[] ttrigger=(String[])script2.elementAt(0,2); if(getTriggerCode(trigger,ttrigger)==17) // function_prog { final String fnamed=CMParms.getCleanBit(trigger,1); if(fnamed.equalsIgnoreCase(named)) { found=true; script.setElementAt(si, 3, script2); execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms), tmp); break; } } } if(!found) { for(int v=0;v<scripts.size();v++) { final DVector script2=scripts.get(v); if(script2.size()<1) continue; final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim(); if(trigger.equalsIgnoreCase(named)) { found=true; script.setElementAt(si, 3, script2); execute(scripted, source, target, monster, primaryItem, secondaryItem, script2, varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms), tmp); break; } } } if(!found) logError(scripted,"MPCALLFUNC","Unknown","Function: "+named); } break; } case 27: // MPWHILE { if(tt==null) { final ArrayList<String> V=new ArrayList<String>(); V.add("MPWHILE"); String conditionStr=(s.substring(7).trim()); if(!conditionStr.startsWith("(")) { logError(scripted,"MPWHILE","Syntax"," NO Starting (: "+s); break; } conditionStr=conditionStr.substring(1).trim(); int x=-1; int depth=0; for(int i=0;i<conditionStr.length();i++) { if(conditionStr.charAt(i)=='(') depth++; else if((conditionStr.charAt(i)==')')&&((--depth)<0)) { x=i; break; } } if(x<0) { logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s); break; } final String DO=conditionStr.substring(x+1).trim(); conditionStr=conditionStr.substring(0,x); try { final String[] EVAL=parseEval(conditionStr); V.add("("); V.addAll(Arrays.asList(EVAL)); V.add(")"); V.add(DO); tt=CMParms.toStringArray(V); script.setElementAt(si,2,tt); } catch(final Exception e) { logError(scripted,"MPWHILE","Syntax",e.getMessage()); break; } if(tt==null) return null; } int evalEnd=2; int depth=0; while((evalEnd<tt.length)&&((!tt[evalEnd].equals(")"))||(depth>0))) { if(tt[evalEnd].equals("(")) depth++; else if(tt[evalEnd].equals(")")) depth--; evalEnd++; } if(evalEnd==tt.length) { logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s); break; } final String[] EVAL=new String[evalEnd-2]; for(int y=2;y<evalEnd;y++) EVAL[y-2]=tt[y]; String DO=tt[evalEnd+1]; String[] DOT=null; final int doLen=(tt.length-evalEnd)-1; if(doLen>1) { DOT=new String[doLen]; for(int y=0;y<DOT.length;y++) { DOT[y]=tt[evalEnd+y+1]; if(y>0) DO+=" "+tt[evalEnd+y+1]; } } final String[][] EVALO={EVAL}; final DVector vscript=new DVector(3); vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random(),null,null); vscript.addElement(DO,DOT,null); final long time=System.currentTimeMillis(); while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVALO,0)) &&((System.currentTimeMillis()-time)<4000) &&(!scripted.amDestroyed())) execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp); if(vscript.elementAt(1,2)!=DOT) { final int oldDotLen=(DOT==null)?1:DOT.length; final String[] newDOT=(String[])vscript.elementAt(1,2); final String[] newTT=new String[tt.length-oldDotLen+newDOT.length]; int end=0; for(end=0;end<tt.length-oldDotLen;end++) newTT[end]=tt[end]; for(int y=0;y<newDOT.length;y++) newTT[end+y]=newDOT[y]; tt=newTT; script.setElementAt(si,2,tt); } if(EVALO[0]!=EVAL) { final Vector<String> lazyV=new Vector<String>(); lazyV.addElement("MPWHILE"); lazyV.addElement("("); final String[] newEVAL=EVALO[0]; for (final String element : newEVAL) lazyV.addElement(element); for(int i=evalEnd;i<tt.length;i++) lazyV.addElement(tt[i]); tt=CMParms.toStringArray(lazyV); script.setElementAt(si,2,tt); } if((System.currentTimeMillis()-time)>=4000) { logError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+s); break; } break; } case 26: // MPALARM { if(tt==null) { tt=parseBits(script,si,"Ccp"); if(tt==null) return null; } final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]); final String parms=tt[2].trim(); if(CMath.s_int(time.trim())<=0) { logError(scripted,"MPALARM","Syntax","Bad time "+time); break; } if(parms.length()==0) { logError(scripted,"MPALARM","Syntax","No command!"); break; } final DVector vscript=new DVector(3); vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random(),null,null); vscript.addElement(parms,null,null); prequeResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg); break; } case 37: // mpenable { if(tt==null) { tt=parseBits(script,si,"Ccccp"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]); final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]); Ability A=null; if(cast!=null) { if(newTarget instanceof MOB) A=((MOB)newTarget).fetchAbility(cast); if(A==null) A=CMClass.getAbility(cast); if(A==null) { final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if(D==null) logError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast); else if((newTarget!=null)&&(newTarget instanceof MOB)) ((MOB)newTarget).addExpertise(D.ID()); } } if((newTarget!=null) &&(A!=null) &&(newTarget instanceof MOB)) { if(!((MOB)newTarget).isMonster()) Log.sysOut("Scripting",newTarget.Name()+" was MPENABLED with "+A.Name()); if(p2.trim().startsWith("++")) p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency()); else if(p2.trim().startsWith("--")) p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2))); A.setProficiency(CMath.s_int(p2.trim())); A.setMiscText(m2); if(((MOB)newTarget).fetchAbility(A.ID())==null) { ((MOB)newTarget).addAbility(A); A.autoInvocation((MOB)newTarget, false); } } break; } case 38: // mpdisable { if(tt==null) { tt=parseBits(script,si,"Ccr"); if(tt==null) return null; } final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp); final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]); if((newTarget!=null)&&(newTarget instanceof MOB)) { final Ability A=((MOB)newTarget).findAbility(cast); if(A!=null) ((MOB)newTarget).delAbility(A); if((!((MOB)newTarget).isMonster())&&(A!=null)) Log.sysOut("Scripting",newTarget.Name()+" was MPDISABLED with "+A.Name()); final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false); if((newTarget instanceof MOB)&&(D!=null)) ((MOB)newTarget).delExpertise(D.ID()); } break; } case Integer.MIN_VALUE: logError(scripted,cmd.toUpperCase(),"Syntax","Unexpected prog start -- missing '~'?"); break; default: if(cmd.length()>0) { final Vector<String> V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s)); if((V.size()>0) &&(monster!=null)) monster.doCommand(V,MUDCmdProcessor.METAFLAG_MPFORCED); } break; } } tickStatus=Tickable.STATUS_END; return null; } protected static final Vector<DVector> empty=new ReadOnlyVector<DVector>(); @Override public String getScriptResourceKey() { return scriptKey; } public void bumpUpCache(final String key) { if((key != null) && (key.length()>0) && (!key.equals("*"))) { synchronized(counterCache) { if(!counterCache.containsKey(key)) counterCache.put(key, new AtomicInteger(0)); counterCache.get(key).addAndGet(1); } } } public void bumpUpCache() { synchronized(this) { final Object ref=cachedRef; if((ref != this) &&(this.scriptKey!=null) &&(this.scriptKey.length()>0)) { bumpUpCache(getScriptResourceKey()); bumpUpCache(scope); bumpUpCache(defaultQuestName); cachedRef=this; } } } public boolean bumpDownCache(final String key) { if((key != null) && (key.length()>0) && (!key.equals("*"))) { if((key != null) &&(key.length()>0) &&(!key.equals("*"))) { synchronized(counterCache) { if(counterCache.containsKey(key)) { if(counterCache.get(key).addAndGet(-1) <= 0) { counterCache.remove(key); return true; } } } } } return false; } protected void bumpDownCache() { synchronized(this) { final Object ref=cachedRef; if(ref == this) { if(bumpDownCache(getScriptResourceKey())) { for(final Resources R : Resources.all()) R._removeResource(getScriptResourceKey()); } if(bumpDownCache(scope)) { for(final Resources R : Resources.all()) R._removeResource("VARSCOPE-"+scope.toUpperCase().trim()); } if(bumpDownCache(defaultQuestName)) { for(final Resources R : Resources.all()) R._removeResource("VARSCOPE-"+defaultQuestName.toUpperCase().trim()); } } } } @Override protected void finalize() throws Throwable { bumpDownCache(); super.finalize(); } protected List<DVector> getScripts() { if(CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLE)||CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTING)) return empty; @SuppressWarnings("unchecked") List<DVector> scripts=(List<DVector>)Resources.getResource(getScriptResourceKey()); if(scripts==null) { String scr=getScript(); scr=CMStrings.replaceAll(scr,"`","'"); scripts=parseScripts(scr); Resources.submitResource(getScriptResourceKey(),scripts); } return scripts; } protected boolean match(final String str, final String patt) { if(patt.trim().equalsIgnoreCase("ALL")) return true; if(patt.length()==0) return true; if(str.length()==0) return false; if(str.equalsIgnoreCase(patt)) return true; return false; } private Item makeCheapItem(final Environmental E) { Item product=null; if(E instanceof Item) product=(Item)E; else { product=CMClass.getItem("StdItem"); product.setName(E.Name()); product.setDisplayText(E.displayText()); product.setDescription(E.description()); if(E instanceof Physical) product.setBasePhyStats((PhyStats)((Physical)E).basePhyStats().copyOf()); product.recoverPhyStats(); } return product; } @Override public boolean okMessage(final Environmental host, final CMMsg msg) { if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get()>2)) return true; try { // atomic recurse counter recurseCounter.addAndGet(1); final PhysicalAgent affecting = (PhysicalAgent)host; final List<DVector> scripts=getScripts(); DVector script=null; boolean tryIt=false; String trigger=null; String[] t=null; int triggerCode=0; String str=null; for(int v=0;v<scripts.size();v++) { tryIt=false; script=scripts.get(v); if(script.size()<1) continue; trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); t=(String[])script.elementAt(0,2); triggerCode=getTriggerCode(trigger,t); switch(triggerCode) { case 42: // cnclmsg_prog if(canTrigger(42)) { if(t==null) t=parseBits(script,0,"CCT"); if(t!=null) { final String command=t[1]; boolean chk=false; final int x=command.indexOf('='); if(x>0) { chk=true; boolean minorOnly = false; boolean majorOnly = false; for(int i=0;i<x;i++) { switch(command.charAt(i)) { case 'S': if(majorOnly) chk=chk&&msg.isSourceMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isSourceMinor(command.substring(x+1)); else chk=chk&&msg.isSource(command.substring(x+1)); break; case 'T': if(majorOnly) chk=chk&&msg.isTargetMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isTargetMinor(command.substring(x+1)); else chk=chk&&msg.isTarget(command.substring(x+1)); break; case 'O': if(majorOnly) chk=chk&&msg.isOthersMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isOthersMinor(command.substring(x+1)); else chk=chk&&msg.isOthers(command.substring(x+1)); break; case '<': minorOnly=true; majorOnly=false; break; case '>': majorOnly=true; minorOnly=false; break; case '?': majorOnly=false; minorOnly=false; break; default: chk=false; break; } } } else if(command.startsWith(">")) { final String cmd=command.substring(1); chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd); } else if(command.startsWith("<")) { final String cmd=command.substring(1); chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd); } else if(command.startsWith("?")) { final String cmd=command.substring(1); chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd); } else chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command); if(chk) { str=""; if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" "; if((t[2].length()==0)||(t[2].equals("ALL"))) tryIt=true; else if((t[2].equals("P"))&&(t.length>3)) { if(match(str.trim(),t[3])) tryIt=true; } else for(int i=2;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=(t[i].trim()+" "+str.trim()).trim(); tryIt=true; break; } } } } } break; } if(tryIt) { final MOB monster=getMakeMOB(affecting); if(lastKnownLocation==null) { lastKnownLocation=msg.source().location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return true; final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; String resp=null; if(msg.target() instanceof MOB) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs()); else if(msg.target() instanceof Item) resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs()); else resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs()); if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL"))) return false; } } } finally { recurseCounter.addAndGet(-1); } return true; } protected String standardTriggerCheck(final DVector script, String[] t, final Environmental E, final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final Object[] tmp) { if(E==null) return null; final boolean[] dollarChecks; if(t==null) { t=parseBits(script,0,"CT"); dollarChecks=new boolean[t.length]; for(int i=1;i<t.length;i++) dollarChecks[i] = t[i].indexOf('$')>=0; script.setElementAt(0, 3, dollarChecks); } else dollarChecks=(boolean[])script.elementAt(0, 3); final String NAME=E.Name().toUpperCase(); final String ID=E.ID().toUpperCase(); if((t[1].length()==0) ||(t[1].equals("ALL")) ||(t[1].equals("P") &&(t.length==3) &&((t[2].equalsIgnoreCase(NAME)) ||(t[2].equalsIgnoreCase("ALL"))))) return t[1]; for(int i=1;i<t.length;i++) { final String word; if (dollarChecks[i]) word=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i]); else word=t[i]; if(word.equals("P") && (i < t.length-1)) { final String arg; if (dollarChecks[i+1]) arg=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i+1]); else arg=t[i+1]; if( arg.equalsIgnoreCase(NAME) || arg.equalsIgnoreCase(ID) || arg.equalsIgnoreCase("ALL")) return word; i++; } else if(((" "+NAME+" ").indexOf(" "+word+" ")>=0) ||(ID.equalsIgnoreCase(word)) ||(word.equalsIgnoreCase("ALL"))) return word; } return null; } @Override public void executeMsg(final Environmental host, final CMMsg msg) { if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get() > 2)) return; try { // atomic recurse counter recurseCounter.addAndGet(1); final PhysicalAgent affecting = (PhysicalAgent)host; final MOB monster=getMakeMOB(affecting); if(lastKnownLocation==null) { lastKnownLocation=msg.source().location(); if(homeKnownLocation==null) homeKnownLocation=lastKnownLocation; } if((monster==null)||(monster.amDead())||(lastKnownLocation==null)) return; final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null; MOB eventMob=monster; if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB)) eventMob=(MOB)defaultItem.owner(); final List<DVector> scripts=getScripts(); if(msg.amITarget(eventMob) &&(!msg.amISource(monster)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.source()!=monster)) lastToHurtMe=msg.source(); DVector script=null; String trigger=null; String[] t=null; for(int v=0;v<scripts.size();v++) { script=scripts.get(v); if(script.size()<1) continue; trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); t=(String[])script.elementAt(0,2); final int triggerCode=getTriggerCode(trigger,t); int targetMinorTrigger=-1; switch(triggerCode) { case 1: // greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&canTrigger(1) &&((!(affecting instanceof MOB))||CMLib.flags().canSenseEnteringLeaving(msg.source(),(MOB)affecting))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 45: // arrive_prog if(((msg.targetMinor()==CMMsg.TYP_ENTER)||(msg.sourceMinor()==CMMsg.TYP_LIFE)) &&(msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&canTrigger(45)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { if((host instanceof Item) &&(((Item)host).owner() instanceof MOB) &&(msg.source()==((Item)host).owner())) { // this is to prevent excessive queing when a player is running full throttle with a scripted item // that pays attention to where it is. for(int i=que.size()-1;i>=0;i--) { try { if(que.get(i).scr == script) que.remove(i); } catch(final Exception e) { } } } enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 2: // all_greet_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&((!(affecting instanceof MOB)) ||CMLib.flags().canActAtAll(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 47: // speak_prog if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(47) &&(msg.amISource(monster)||(!(affecting instanceof MOB))) &&(!msg.othersMajor(CMMsg.MASK_CHANNEL)) &&((msg.sourceMessage()!=null) ||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null))) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) { t=parseBits(script,0,"CT"); for(int i=0;i<t.length;i++) { if(t[i]!=null) t[i]=t[i].replace('`', '\''); } } String str=null; if(msg.sourceMessage() != null) str=CMStrings.getSayFromMessage(msg.sourceMessage().toUpperCase()); else if(msg.targetMessage() != null) str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()); else if(msg.othersMessage() != null) str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()); if(str != null) { str=(" "+str.replace('`', '\'')+" ").toUpperCase(); str=CMStrings.removeColors(str); str=CMStrings.replaceAll(str,"\n\r"," "); if((t[1].length()==0)||(t[1].equals("ALL"))) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } else if((t[1].equals("P"))&&(t.length>2)) { if(match(str.trim(),t[2])) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } } else for(int i=1;i<t.length;i++) { final int x=str.indexOf(" "+t[i]+" "); if(x>=0) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t); return; } } } } break; case 3: // speech_prog if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3) &&(!msg.amISource(monster)) &&(!msg.othersMajor(CMMsg.MASK_CHANNEL)) &&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE))) ||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null))) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) { t=parseBits(script,0,"CT"); for(int i=0;i<t.length;i++) { if(t[i]!=null) t[i]=t[i].replace('`', '\''); } } String str=null; if(msg.othersMessage() != null) str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase()); else if(msg.targetMessage() != null) str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase()); if(str != null) { str=(" "+str.replace('`', '\'')+" ").toUpperCase(); str=CMStrings.removeColors(str); str=CMStrings.replaceAll(str,"\n\r"," "); if((t[1].length()==0)||(t[1].equals("ALL"))) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } else if((t[1].equals("P"))&&(t.length>2)) { if(match(str.trim(),t[2])) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t); return; } } else for(int i=1;i<t.length;i++) { final int x=str.indexOf(" "+t[i]+" "); if(x>=0) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t); return; } } } } break; case 4: // give_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&canTrigger(4) &&((msg.amITarget(monster)) ||(msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(msg.tool() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,check, t); return; } } break; case 48: // giving_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&canTrigger(48) &&((msg.amISource(monster)) ||(msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(msg.tool() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,script,1,check, t); return; } } break; case 49: // cast_prog if((msg.tool() instanceof Ability) &&canTrigger(49) &&((msg.amITarget(monster)) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(!msg.amISource(monster)) &&(msg.sourceMinor()!=CMMsg.TYP_TEACH) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,defaultItem,null,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,check, t); return; } } break; case 50: // casting_prog if((msg.tool() instanceof Ability) &&canTrigger(50) &&((msg.amISource(monster)) ||(affecting instanceof Room) ||(affecting instanceof Area)) &&(msg.sourceMinor()!=CMMsg.TYP_TEACH) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,null,defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t); return; } } break; case 40: // llook_prog if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,null,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t); return; } } break; case 41: // execmsg_prog if(canTrigger(41)) { if(t==null) t=parseBits(script,0,"CCT"); if(t!=null) { final String command=t[1]; boolean chk=false; final int x=command.indexOf('='); if(x>0) { chk=true; boolean minorOnly = false; boolean majorOnly = false; for(int i=0;i<x;i++) { switch(command.charAt(i)) { case 'S': if(majorOnly) chk=chk&&msg.isSourceMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isSourceMinor(command.substring(x+1)); else chk=chk&&msg.isSource(command.substring(x+1)); break; case 'T': if(majorOnly) chk=chk&&msg.isTargetMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isTargetMinor(command.substring(x+1)); else chk=chk&&msg.isTarget(command.substring(x+1)); break; case 'O': if(majorOnly) chk=chk&&msg.isOthersMajor(command.substring(x+1)); else if(minorOnly) chk=chk&&msg.isOthersMinor(command.substring(x+1)); else chk=chk&&msg.isOthers(command.substring(x+1)); break; case '<': minorOnly=true; majorOnly=false; break; case '>': majorOnly=true; minorOnly=false; break; case '?': majorOnly=false; minorOnly=false; break; default: chk=false; break; } } } else if(command.startsWith(">")) { final String cmd=command.substring(1); chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd); } else if(command.startsWith("<")) { final String cmd=command.substring(1); chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd); } else if(command.startsWith("?")) { final String cmd=command.substring(1); chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd); } else chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command); if(chk) { String str=""; if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null)) str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" "; boolean doIt=false; if((t[2].length()==0)||(t[2].equals("ALL"))) doIt=true; else if((t[2].equals("P"))&&(t.length>3)) { if(match(str.trim(),t[3])) doIt=true; } else for(int i=2;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=(t[i].trim()+" "+str.trim()).trim(); doIt=true; break; } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } } } break; case 39: // look_prog if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,script,1,check, t); return; } } break; case 20: // get_prog if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20) &&(msg.amITarget(affecting) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { Item checkInE=(Item)msg.target(); if((msg.tool() instanceof Item) &&(((Item)msg.tool()).container()==msg.target())) checkInE=(Item)msg.tool(); final String check=standardTriggerCheck(script,t,checkInE,affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; enqueResponse(affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,script,1,check, t); return; } } break; case 22: // drop_prog if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; if(msg.target() instanceof Coins) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 24: // remove_prog if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 34: // open_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_OPEN; //$FALL-THROUGH$ case 35: // close_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_CLOSE; //$FALL-THROUGH$ case 36: // lock_prog if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_LOCK; //$FALL-THROUGH$ case 37: // unlock_prog { if(targetMinorTrigger<0) targetMinorTrigger=CMMsg.TYP_UNLOCK; if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem; final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,I,defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,check, t); return; } } break; } case 25: // consume_prog if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(25) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t); if(check!=null) { if((msg.target() == affecting) &&(affecting instanceof Food)) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 21: // put_prog if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21) &&((msg.amITarget(affecting)) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(msg.tool() instanceof Item) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t); return; } } break; case 46: // putting_prog if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(46) &&((msg.tool()==affecting) ||(affecting instanceof Room) ||(affecting instanceof Area) ||(affecting instanceof MOB)) &&(msg.tool() instanceof Item) &&(!msg.amISource(monster)) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t); if(check!=null) { if(lastMsg==msg) break; lastMsg=msg; if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room)) execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t); return; } } break; case 27: // buy_prog if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27) &&((!(affecting instanceof ShopKeeper)) ||msg.amITarget(affecting)) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null; final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t); if(check!=null) { final Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,check,newObjs()); else enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t); return; } } break; case 28: // sell_prog if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28) &&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper))) &&(!msg.amISource(monster)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null; final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t); if(check!=null) { final Item product=makeCheapItem(msg.tool()); if((product instanceof Coins) &&(product.owner() instanceof Room)) execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,newObjs()); else enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t); return; } } break; case 23: // wear_prog if(((msg.targetMinor()==CMMsg.TYP_WEAR) ||(msg.targetMinor()==CMMsg.TYP_HOLD) ||(msg.targetMinor()==CMMsg.TYP_WIELD)) &&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB)) &&(!msg.amISource(monster))&&canTrigger(23) &&(msg.target() instanceof Item) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,t); if(check!=null) { enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,check, t); return; } } break; case 19: // bribe_prog if((msg.targetMinor()==CMMsg.TYP_GIVE) &&(msg.amITarget(eventMob)||(!(affecting instanceof MOB))) &&(!msg.amISource(monster))&&canTrigger(19) &&(msg.tool() instanceof Coins) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { if(t[1].startsWith("ANY")||t[1].startsWith("ALL")) t[1]=t[1].trim(); else if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster))) break; double d=0.0; if(CMath.isDouble(t[1])) d=CMath.s_double(t[1]); else d=CMath.s_int(t[1]); if((((Coins)msg.tool()).getTotalValue()>=d) ||(t[1].equals("ALL")) ||(t[1].equals("ANY"))) { enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null, t); return; } } } break; case 8: // entry_prog if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8) &&(msg.amISource(eventMob) ||(msg.target()==affecting) ||(msg.tool()==affecting) ||(affecting instanceof Item)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que); ScriptableResponse SB=null; String roomID=null; if(msg.target()!=null) roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target())); for(int q=0;q<V.size();q++) { SB=V.get(q); if((SB.scr==script)&&(SB.s==msg.source())) { if(que.remove(SB)) execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs()); break; } } enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t); return; } } } break; case 9: // exit_prog if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9) &&(msg.amITarget(lastKnownLocation)) &&(!msg.amISource(eventMob)) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que); ScriptableResponse SB=null; String roomID=null; if(msg.target()!=null) roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target())); for(int q=0;q<V.size();q++) { SB=V.get(q); if((SB.scr==script)&&(SB.s==msg.source())) { if(que.remove(SB)) execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs()); break; } } enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t); return; } } } break; case 10: // death_prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10) &&(msg.amISource(eventMob)||(!(affecting instanceof MOB)))) { if(t==null) t=parseBits(script,0,"C"); final MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs()); return; } break; case 44: // kill_prog if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44) &&((msg.tool()==affecting)||(!(affecting instanceof MOB)))) { if(t==null) t=parseBits(script,0,"C"); final MOB ded=msg.source(); MOB src=lastToHurtMe; if(msg.tool() instanceof MOB) src=(MOB)msg.tool(); if((src==null)||(src.location()!=monster.location())) src=ded; execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs()); return; } break; case 26: // damage_prog if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26) &&(msg.amITarget(eventMob)||(msg.tool()==affecting))) { if(t==null) t=parseBits(script,0,"C"); Item I=null; if(msg.tool() instanceof Item) I=(Item)msg.tool(); execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),newObjs()); return; } break; case 29: // login_prog if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LOGIN))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN); registeredEvents.add(Integer.valueOf(CMMsg.TYP_LOGIN)); } if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&(!CMLib.flags().isCloaked(msg.source()))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 32: // level_prog if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LEVEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL); registeredEvents.add(Integer.valueOf(CMMsg.TYP_LEVEL)); } if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&(msg.value() > msg.source().basePhyStats().level()) &&(!CMLib.flags().isCloaked(msg.source()))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { execute(affecting,msg.source(),monster,monster,defaultItem,null,script,null,t); return; } } } break; case 30: // logoff_prog if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30) &&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)) &&((!CMLib.flags().isCloaked(msg.source()))||(!CMSecurity.isASysOp(msg.source())))) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t); return; } } } break; case 12: // mask_prog { if(!canTrigger(12)) break; } //$FALL-THROUGH$ case 18: // act_prog if((msg.amISource(monster)) ||((triggerCode==18)&&(!canTrigger(18)))) break; //$FALL-THROUGH$ case 43: // imask_prog if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43))) { if(t==null) { t=parseBits(script,0,"CT"); for(int i=1;i<t.length;i++) t[i]=CMLib.english().stripPunctuation(CMStrings.removeColors(t[i])); } boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); str=CMLib.english().stripPunctuation(CMStrings.removeColors(str)); str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" "; if((t[1].length()==0)||(t[1].equals("ALL"))) doIt=true; else if((t[1].equals("P"))&&(t.length>2)) { if(match(str.trim(),t[2])) doIt=true; } else for(int i=1;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=t[i]; doIt=true; break; } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } break; case 38: // social_prog if(!msg.amISource(monster) &&canTrigger(38) &&(msg.tool() instanceof Social)) { if(t==null) t=parseBits(script,0,"CR"); if((t!=null) &&((Social)msg.tool()).Name().toUpperCase().startsWith(t[1])) { final Item Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,msg.tool().Name(), t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t); return; } } break; case 33: // channel_prog if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_CHANNEL))) { CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL); registeredEvents.add(Integer.valueOf(CMMsg.TYP_CHANNEL)); } if(!msg.amISource(monster) &&(msg.othersMajor(CMMsg.MASK_CHANNEL)) &&canTrigger(33)) { if(t==null) t=parseBits(script,0,"CCT"); boolean doIt=false; if(t!=null) { final String channel=t[1]; final int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL; String str=null; final CMChannel officialChannel=CMLib.channels().getChannel(channelInt); if(officialChannel==null) Log.errOut("Script","Unknown channel for code '"+channelInt+"': "+msg.othersMessage()); else if(channel.equalsIgnoreCase(officialChannel.name())) { str=msg.sourceMessage(); if(str==null) str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim(); int dex=str.indexOf("["+channel+"]"); if(dex>0) str=str.substring(dex+2+channel.length()).trim(); else { dex=str.indexOf('\''); final int edex=str.lastIndexOf('\''); if(edex>dex) str=str.substring(dex+1,edex); } str=" "+CMStrings.removeColors(str)+" "; str=CMStrings.replaceAll(str,"\n\r"," "); if((t[2].length()==0)||(t[2].equals("ALL"))) doIt=true; else if(t[2].equals("P")&&(t.length>2)) { if(match(str.trim(),t[3])) doIt=true; } else for(int i=2;i<t.length;i++) { if(str.indexOf(" "+t[i]+" ")>=0) { str=t[i]; doIt=true; break; } } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } } break; case 31: // regmask_prog if(!msg.amISource(monster)&&canTrigger(31)) { boolean doIt=false; String str=msg.othersMessage(); if(str==null) str=msg.targetMessage(); if(str==null) str=msg.sourceMessage(); if(str==null) break; str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false); if(t==null) t=parseBits(script,0,"Cp"); if(t!=null) { if(CMParms.getCleanBit(t[1],0).equalsIgnoreCase("p")) doIt=str.trim().equals(t[1].substring(1).trim()); else { Pattern P=patterns.get(t[1]); if(P==null) { P=Pattern.compile(t[1], Pattern.CASE_INSENSITIVE | Pattern.DOTALL); patterns.put(t[1],P); } final Matcher M=P.matcher(str); doIt=M.find(); if(doIt) str=str.substring(M.start()).trim(); } } if(doIt) { Item Tool=null; if(msg.tool() instanceof Item) Tool=(Item)msg.tool(); if(Tool==null) Tool=defaultItem; if(msg.target() instanceof MOB) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); else if(msg.target() instanceof Item) enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t); else enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t); return; } } break; } } } finally { recurseCounter.addAndGet(-1); } } protected int getTriggerCode(final String trigger, final String[] ttrigger) { final Integer I; if((ttrigger!=null)&&(ttrigger.length>0)) I=progH.get(ttrigger[0]); else { final int x=trigger.indexOf(' '); if(x<0) I=progH.get(trigger.toUpperCase().trim()); else I=progH.get(trigger.substring(0,x).toUpperCase().trim()); } if(I==null) return 0; return I.intValue(); } @Override public MOB getMakeMOB(final Tickable ticking) { MOB mob=null; if(ticking instanceof MOB) { mob=(MOB)ticking; if(!mob.amDead()) lastKnownLocation=mob.location(); } else if(ticking instanceof Environmental) { final Room R=CMLib.map().roomLocation((Environmental)ticking); if(R!=null) lastKnownLocation=R; if((backupMOB==null) ||(backupMOB.amDestroyed()) ||(backupMOB.amDead())) { backupMOB=CMClass.getMOB("StdMOB"); if(backupMOB!=null) { backupMOB.setName(ticking.name()); backupMOB.setDisplayText(L("@x1 is here.",ticking.name())); backupMOB.setDescription(""); backupMOB.setAgeMinutes(-1); mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) backupMOB.setLocation(lastKnownLocation); } } else { backupMOB.setAgeMinutes(-1); mob=backupMOB; if(backupMOB.location()!=lastKnownLocation) { backupMOB.setLocation(lastKnownLocation); backupMOB.setName(ticking.name()); backupMOB.setDisplayText(L("@x1 is here.",ticking.name())); } } } return mob; } protected boolean canTrigger(final int triggerCode) { final Long L=noTrigger.get(Integer.valueOf(triggerCode)); if(L==null) return true; if(System.currentTimeMillis()<L.longValue()) return false; noTrigger.remove(Integer.valueOf(triggerCode)); return true; } @Override public boolean tick(final Tickable ticking, final int tickID) { final Item defaultItem=(ticking instanceof Item)?(Item)ticking:null; final MOB mob; synchronized(this) // supposedly this will cause a sync between cpus of the object { mob=getMakeMOB(ticking); } if((mob==null)||(lastKnownLocation==null)) { altStatusTickable=null; return true; } final PhysicalAgent affecting=(ticking instanceof PhysicalAgent)?((PhysicalAgent)ticking):null; final List<DVector> scripts=getScripts(); if(!runInPassiveAreas) { final Area A=CMLib.map().areaLocation(ticking); if((A!=null)&&(A.getAreaState() != Area.State.ACTIVE)) { return true; } } if(defaultItem != null) { final ItemPossessor poss=defaultItem.owner(); if(poss instanceof MOB) { final Room R=((MOB)poss).location(); if((R==null)||(R.numInhabitants()==0)) { altStatusTickable=null; return true; } } } int triggerCode=-1; String trigger=""; String[] t=null; for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++) { final DVector script=scripts.get(thisScriptIndex); if(script.size()<2) continue; trigger=((String)script.elementAt(0,1)).toUpperCase().trim(); t=(String[])script.elementAt(0,2); triggerCode=getTriggerCode(trigger,t); tickStatus=Tickable.STATUS_SCRIPT+triggerCode; switch(triggerCode) { case 5: // rand_Prog if((!mob.amDead())&&canTrigger(5)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } } break; case 16: // delay_prog if((!mob.amDead())&&canTrigger(16)) { int targetTick=-1; final Integer thisScriptIndexI=Integer.valueOf(thisScriptIndex); final int[] delayProgCounter; synchronized(thisScriptIndexI) { if(delayTargetTimes.containsKey(thisScriptIndexI)) targetTick=delayTargetTimes.get(thisScriptIndexI).intValue(); else { if(t==null) t=parseBits(script,0,"CCR"); if(t!=null) { final int low=CMath.s_int(t[1]); int high=CMath.s_int(t[2]); if(high<low) high=low; targetTick=CMLib.dice().roll(1,high-low+1,low-1); delayTargetTimes.put(thisScriptIndexI,Integer.valueOf(targetTick)); } } if(delayProgCounters.containsKey(thisScriptIndexI)) delayProgCounter=delayProgCounters.get(thisScriptIndexI); else { delayProgCounter=new int[]{0}; delayProgCounters.put(thisScriptIndexI,delayProgCounter); } } boolean exec=false; synchronized(delayProgCounter) { if(delayProgCounter[0]>=targetTick) { exec=true; delayProgCounter[0]=0; } else delayProgCounter[0]++; } if(exec) execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } break; case 7: // fight_Prog if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs()); } } else if((ticking instanceof Item) &&canTrigger(7) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); if(CMLib.dice().rollPercentage()<prcnt) { final MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs()); } } } break; case 11: // hitprcnt_prog if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11)) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),mob.maxState().getHitPoints())); if(mob.curState().getHitPoints()<=floor) execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs()); } } else if((ticking instanceof Item) &&canTrigger(11) &&(((Item)ticking).owner() instanceof MOB) &&(((MOB)((Item)ticking).owner()).isInCombat())) { final MOB M=(MOB)((Item)ticking).owner(); if(!M.amDead()) { if(t==null) t=parseBits(script,0,"CR"); if(t!=null) { final int prcnt=CMath.s_int(t[1]); final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),M.maxState().getHitPoints())); if(M.curState().getHitPoints()<=floor) execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs()); } } } break; case 6: // once_prog if(!oncesDone.contains(script)&&canTrigger(6)) { if(t==null) t=parseBits(script,0,"C"); oncesDone.add(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } break; case 14: // time_prog if((mob.location()!=null) &&canTrigger(14) &&(!mob.amDead())) { if(t==null) t=parseBits(script,0,"CT"); int lastTimeProgDone=-1; if(lastTimeProgsDone.containsKey(Integer.valueOf(thisScriptIndex))) lastTimeProgDone=lastTimeProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue(); final int time=mob.location().getArea().getTimeObj().getHourOfDay(); if((t!=null)&&(lastTimeProgDone!=time)) { boolean done=false; for(int i=1;i<t.length;i++) { if(time==CMath.s_int(t[i])) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,""+time,newObjs()); lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex)); lastTimeProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(time)); break; } } if(!done) lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex)); } } break; case 15: // day_prog if((mob.location()!=null)&&canTrigger(15) &&(!mob.amDead())) { if(t==null) t=parseBits(script,0,"CT"); int lastDayProgDone=-1; if(lastDayProgsDone.containsKey(Integer.valueOf(thisScriptIndex))) lastDayProgDone=lastDayProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue(); final int day=mob.location().getArea().getTimeObj().getDayOfMonth(); if((t!=null)&&(lastDayProgDone!=day)) { boolean done=false; for(int i=1;i<t.length;i++) { if(day==CMath.s_int(t[i])) { done=true; execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex)); lastDayProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(day)); break; } } if(!done) lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex)); } } break; case 13: // quest_time_prog if(!oncesDone.contains(script)&&canTrigger(13)) { if(t==null) t=parseBits(script,0,"CCC"); if(t!=null) { final Quest Q=getQuest(t[1]); if((Q!=null) &&(Q.running()) &&(!Q.stopping()) &&(Q.duration()!=0)) { final int time=CMath.s_int(t[2]); if(time>=Q.minsRemaining()) { oncesDone.add(script); execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs()); } } } } break; default: break; } } tickStatus=Tickable.STATUS_SCRIPT+100; dequeResponses(); altStatusTickable=null; return true; } @Override public void initializeClass() { } @Override public int compareTo(final CMObject o) { return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o)); } public void enqueResponse(final PhysicalAgent host, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final DVector script, final int ticks, final String msg, final String[] triggerStr) { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return; if(que.size()>25) { this.logError(monster, "UNK", "SYS", "Attempt to enque more than 25 events (last was "+CMParms.toListString(triggerStr)+" )."); que.clear(); } if(noDelay) execute(host,source,target,monster,primaryItem,secondaryItem,script,msg,newObjs()); else que.add(new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg)); } public void prequeResponse(final PhysicalAgent host, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final DVector script, final int ticks, final String msg) { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return; if(que.size()>25) { this.logError(monster, "UNK", "SYS", "Attempt to pre que more than 25 events."); que.clear(); } que.add(0,new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg)); } @Override public void dequeResponses() { try { tickStatus=Tickable.STATUS_SCRIPT+100; for(int q=que.size()-1;q>=0;q--) { ScriptableResponse SB=null; try { SB=que.get(q); } catch(final ArrayIndexOutOfBoundsException x) { continue; } if(SB.checkTimeToExecute()) { execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs()); que.remove(SB); } } } catch (final Exception e) { Log.errOut("DefaultScriptingEngine", e); } } public String L(final String str, final String ... xs) { return CMLib.lang().fullSessionTranslation(str, xs); } protected static class JScriptEvent extends ScriptableObject { @Override public String getClassName() { return "JScriptEvent"; } static final long serialVersionUID = 43; final PhysicalAgent h; final MOB s; final Environmental t; final MOB m; final Item pi; final Item si; final Object[] objs; Vector<String> scr; final String message; final DefaultScriptingEngine c; public Environmental host() { return h; } public MOB source() { return s; } public Environmental target() { return t; } public MOB monster() { return m; } public Item item() { return pi; } public Item item2() { return si; } public String message() { return message; } public void setVar(final String host, final String var, final String value) { c.setVar(host,var.toUpperCase(),value); } public String getVar(final String host, final String var) { return c.getVar(host, var); } public String toJavaString(final Object O) { return Context.toString(O); } public String getCMType(final Object O) { if(O == null) return "null"; final CMObjectType typ = CMClass.getObjectType(O); if(typ == null) return "unknown"; return typ.name().toLowerCase(); } @Override public Object get(final String name, final Scriptable start) { if (super.has(name, start)) return super.get(name, start); if (methH.containsKey(name) || funcH.containsKey(name) || (name.endsWith("$")&&(funcH.containsKey(name.substring(0,name.length()-1))))) { return new Function() { @Override public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if(methH.containsKey(name)) { final StringBuilder strb=new StringBuilder(name); if(args.length==1) strb.append(" ").append(String.valueOf(args[0])); else for(int i=0;i<args.length;i++) { if(i==args.length-1) strb.append(" ").append(String.valueOf(args[i])); else strb.append(" ").append("'"+String.valueOf(args[i])+"'"); } final DVector DV=new DVector(2); DV.addElement("JS_PROG",null); DV.addElement(strb.toString(),null); return c.execute(h,s,t,m,pi,si,DV,message,objs); } if(name.endsWith("$")) { final StringBuilder strb=new StringBuilder(name.substring(0,name.length()-1)).append("("); if(args.length==1) strb.append(" ").append(String.valueOf(args[0])); else for(int i=0;i<args.length;i++) { if(i==args.length-1) strb.append(" ").append(String.valueOf(args[i])); else strb.append(" ").append("'"+String.valueOf(args[i])+"'"); } strb.append(" ) "); return c.functify(h,s,t,m,pi,si,message,objs,strb.toString()); } final String[] sargs=new String[args.length+3]; sargs[0]=name; sargs[1]="("; for(int i=0;i<args.length;i++) sargs[i+2]=String.valueOf(args[i]); sargs[sargs.length-1]=")"; final String[][] EVAL={sargs}; return Boolean.valueOf(c.eval(h,s,t,m,pi,si,message,objs,EVAL,0)); } @Override public void delete(final String arg0) { } @Override public void delete(final int arg0) { } @Override public Object get(final String arg0, final Scriptable arg1) { return null; } @Override public Object get(final int arg0, final Scriptable arg1) { return null; } @Override public String getClassName() { return null; } @Override public Object getDefaultValue(final Class<?> arg0) { return null; } @Override public Object[] getIds() { return null; } @Override public Scriptable getParentScope() { return null; } @Override public Scriptable getPrototype() { return null; } @Override public boolean has(final String arg0, final Scriptable arg1) { return false; } @Override public boolean has(final int arg0, final Scriptable arg1) { return false; } @Override public boolean hasInstance(final Scriptable arg0) { return false; } @Override public void put(final String arg0, final Scriptable arg1, final Object arg2) { } @Override public void put(final int arg0, final Scriptable arg1, final Object arg2) { } @Override public void setParentScope(final Scriptable arg0) { } @Override public void setPrototype(final Scriptable arg0) { } @Override public Scriptable construct(final Context arg0, final Scriptable arg1, final Object[] arg2) { return null; } }; } return super.get(name, start); } public void executeEvent(final DVector script, final int lineNum) { c.execute(h, s, t, m, pi, si, script, message, objs, lineNum); } public JScriptEvent(final DefaultScriptingEngine scrpt, final PhysicalAgent host, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp) { c=scrpt; h=host; s=source; t=target; m=monster; pi=primaryItem; si=secondaryItem; message=msg; objs=tmp; } } }
improved HAS debugging. git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@19100 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Common/DefaultScriptingEngine.java
improved HAS debugging.
<ide><path>om/planet_ink/coffee_mud/Common/DefaultScriptingEngine.java <ide> final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp); <ide> if(arg2.length()==0) <ide> { <del> logError(scripted,"HAS","Syntax",eval[0][t]); <add> logError(scripted,"HAS","Syntax","'"+eval[0][t]+"' in "+CMParms.toListString(eval[0])); <ide> return returnable; <ide> } <ide> if(E==null)
Java
apache-2.0
95c78f469c4eaa37dff7ca17dd16dd98e72c4ffb
0
jbartece/pnc,jdcasey/pnc,ruhan1/pnc,thescouser89/pnc,pkocandr/pnc,jbartece/pnc,alexcreasy/pnc,project-ncl/pnc,rnc/pnc,alexcreasy/pnc,matedo1/pnc,matedo1/pnc,jbartece/pnc,matedo1/pnc,ruhan1/pnc,alexcreasy/pnc,jdcasey/pnc,ruhan1/pnc,jdcasey/pnc,matejonnet/pnc
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.rest.restmodel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.NotBlank; import org.jboss.pnc.model.RepositoryConfiguration; import org.jboss.pnc.rest.validation.groups.WhenCreatingNew; import org.jboss.pnc.rest.validation.groups.WhenUpdating; import org.jboss.pnc.rest.validation.validators.ScmUrl; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import javax.xml.bind.annotation.XmlRootElement; /** * The REST entity that contains configuration of the SCM repositories. * * @author Jakub Bartecek */ @EqualsAndHashCode @ToString @Builder @AllArgsConstructor @XmlRootElement(name = "RepositoryConfiguration") public class RepositoryConfigurationRest implements GenericRestEntity<Integer> { @NotNull(groups = WhenUpdating.class) @Null(groups = WhenCreatingNew.class) private Integer id; @Getter @Setter @NotBlank(groups = {WhenUpdating.class}) @ScmUrl(groups = {WhenUpdating.class, WhenCreatingNew.class} ) private String internalUrl; @Getter @Setter @ScmUrl(groups = {WhenUpdating.class, WhenCreatingNew.class} ) private String externalUrl; @Getter @Setter private boolean preBuildSyncEnabled = true; public RepositoryConfigurationRest() { } public RepositoryConfigurationRest(RepositoryConfiguration repositoryConfiguration) { this.id = repositoryConfiguration.getId(); this.internalUrl = repositoryConfiguration.getInternalUrl(); this.externalUrl = repositoryConfiguration.getExternalUrl(); this.preBuildSyncEnabled = repositoryConfiguration.isPreBuildSyncEnabled(); } /** * Gets Id. * * @return Id. */ @Override public Integer getId() { return id; } /** * Sets id. * * @param id id. */ @Override public void setId(Integer id) { this.id = id; } public RepositoryConfiguration.Builder toDBEntityBuilder() { RepositoryConfiguration.Builder builder = RepositoryConfiguration.Builder.newBuilder() .id(id) .internalUrl(internalUrl) .externalUrl(externalUrl) .preBuildSyncEnabled(preBuildSyncEnabled); return builder; } }
rest-model/src/main/java/org/jboss/pnc/rest/restmodel/RepositoryConfigurationRest.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.rest.restmodel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.NotBlank; import org.jboss.pnc.model.RepositoryConfiguration; import org.jboss.pnc.rest.validation.groups.WhenCreatingNew; import org.jboss.pnc.rest.validation.groups.WhenUpdating; import org.jboss.pnc.rest.validation.validators.ScmUrl; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import javax.xml.bind.annotation.XmlRootElement; /** * The REST entity that contains configuration of the SCM repositories. * * @author Jakub Bartecek */ @EqualsAndHashCode @ToString @Builder @AllArgsConstructor @XmlRootElement(name = "RepositoryConfiguration") public class RepositoryConfigurationRest implements GenericRestEntity<Integer> { @NotNull(groups = WhenUpdating.class) @Null(groups = WhenCreatingNew.class) private Integer id; @Getter @Setter @NotBlank(groups = {WhenUpdating.class, WhenCreatingNew.class}) @ScmUrl(groups = {WhenUpdating.class, WhenCreatingNew.class} ) private String internalUrl; @Getter @Setter @ScmUrl(groups = {WhenUpdating.class, WhenCreatingNew.class} ) private String externalUrl; @Getter @Setter private boolean preBuildSyncEnabled = true; public RepositoryConfigurationRest() { } public RepositoryConfigurationRest(RepositoryConfiguration repositoryConfiguration) { this.id = repositoryConfiguration.getId(); this.internalUrl = repositoryConfiguration.getInternalUrl(); this.externalUrl = repositoryConfiguration.getExternalUrl(); this.preBuildSyncEnabled = repositoryConfiguration.isPreBuildSyncEnabled(); } /** * Gets Id. * * @return Id. */ @Override public Integer getId() { return id; } /** * Sets id. * * @param id id. */ @Override public void setId(Integer id) { this.id = id; } public RepositoryConfiguration.Builder toDBEntityBuilder() { RepositoryConfiguration.Builder builder = RepositoryConfiguration.Builder.newBuilder() .id(id) .internalUrl(internalUrl) .externalUrl(externalUrl) .preBuildSyncEnabled(preBuildSyncEnabled); return builder; } }
Allow empty internalURL when creating new RC.
rest-model/src/main/java/org/jboss/pnc/rest/restmodel/RepositoryConfigurationRest.java
Allow empty internalURL when creating new RC.
<ide><path>est-model/src/main/java/org/jboss/pnc/rest/restmodel/RepositoryConfigurationRest.java <ide> <ide> @Getter <ide> @Setter <del> @NotBlank(groups = {WhenUpdating.class, WhenCreatingNew.class}) <add> @NotBlank(groups = {WhenUpdating.class}) <ide> @ScmUrl(groups = {WhenUpdating.class, WhenCreatingNew.class} ) <ide> private String internalUrl; <ide>
Java
apache-2.0
cd31f467137aa60ef10f36f8b7dc86ce2014744f
0
graphhopper/graphhopper,fbonzon/graphhopper,fbonzon/graphhopper,graphhopper/graphhopper,boldtrn/graphhopper,fbonzon/graphhopper,boldtrn/graphhopper,boldtrn/graphhopper,boldtrn/graphhopper,graphhopper/graphhopper,fbonzon/graphhopper,graphhopper/graphhopper
/* * Copyright (c) 2015, Conveyal * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.conveyal.gtfs; import com.conveyal.gtfs.error.GTFSError; import com.conveyal.gtfs.error.GeneralError; import com.conveyal.gtfs.model.Calendar; import com.conveyal.gtfs.model.*; import com.google.common.collect.Iterables; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.CoordinateList; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.mapdb.BTreeMap; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun; import org.mapdb.Fun.Tuple2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.ConcurrentNavigableMap; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * All entities must be from a single feed namespace. * Composed of several GTFSTables. */ public class GTFSFeed implements Cloneable, Closeable { private static final Logger LOG = LoggerFactory.getLogger(GTFSFeed.class); public static final double METERS_PER_DEGREE_LATITUDE = 111111.111; private DB db; public String feedId = null; public final Map<String, Agency> agency; public final Map<String, FeedInfo> feedInfo; // This is how you do a multimap in mapdb: https://github.com/jankotek/MapDB/blob/release-1.0/src/test/java/examples/MultiMap.java public final NavigableSet<Tuple2<String, Frequency>> frequencies; public final Map<String, Route> routes; public final Map<String, Stop> stops; public final Map<String, Transfer> transfers; public final BTreeMap<String, Trip> trips; /** CRC32 of the GTFS file this was loaded from */ public long checksum; /* Map from 2-tuples of (shape_id, shape_pt_sequence) to shape points */ public final ConcurrentNavigableMap<Tuple2<String, Integer>, ShapePoint> shape_points; /* Map from 2-tuples of (trip_id, stop_sequence) to stoptimes. */ public final BTreeMap<Tuple2, StopTime> stop_times; /* A fare is a fare_attribute and all fare_rules that reference that fare_attribute. */ public final Map<String, Fare> fares; /* A service is a calendar entry and all calendar_dates that modify that calendar entry. */ public final BTreeMap<String, Service> services; /* A place to accumulate errors while the feed is loaded. Tolerate as many errors as possible and keep on loading. */ public final NavigableSet<GTFSError> errors; /* Create geometry factory to produce LineString geometries. */ private GeometryFactory gf = new GeometryFactory(); private boolean loaded = false; /** * The order in which we load the tables is important for two reasons. * 1. We must load feed_info first so we know the feed ID before loading any other entities. This could be relaxed * by having entities point to the feed object rather than its ID String. * 2. Referenced entities must be loaded before any entities that reference them. This is because we check * referential integrity while the files are being loaded. This is done on the fly during loading because it allows * us to associate a line number with errors in objects that don't have any other clear identifier. * * Interestingly, all references are resolvable when tables are loaded in alphabetical order. */ public void loadFromFile(ZipFile zip, String fid) throws IOException { if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database"); // NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not // simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a // long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated // probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent, // this will yield a nice uniformly distributed result, because when combining two bits there is an equal // probability of any input, which means an equal probability of any output. At least I think that's all correct. // Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory // of the zip file, so that's not a problem. checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong(); db.getAtomicLong("checksum").set(checksum); new FeedInfo.Loader(this).loadTable(zip); // maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading if (fid != null) { feedId = fid; LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else if (feedId == null || feedId.isEmpty()) { feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", ""); LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else { LOG.info("Feed ID is '{}'.", feedId); } db.getAtomicString("feed_id").set(feedId); new Agency.Loader(this).loadTable(zip); if (agency.isEmpty()) { errors.add(new GeneralError("agency", 0, "agency_id", "Need at least one agency.")); } // calendars and calendar dates are joined into services. This means a lot of manipulating service objects as // they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once // we're done loading them Map<String, Service> serviceTable = new HashMap<>(); new Calendar.Loader(this, serviceTable).loadTable(zip); new CalendarDate.Loader(this, serviceTable).loadTable(zip); this.services.putAll(serviceTable); serviceTable = null; // free memory // Same deal Map<String, Fare> fares = new HashMap<>(); new FareAttribute.Loader(this, fares).loadTable(zip); new FareRule.Loader(this, fares).loadTable(zip); this.fares.putAll(fares); fares = null; // free memory new Route.Loader(this).loadTable(zip); new ShapePoint.Loader(this).loadTable(zip); new Stop.Loader(this).loadTable(zip); new Transfer.Loader(this).loadTable(zip); new Trip.Loader(this).loadTable(zip); new Frequency.Loader(this).loadTable(zip); new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed loaded = true; } public void loadFromFileAndLogErrors(ZipFile zip) throws IOException { loadFromFile(zip, null); for (GTFSError error : errors) { LOG.error(error.getMessageWithContext()); } } public boolean hasFeedInfo () { return !this.feedInfo.isEmpty(); } public FeedInfo getFeedInfo () { return this.hasFeedInfo() ? this.feedInfo.values().iterator().next() : null; } /** * For the given trip ID, fetch all the stop times in order of increasing stop_sequence. * This is an efficient iteration over a tree map. */ public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) { Map<Fun.Tuple2, StopTime> tripStopTimes = stop_times.subMap( Fun.t2(trip_id, null), Fun.t2(trip_id, Fun.HI) ); return tripStopTimes.values(); } /** Get the shape for the given shape ID */ public Shape getShape (String shape_id) { Shape shape = new Shape(this, shape_id); return shape.shape_dist_traveled.length > 0 ? shape : null; } /** * For the given trip ID, fetch all the stop times in order, and interpolate stop-to-stop travel times. */ public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes { // clone stop times so as not to modify base GTFS structures StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .map(st -> st.clone()) .toArray(i -> new StopTime[i]); // avoid having to make sure that the array has length below. if (stopTimes.length == 0) return Collections.emptyList(); // first pass: set all partially filled stop times for (StopTime st : stopTimes) { if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) { st.departure_time = st.arrival_time; } if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) { st.arrival_time = st.departure_time; } } // quick check: ensure that first and last stops have times. // technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop, // but we are slightly more lenient and only insist that one of them be filled at both the first and last stop. // The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except // in the case of interlining). // it's fine to just check departure time, as the above pass ensures that all stop times have either both // arrival and departure times, or neither if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) { throw new FirstAndLastStopsDoNotHaveTimes(); } // second pass: fill complete stop times int startOfInterpolatedBlock = -1; for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) { if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) { startOfInterpolatedBlock = stopTime; } else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) { // we have found the end of the interpolated section int nInterpolatedStops = stopTime - startOfInterpolatedBlock; double totalLengthOfInterpolatedSection = 0; double[] lengthOfInterpolatedSections = new double[nInterpolatedStops]; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { Stop start = stops.get(stopTimes[stopTimeToInterpolate - 1].stop_id); Stop end = stops.get(stopTimes[stopTimeToInterpolate].stop_id); double segLen = fastDistance(start.stop_lat, start.stop_lon, end.stop_lat, end.stop_lon); totalLengthOfInterpolatedSection += segLen; lengthOfInterpolatedSections[i] = segLen; } // add the segment post-last-interpolated-stop Stop start = stops.get(stopTimes[stopTime - 1].stop_id); Stop end = stops.get(stopTimes[stopTime].stop_id); totalLengthOfInterpolatedSection += fastDistance(start.stop_lat, start.stop_lon, end.stop_lat, end.stop_lon); int departureBeforeInterpolation = stopTimes[startOfInterpolatedBlock - 1].departure_time; int arrivalAfterInterpolation = stopTimes[stopTime].arrival_time; int totalTime = arrivalAfterInterpolation - departureBeforeInterpolation; double lengthSoFar = 0; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { lengthSoFar += lengthOfInterpolatedSections[i]; int time = (int) (departureBeforeInterpolation + totalTime * (lengthSoFar / totalLengthOfInterpolatedSection)); stopTimes[stopTimeToInterpolate].arrival_time = stopTimes[stopTimeToInterpolate].departure_time = time; } // we're done with this block startOfInterpolatedBlock = -1; } } return Arrays.asList(stopTimes); } /** * @return Equirectangular approximation to distance. */ public static double fastDistance (double lat0, double lon0, double lat1, double lon1) { double midLat = (lat0 + lat1) / 2; double xscale = Math.cos(Math.toRadians(midLat)); double dx = xscale * (lon1 - lon0); double dy = (lat1 - lat0); return Math.sqrt(dx * dx + dy * dy) * METERS_PER_DEGREE_LATITUDE; } public Collection<Frequency> getFrequencies (String trip_id) { // IntelliJ tells me all these casts are unnecessary, and that's also my feeling, but the code won't compile // without them return (List<Frequency>) frequencies.subSet(new Fun.Tuple2(trip_id, null), new Fun.Tuple2(trip_id, Fun.HI)).stream() .map(t2 -> ((Tuple2<String, Frequency>) t2).b) .collect(Collectors.toList()); } public LineString getStraightLineForStops(String trip_id) { CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); Iterable<StopTime> stopTimes; stopTimes = getOrderedStopTimesForTrip(trip.trip_id); if (Iterables.size(stopTimes) > 1) { for (StopTime stopTime : stopTimes) { Stop stop = stops.get(stopTime.stop_id); Double lat = stop.stop_lat; Double lon = stop.stop_lon; coordinates.add(new Coordinate(lon, lat)); } ls = gf.createLineString(coordinates.toCoordinateArray()); } // set ls equal to null if there is only one stopTime to avoid an exception when creating linestring else{ ls = null; } return ls; } /** * Returns a trip geometry object (LineString) for a given trip id. * If the trip has a shape reference, this will be used for the geometry. * Otherwise, the ordered stoptimes will be used. * * @param trip_id trip id of desired trip geometry * @return the LineString representing the trip geometry. * @see LineString */ public LineString getTripGeometry(String trip_id){ CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); // If trip has shape_id, use it to generate geometry. if (trip.shape_id != null) { Shape shape = getShape(trip.shape_id); if (shape != null) ls = shape.geometry; } // Use the ordered stoptimes. if (ls == null) { ls = getStraightLineForStops(trip_id); } return ls; } /** * Cloning can be useful when you want to make only a few modifications to an existing feed. * Keep in mind that this is a shallow copy, so you'll have to create new maps in the clone for tables you want * to modify. */ @Override public GTFSFeed clone() { try { return (GTFSFeed) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void close () { db.close(); } /** Thrown when we cannot interpolate stop times because the first or last stops do not have times */ public class FirstAndLastStopsDoNotHaveTimes extends RuntimeException { /** do nothing */ } /** Create a GTFS feed in a temp file */ public GTFSFeed () { this(DBMaker.newTempFileDB() .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .deleteFilesAfterClose() .closeOnJvmShutdown() .compressionEnable() .make()); } /** Create a GTFS feed connected to a particular DB, which will be created if it does not exist. */ public GTFSFeed(File file) { this(constructDB(file)); } private static DB constructDB(File file) { DBMaker<?> dbMaker = DBMaker.newFileDB(file) .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .compressionEnable(); if (file.exists()) { dbMaker.readOnly(); } return dbMaker.make(); } private GTFSFeed (DB db) { this.db = db; agency = db.getTreeMap("agency"); feedInfo = db.getTreeMap("feed_info"); routes = db.getTreeMap("routes"); trips = db.getTreeMap("trips"); stop_times = db.getTreeMap("stop_times"); frequencies = db.getTreeSet("frequencies"); transfers = db.getTreeMap("transfers"); stops = db.getTreeMap("stops"); fares = db.getTreeMap("fares"); services = db.getTreeMap("services"); shape_points = db.getTreeMap("shape_points"); feedId = db.getAtomicString("feed_id").get(); checksum = db.getAtomicLong("checksum").get(); errors = db.getTreeSet("errors"); } public LocalDate getStartDate() { LocalDate startDate = getCalendarServiceRangeStart(); if (startDate == null) startDate = getCalendarDateStart(); return startDate; } public LocalDate getCalendarServiceRangeStart() { int startDate = 0; for (Service service : services.values()) { if (service.calendar == null) continue; if (startDate == 0 || service.calendar.start_date < startDate) { startDate = service.calendar.start_date; } } if (startDate == 0) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.getDefault()); return LocalDate.parse(String.valueOf(startDate), formatter); } public LocalDate getCalendarDateStart() { LocalDate startDate = null; for (Service service : services.values()) { for (LocalDate date : service.calendar_dates.keySet()) { if (startDate == null || date.isBefore(startDate)) startDate = date; } } return startDate; } public LocalDate getCalendarServiceRangeEnd() { int endDate = 0; for (Service service : services.values()) { if (service.calendar == null) continue; if (endDate == 0 || service.calendar.end_date > endDate) { endDate = service.calendar.end_date; } } if (endDate == 0) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.getDefault()); return LocalDate.parse(String.valueOf(endDate), formatter); } public LocalDate getEndDate() { LocalDate endDate = getCalendarServiceRangeEnd(); if (endDate == null) endDate = getCalendarDateEnd(); return endDate; } public LocalDate getCalendarDateEnd() { LocalDate endDate = null; for (Service service : services.values()) { for (LocalDate date : service.calendar_dates.keySet()) { if (endDate == null || date.isAfter(endDate)) endDate = date; } } return endDate; } }
reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java
/* * Copyright (c) 2015, Conveyal * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.conveyal.gtfs; import com.conveyal.gtfs.error.GTFSError; import com.conveyal.gtfs.error.GeneralError; import com.conveyal.gtfs.model.Calendar; import com.conveyal.gtfs.model.*; import com.google.common.collect.Iterables; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.CoordinateList; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.mapdb.BTreeMap; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun; import org.mapdb.Fun.Tuple2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.ConcurrentNavigableMap; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * All entities must be from a single feed namespace. * Composed of several GTFSTables. */ public class GTFSFeed implements Cloneable, Closeable { private static final Logger LOG = LoggerFactory.getLogger(GTFSFeed.class); public static final double METERS_PER_DEGREE_LATITUDE = 111111.111; private DB db; public String feedId = null; public final Map<String, Agency> agency; public final Map<String, FeedInfo> feedInfo; // This is how you do a multimap in mapdb: https://github.com/jankotek/MapDB/blob/release-1.0/src/test/java/examples/MultiMap.java public final NavigableSet<Tuple2<String, Frequency>> frequencies; public final Map<String, Route> routes; public final Map<String, Stop> stops; public final Map<String, Transfer> transfers; public final BTreeMap<String, Trip> trips; /** CRC32 of the GTFS file this was loaded from */ public long checksum; /* Map from 2-tuples of (shape_id, shape_pt_sequence) to shape points */ public final ConcurrentNavigableMap<Tuple2<String, Integer>, ShapePoint> shape_points; /* Map from 2-tuples of (trip_id, stop_sequence) to stoptimes. */ public final BTreeMap<Tuple2, StopTime> stop_times; /* A fare is a fare_attribute and all fare_rules that reference that fare_attribute. */ public final Map<String, Fare> fares; /* A service is a calendar entry and all calendar_dates that modify that calendar entry. */ public final BTreeMap<String, Service> services; /* A place to accumulate errors while the feed is loaded. Tolerate as many errors as possible and keep on loading. */ public final NavigableSet<GTFSError> errors; /* Create geometry factory to produce LineString geometries. */ private GeometryFactory gf = new GeometryFactory(); private boolean loaded = false; /** * The order in which we load the tables is important for two reasons. * 1. We must load feed_info first so we know the feed ID before loading any other entities. This could be relaxed * by having entities point to the feed object rather than its ID String. * 2. Referenced entities must be loaded before any entities that reference them. This is because we check * referential integrity while the files are being loaded. This is done on the fly during loading because it allows * us to associate a line number with errors in objects that don't have any other clear identifier. * * Interestingly, all references are resolvable when tables are loaded in alphabetical order. */ public void loadFromFile(ZipFile zip, String fid) throws IOException { if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database"); // NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not // simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a // long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated // probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent, // this will yield a nice uniformly distributed result, because when combining two bits there is an equal // probability of any input, which means an equal probability of any output. At least I think that's all correct. // Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory // of the zip file, so that's not a problem. checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong(); db.getAtomicLong("checksum").set(checksum); new FeedInfo.Loader(this).loadTable(zip); // maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading if (fid != null) { feedId = fid; LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else if (feedId == null || feedId.isEmpty()) { feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", ""); LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else { LOG.info("Feed ID is '{}'.", feedId); } db.getAtomicString("feed_id").set(feedId); new Agency.Loader(this).loadTable(zip); if (agency.isEmpty()) { errors.add(new GeneralError("agency", 0, "agency_id", "Need at least one agency.")); } // calendars and calendar dates are joined into services. This means a lot of manipulating service objects as // they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once // we're done loading them Map<String, Service> serviceTable = new HashMap<>(); new Calendar.Loader(this, serviceTable).loadTable(zip); new CalendarDate.Loader(this, serviceTable).loadTable(zip); this.services.putAll(serviceTable); serviceTable = null; // free memory // Same deal Map<String, Fare> fares = new HashMap<>(); new FareAttribute.Loader(this, fares).loadTable(zip); new FareRule.Loader(this, fares).loadTable(zip); this.fares.putAll(fares); fares = null; // free memory new Route.Loader(this).loadTable(zip); new ShapePoint.Loader(this).loadTable(zip); new Stop.Loader(this).loadTable(zip); new Transfer.Loader(this).loadTable(zip); new Trip.Loader(this).loadTable(zip); new Frequency.Loader(this).loadTable(zip); new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed loaded = true; } public void loadFromFileAndLogErrors(ZipFile zip) throws IOException { loadFromFile(zip, null); for (GTFSError error : errors) { LOG.error(error.getMessageWithContext()); } } public boolean hasFeedInfo () { return !this.feedInfo.isEmpty(); } public FeedInfo getFeedInfo () { return this.hasFeedInfo() ? this.feedInfo.values().iterator().next() : null; } /** * For the given trip ID, fetch all the stop times in order of increasing stop_sequence. * This is an efficient iteration over a tree map. */ public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) { Map<Fun.Tuple2, StopTime> tripStopTimes = stop_times.subMap( Fun.t2(trip_id, null), Fun.t2(trip_id, Fun.HI) ); return tripStopTimes.values(); } /** Get the shape for the given shape ID */ public Shape getShape (String shape_id) { Shape shape = new Shape(this, shape_id); return shape.shape_dist_traveled.length > 0 ? shape : null; } /** * For the given trip ID, fetch all the stop times in order, and interpolate stop-to-stop travel times. */ public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes { // clone stop times so as not to modify base GTFS structures StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .map(st -> st.clone()) .toArray(i -> new StopTime[i]); // avoid having to make sure that the array has length below. if (stopTimes.length == 0) return Collections.emptyList(); // first pass: set all partially filled stop times for (StopTime st : stopTimes) { if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) { st.departure_time = st.arrival_time; } if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) { st.arrival_time = st.departure_time; } } // quick check: ensure that first and last stops have times. // technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop, // but we are slightly more lenient and only insist that one of them be filled at both the first and last stop. // The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except // in the case of interlining). // it's fine to just check departure time, as the above pass ensures that all stop times have either both // arrival and departure times, or neither if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) { throw new FirstAndLastStopsDoNotHaveTimes(); } // second pass: fill complete stop times int startOfInterpolatedBlock = -1; for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) { if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) { startOfInterpolatedBlock = stopTime; } else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) { // we have found the end of the interpolated section int nInterpolatedStops = stopTime - startOfInterpolatedBlock; double totalLengthOfInterpolatedSection = 0; double[] lengthOfInterpolatedSections = new double[nInterpolatedStops]; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { Stop start = stops.get(stopTimes[stopTimeToInterpolate - 1].stop_id); Stop end = stops.get(stopTimes[stopTimeToInterpolate].stop_id); double segLen = fastDistance(start.stop_lat, start.stop_lon, end.stop_lat, end.stop_lon); totalLengthOfInterpolatedSection += segLen; lengthOfInterpolatedSections[i] = segLen; } // add the segment post-last-interpolated-stop Stop start = stops.get(stopTimes[stopTime - 1].stop_id); Stop end = stops.get(stopTimes[stopTime].stop_id); totalLengthOfInterpolatedSection += fastDistance(start.stop_lat, start.stop_lon, end.stop_lat, end.stop_lon); int departureBeforeInterpolation = stopTimes[startOfInterpolatedBlock - 1].departure_time; int arrivalAfterInterpolation = stopTimes[stopTime].arrival_time; int totalTime = arrivalAfterInterpolation - departureBeforeInterpolation; double lengthSoFar = 0; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { lengthSoFar += lengthOfInterpolatedSections[i]; int time = (int) (departureBeforeInterpolation + totalTime * (lengthSoFar / totalLengthOfInterpolatedSection)); stopTimes[stopTimeToInterpolate].arrival_time = stopTimes[stopTimeToInterpolate].departure_time = time; } // we're done with this block startOfInterpolatedBlock = -1; } } return Arrays.asList(stopTimes); } /** * @return Equirectangular approximation to distance. */ public static double fastDistance (double lat0, double lon0, double lat1, double lon1) { double midLat = (lat0 + lat1) / 2; double xscale = Math.cos(Math.toRadians(midLat)); double dx = xscale * (lon1 - lon0); double dy = (lat1 - lat0); return Math.sqrt(dx * dx + dy * dy) * METERS_PER_DEGREE_LATITUDE; } public Collection<Frequency> getFrequencies (String trip_id) { // IntelliJ tells me all these casts are unnecessary, and that's also my feeling, but the code won't compile // without them return (List<Frequency>) frequencies.subSet(new Fun.Tuple2(trip_id, null), new Fun.Tuple2(trip_id, Fun.HI)).stream() .map(t2 -> ((Tuple2<String, Frequency>) t2).b) .collect(Collectors.toList()); } public LineString getStraightLineForStops(String trip_id) { CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); Iterable<StopTime> stopTimes; stopTimes = getOrderedStopTimesForTrip(trip.trip_id); if (Iterables.size(stopTimes) > 1) { for (StopTime stopTime : stopTimes) { Stop stop = stops.get(stopTime.stop_id); Double lat = stop.stop_lat; Double lon = stop.stop_lon; coordinates.add(new Coordinate(lon, lat)); } ls = gf.createLineString(coordinates.toCoordinateArray()); } // set ls equal to null if there is only one stopTime to avoid an exception when creating linestring else{ ls = null; } return ls; } /** * Returns a trip geometry object (LineString) for a given trip id. * If the trip has a shape reference, this will be used for the geometry. * Otherwise, the ordered stoptimes will be used. * * @param trip_id trip id of desired trip geometry * @return the LineString representing the trip geometry. * @see LineString */ public LineString getTripGeometry(String trip_id){ CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); // If trip has shape_id, use it to generate geometry. if (trip.shape_id != null) { Shape shape = getShape(trip.shape_id); if (shape != null) ls = shape.geometry; } // Use the ordered stoptimes. if (ls == null) { ls = getStraightLineForStops(trip_id); } return ls; } /** * Cloning can be useful when you want to make only a few modifications to an existing feed. * Keep in mind that this is a shallow copy, so you'll have to create new maps in the clone for tables you want * to modify. */ @Override public GTFSFeed clone() { try { return (GTFSFeed) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void close () { db.close(); } /** Thrown when we cannot interpolate stop times because the first or last stops do not have times */ public class FirstAndLastStopsDoNotHaveTimes extends RuntimeException { /** do nothing */ } /** Create a GTFS feed in a temp file */ public GTFSFeed () { // calls to this must be first operation in constructor - why, Java? this(DBMaker.newTempFileDB() .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .deleteFilesAfterClose() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make()); // TODO db.close(); } /** Create a GTFS feed connected to a particular DB, which will be created if it does not exist. */ public GTFSFeed(File file) { this(constructDB(file)); } private static DB constructDB(File file) { DBMaker<?> dbMaker = DBMaker.newFileDB(file) .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .compressionEnable(); if (file.exists()) { dbMaker.readOnly(); } return dbMaker.make(); } private GTFSFeed (DB db) { this.db = db; agency = db.getTreeMap("agency"); feedInfo = db.getTreeMap("feed_info"); routes = db.getTreeMap("routes"); trips = db.getTreeMap("trips"); stop_times = db.getTreeMap("stop_times"); frequencies = db.getTreeSet("frequencies"); transfers = db.getTreeMap("transfers"); stops = db.getTreeMap("stops"); fares = db.getTreeMap("fares"); services = db.getTreeMap("services"); shape_points = db.getTreeMap("shape_points"); feedId = db.getAtomicString("feed_id").get(); checksum = db.getAtomicLong("checksum").get(); errors = db.getTreeSet("errors"); } public LocalDate getStartDate() { LocalDate startDate = getCalendarServiceRangeStart(); if (startDate == null) startDate = getCalendarDateStart(); return startDate; } public LocalDate getCalendarServiceRangeStart() { int startDate = 0; for (Service service : services.values()) { if (service.calendar == null) continue; if (startDate == 0 || service.calendar.start_date < startDate) { startDate = service.calendar.start_date; } } if (startDate == 0) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.getDefault()); return LocalDate.parse(String.valueOf(startDate), formatter); } public LocalDate getCalendarDateStart() { LocalDate startDate = null; for (Service service : services.values()) { for (LocalDate date : service.calendar_dates.keySet()) { if (startDate == null || date.isBefore(startDate)) startDate = date; } } return startDate; } public LocalDate getCalendarServiceRangeEnd() { int endDate = 0; for (Service service : services.values()) { if (service.calendar == null) continue; if (endDate == 0 || service.calendar.end_date > endDate) { endDate = service.calendar.end_date; } } if (endDate == 0) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.getDefault()); return LocalDate.parse(String.valueOf(endDate), formatter); } public LocalDate getEndDate() { LocalDate endDate = getCalendarServiceRangeEnd(); if (endDate == null) endDate = getCalendarDateEnd(); return endDate; } public LocalDate getCalendarDateEnd() { LocalDate endDate = null; for (Service service : services.values()) { for (LocalDate date : service.calendar_dates.keySet()) { if (endDate == null || date.isAfter(endDate)) endDate = date; } } return endDate; } }
closeOnJvmShutdown and deleteFilesAfterClose temporary files in test; fixes #2325
reader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java
closeOnJvmShutdown and deleteFilesAfterClose temporary files in test; fixes #2325
<ide><path>eader-gtfs/src/main/java/com/conveyal/gtfs/GTFSFeed.java <ide> <ide> /** Create a GTFS feed in a temp file */ <ide> public GTFSFeed () { <del> // calls to this must be first operation in constructor - why, Java? <ide> this(DBMaker.newTempFileDB() <ide> .transactionDisable() <ide> .mmapFileEnable() <ide> .asyncWriteEnable() <ide> .deleteFilesAfterClose() <add> .closeOnJvmShutdown() <ide> .compressionEnable() <del> // .cacheSize(1024 * 1024) this bloats memory consumption <del> .make()); // TODO db.close(); <add> .make()); <ide> } <ide> <ide> /** Create a GTFS feed connected to a particular DB, which will be created if it does not exist. */
Java
apache-2.0
2e02c01ab33b42e5727d2f3e63371cae7b2e6c78
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.richcopy; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.FontPreferences; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.ex.MarkupIterator; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.editor.impl.FontFallbackIterator; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.editor.richcopy.model.SyntaxInfo; import com.intellij.openapi.util.SystemInfo; import com.intellij.psi.TokenType; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.Arrays; import java.util.Comparator; public final class SyntaxInfoBuilder { private SyntaxInfoBuilder() { } @NotNull static MyMarkupIterator createMarkupIterator(@NotNull EditorHighlighter highlighter, @NotNull CharSequence text, @NotNull EditorColorsScheme schemeToUse, @Nullable MarkupModel markupModel, int startOffsetToUse, int endOffset) { CompositeRangeIterator iterator = new CompositeRangeIterator( schemeToUse, new HighlighterRangeIterator(highlighter, startOffsetToUse, endOffset), new MarkupModelRangeIterator(markupModel, schemeToUse, startOffsetToUse, endOffset) ); return new MyMarkupIterator(text, iterator, schemeToUse); } public interface RangeIterator { boolean atEnd(); void advance(); int getRangeStart(); int getRangeEnd(); TextAttributes getTextAttributes(); void dispose(); } static class MyMarkupIterator { private final SegmentIterator mySegmentIterator; private final RangeIterator myRangeIterator; private int myCurrentFontStyle; private Color myCurrentForegroundColor; private Color myCurrentBackgroundColor; MyMarkupIterator(@NotNull CharSequence charSequence, @NotNull RangeIterator rangeIterator, @NotNull EditorColorsScheme colorsScheme) { myRangeIterator = rangeIterator; mySegmentIterator = new SegmentIterator(charSequence, colorsScheme.getFontPreferences()); } public boolean atEnd() { return myRangeIterator.atEnd() && mySegmentIterator.atEnd(); } public void advance() { if (mySegmentIterator.atEnd()) { myRangeIterator.advance(); TextAttributes textAttributes = myRangeIterator.getTextAttributes(); myCurrentFontStyle = textAttributes == null ? Font.PLAIN : textAttributes.getFontType(); myCurrentForegroundColor = textAttributes == null ? null : textAttributes.getForegroundColor(); myCurrentBackgroundColor = textAttributes == null ? null : textAttributes.getBackgroundColor(); mySegmentIterator.reset(myRangeIterator.getRangeStart(), myRangeIterator.getRangeEnd(), myCurrentFontStyle); } mySegmentIterator.advance(); } public int getStartOffset() { return mySegmentIterator.getCurrentStartOffset(); } public int getEndOffset() { return mySegmentIterator.getCurrentEndOffset(); } public int getFontStyle() { return myCurrentFontStyle; } @NotNull public String getFontFamilyName() { return mySegmentIterator.getCurrentFontFamilyName(); } @Nullable public Color getForegroundColor() { return myCurrentForegroundColor; } @Nullable public Color getBackgroundColor() { return myCurrentBackgroundColor; } public void dispose() { myRangeIterator.dispose(); } } static class CompositeRangeIterator implements RangeIterator { private final @NotNull Color myDefaultForeground; private final @NotNull Color myDefaultBackground; private final IteratorWrapper[] myIterators; private final TextAttributes myMergedAttributes = new TextAttributes(); private int overlappingRangesCount; private int myCurrentStart; private int myCurrentEnd; // iterators have priority corresponding to their order in the parameter list - rightmost having the largest priority CompositeRangeIterator(@NotNull EditorColorsScheme colorsScheme, RangeIterator... iterators) { myDefaultForeground = colorsScheme.getDefaultForeground(); myDefaultBackground = colorsScheme.getDefaultBackground(); myIterators = new IteratorWrapper[iterators.length]; for (int i = 0; i < iterators.length; i++) { myIterators[i] = new IteratorWrapper(iterators[i], i); } } @Override public boolean atEnd() { boolean validIteratorExists = false; for (int i = 0; i < myIterators.length; i++) { IteratorWrapper wrapper = myIterators[i]; if (wrapper == null) { continue; } RangeIterator iterator = wrapper.iterator; if (!iterator.atEnd() || overlappingRangesCount > 0 && (i >= overlappingRangesCount || iterator.getRangeEnd() > myCurrentEnd)) { validIteratorExists = true; } } return !validIteratorExists; } @Override public void advance() { int max = overlappingRangesCount == 0 ? myIterators.length : overlappingRangesCount; for (int i = 0; i < max; i++) { IteratorWrapper wrapper = myIterators[i]; if (wrapper == null) { continue; } RangeIterator iterator = wrapper.iterator; if (overlappingRangesCount > 0 && iterator.getRangeEnd() > myCurrentEnd) { continue; } if (iterator.atEnd()) { iterator.dispose(); myIterators[i] = null; } else { iterator.advance(); } } Arrays.sort(myIterators, RANGE_SORTER); myCurrentStart = Math.max(myIterators[0].iterator.getRangeStart(), myCurrentEnd); myCurrentEnd = Integer.MAX_VALUE; //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myIterators.length; i++) { IteratorWrapper wrapper = myIterators[i]; if (wrapper == null) { break; } RangeIterator iterator = wrapper.iterator; int nearestBound; if (iterator.getRangeStart() > myCurrentStart) { nearestBound = iterator.getRangeStart(); } else { nearestBound = iterator.getRangeEnd(); } myCurrentEnd = Math.min(myCurrentEnd, nearestBound); } for (overlappingRangesCount = 1; overlappingRangesCount < myIterators.length; overlappingRangesCount++) { IteratorWrapper wrapper = myIterators[overlappingRangesCount]; if (wrapper == null || wrapper.iterator.getRangeStart() > myCurrentStart) { break; } } } private final Comparator<IteratorWrapper> RANGE_SORTER = new Comparator<IteratorWrapper>() { @Override public int compare(IteratorWrapper o1, IteratorWrapper o2) { if (o1 == null) { return 1; } if (o2 == null) { return -1; } int startDiff = Math.max(o1.iterator.getRangeStart(), myCurrentEnd) - Math.max(o2.iterator.getRangeStart(), myCurrentEnd); if (startDiff != 0) { return startDiff; } return o2.order - o1.order; } }; @Override public int getRangeStart() { return myCurrentStart; } @Override public int getRangeEnd() { return myCurrentEnd; } @Override public TextAttributes getTextAttributes() { TextAttributes ta = myIterators[0].iterator.getTextAttributes(); myMergedAttributes.setAttributes(ta.getForegroundColor(), ta.getBackgroundColor(), null, null, null, ta.getFontType()); for (int i = 1; i < overlappingRangesCount; i++) { merge(myIterators[i].iterator.getTextAttributes()); } return myMergedAttributes; } private void merge(TextAttributes attributes) { Color myBackground = myMergedAttributes.getBackgroundColor(); if (myBackground == null || myDefaultBackground.equals(myBackground)) { myMergedAttributes.setBackgroundColor(attributes.getBackgroundColor()); } Color myForeground = myMergedAttributes.getForegroundColor(); if (myForeground == null || myDefaultForeground.equals(myForeground)) { myMergedAttributes.setForegroundColor(attributes.getForegroundColor()); } if (myMergedAttributes.getFontType() == Font.PLAIN) { myMergedAttributes.setFontType(attributes.getFontType()); } } @Override public void dispose() { for (IteratorWrapper wrapper : myIterators) { if (wrapper != null) { wrapper.iterator.dispose(); } } } private static class IteratorWrapper { private final RangeIterator iterator; private final int order; private IteratorWrapper(RangeIterator iterator, int order) { this.iterator = iterator; this.order = order; } } } private static class MarkupModelRangeIterator implements RangeIterator { private final boolean myUnsupportedModel; private final int myStartOffset; private final int myEndOffset; private final EditorColorsScheme myColorsScheme; private final Color myDefaultForeground; private final Color myDefaultBackground; private final MarkupIterator<RangeHighlighterEx> myIterator; private int myCurrentStart; private int myCurrentEnd; private TextAttributes myCurrentAttributes; private int myNextStart; private int myNextEnd; private TextAttributes myNextAttributes; private MarkupModelRangeIterator(@Nullable MarkupModel markupModel, @NotNull EditorColorsScheme colorsScheme, int startOffset, int endOffset) { myStartOffset = startOffset; myEndOffset = endOffset; myColorsScheme = colorsScheme; myDefaultForeground = colorsScheme.getDefaultForeground(); myDefaultBackground = colorsScheme.getDefaultBackground(); myUnsupportedModel = !(markupModel instanceof MarkupModelEx); if (myUnsupportedModel) { myIterator = null; return; } myIterator = ((MarkupModelEx)markupModel).overlappingIterator(startOffset, endOffset); try { findNextSuitableRange(); } catch (RuntimeException | Error e) { myIterator.dispose(); throw e; } } @Override public boolean atEnd() { return myUnsupportedModel || myNextAttributes == null; } @Override public void advance() { myCurrentStart = myNextStart; myCurrentEnd = myNextEnd; myCurrentAttributes = myNextAttributes; findNextSuitableRange(); } private void findNextSuitableRange() { myNextAttributes = null; while (myIterator.hasNext()) { RangeHighlighterEx highlighter = myIterator.next(); if (highlighter == null || !highlighter.isValid() || !isInterestedInLayer(highlighter.getLayer())) { continue; } // LINES_IN_RANGE highlighters are not supported currently myNextStart = Math.max(highlighter.getStartOffset(), myStartOffset); myNextEnd = Math.min(highlighter.getEndOffset(), myEndOffset); if (myNextStart >= myEndOffset) { break; } if (myNextStart < myCurrentEnd) { continue; // overlapping ranges withing document markup model are not supported currently } TextAttributes attributes = null; HighlightInfo info = HighlightInfo.fromRangeHighlighter(highlighter); if (info != null) { TextAttributesKey key = info.forcedTextAttributesKey; if (key == null) { HighlightInfoType type = info.type; key = type.getAttributesKey(); } if (key != null) { attributes = myColorsScheme.getAttributes(key); } } if (attributes == null) { continue; } Color foreground = attributes.getForegroundColor(); Color background = attributes.getBackgroundColor(); if ((foreground == null || myDefaultForeground.equals(foreground)) && (background == null || myDefaultBackground.equals(background)) && attributes.getFontType() == Font.PLAIN) { continue; } myNextAttributes = attributes; break; } } private static boolean isInterestedInLayer(int layer) { return layer != HighlighterLayer.CARET_ROW && layer != HighlighterLayer.SELECTION && layer != HighlighterLayer.ERROR && layer != HighlighterLayer.WARNING && layer != HighlighterLayer.ELEMENT_UNDER_CARET; } @Override public int getRangeStart() { return myCurrentStart; } @Override public int getRangeEnd() { return myCurrentEnd; } @Override public TextAttributes getTextAttributes() { return myCurrentAttributes; } @Override public void dispose() { if (myIterator != null) { myIterator.dispose(); } } } static class HighlighterRangeIterator implements RangeIterator { private static final TextAttributes EMPTY_ATTRIBUTES = new TextAttributes(); private final HighlighterIterator myIterator; private final int myStartOffset; private final int myEndOffset; private int myCurrentStart; private int myCurrentEnd; private TextAttributes myCurrentAttributes; HighlighterRangeIterator(@NotNull EditorHighlighter highlighter, int startOffset, int endOffset) { myStartOffset = startOffset; myEndOffset = endOffset; myIterator = highlighter.createIterator(startOffset); } @Override public boolean atEnd() { return myIterator.atEnd() || getCurrentStart() >= myEndOffset; } private int getCurrentStart() { return Math.max(myIterator.getStart(), myStartOffset); } private int getCurrentEnd() { return Math.min(myIterator.getEnd(), myEndOffset); } @Override public void advance() { myCurrentStart = getCurrentStart(); myCurrentEnd = getCurrentEnd(); myCurrentAttributes = myIterator.getTokenType() == TokenType.BAD_CHARACTER ? EMPTY_ATTRIBUTES : myIterator.getTextAttributes(); myIterator.advance(); } @Override public int getRangeStart() { return myCurrentStart; } @Override public int getRangeEnd() { return myCurrentEnd; } @Override public TextAttributes getTextAttributes() { return myCurrentAttributes; } @Override public void dispose() { } } private static class SegmentIterator { private final FontFallbackIterator myIterator = new FontFallbackIterator(); private final CharSequence myCharSequence; private int myEndOffset; private boolean myAdvanceCalled; private SegmentIterator(CharSequence charSequence, FontPreferences fontPreferences) { myCharSequence = charSequence; myIterator.setPreferredFonts(fontPreferences); } public void reset(int startOffset, int endOffset, int fontStyle) { myIterator.setFontStyle(fontStyle); myIterator.start(myCharSequence, startOffset, endOffset); myEndOffset = endOffset; myAdvanceCalled = false; } public boolean atEnd() { return myIterator.atEnd() || myIterator.getEnd() == myEndOffset; } public void advance() { if (!myAdvanceCalled) { myAdvanceCalled = true; return; } myIterator.advance(); } public int getCurrentStartOffset() { return myIterator.getStart(); } public int getCurrentEndOffset() { return myIterator.getEnd(); } public String getCurrentFontFamilyName() { return myIterator.getFont().getFamily(); } } static class Context { private final SyntaxInfo.Builder builder; @NotNull private final CharSequence myText; @NotNull private final Color myDefaultForeground; @NotNull private final Color myDefaultBackground; @Nullable private Color myBackground; @Nullable private Color myForeground; @Nullable private String myFontFamilyName; private final int myIndentSymbolsToStrip; private int myFontStyle = -1; private int myStartOffset = -1; private int myOffsetShift = 0; private int myIndentSymbolsToStripAtCurrentLine; Context(@NotNull CharSequence charSequence, @NotNull EditorColorsScheme scheme, int indentSymbolsToStrip) { myText = charSequence; myDefaultForeground = scheme.getDefaultForeground(); myDefaultBackground = scheme.getDefaultBackground(); int javaFontSize = scheme.getEditorFontSize(); float fontSize = SystemInfo.isMac || ApplicationManager.getApplication().isHeadlessEnvironment() ? javaFontSize : javaFontSize * 0.75f / UISettings.getDefFontScale(); // matching font size in external apps builder = new SyntaxInfo.Builder(myDefaultForeground, myDefaultBackground, fontSize); myIndentSymbolsToStrip = indentSymbolsToStrip; } public void reset(int offsetShiftDelta) { myStartOffset = -1; myOffsetShift += offsetShiftDelta; myIndentSymbolsToStripAtCurrentLine = 0; } public void iterate(MyMarkupIterator iterator, int endOffset) { while (!iterator.atEnd()) { iterator.advance(); int startOffset = iterator.getStartOffset(); if (startOffset >= endOffset) { break; } if (myStartOffset < 0) { myStartOffset = startOffset; } boolean whiteSpacesOnly = CharArrayUtil.isEmptyOrSpaces(myText, startOffset, iterator.getEndOffset()); processBackground(startOffset, iterator.getBackgroundColor()); if (!whiteSpacesOnly) { processForeground(startOffset, iterator.getForegroundColor()); processFontFamilyName(startOffset, iterator.getFontFamilyName()); processFontStyle(startOffset, iterator.getFontStyle()); } } addTextIfPossible(endOffset); } private void processFontStyle(int startOffset, int fontStyle) { if (fontStyle != myFontStyle) { addTextIfPossible(startOffset); builder.addFontStyle(fontStyle); myFontStyle = fontStyle; } } private void processFontFamilyName(int startOffset, String fontName) { String fontFamilyName = FontMapper.getPhysicalFontName(fontName); if (!fontFamilyName.equals(myFontFamilyName)) { addTextIfPossible(startOffset); builder.addFontFamilyName(fontFamilyName); myFontFamilyName = fontFamilyName; } } private void processForeground(int startOffset, Color foreground) { if (myForeground == null && foreground != null) { addTextIfPossible(startOffset); myForeground = foreground; builder.addForeground(foreground); } else if (myForeground != null) { Color c = foreground == null ? myDefaultForeground : foreground; if (!myForeground.equals(c)) { addTextIfPossible(startOffset); builder.addForeground(c); myForeground = c; } } } private void processBackground(int startOffset, Color background) { if (myBackground == null && background != null && !myDefaultBackground.equals(background)) { addTextIfPossible(startOffset); myBackground = background; builder.addBackground(background); } else if (myBackground != null) { Color c = background == null ? myDefaultBackground : background; if (!myBackground.equals(c)) { addTextIfPossible(startOffset); builder.addBackground(c); myBackground = c; } } } private void addTextIfPossible(int endOffset) { if (endOffset <= myStartOffset) { return; } for (int i = myStartOffset; i < endOffset; i++) { char c = myText.charAt(i); switch (c) { case '\r': if (i + 1 < myText.length() && myText.charAt(i + 1) == '\n') { myIndentSymbolsToStripAtCurrentLine = myIndentSymbolsToStrip; builder.addText(myStartOffset + myOffsetShift, i + myOffsetShift + 1); myStartOffset = i + 2; myOffsetShift--; //noinspection AssignmentToForLoopParameter i++; break; } // Intended fall-through. case '\n': myIndentSymbolsToStripAtCurrentLine = myIndentSymbolsToStrip; builder.addText(myStartOffset + myOffsetShift, i + myOffsetShift + 1); myStartOffset = i + 1; break; // Intended fall-through. case ' ': case '\t': if (myIndentSymbolsToStripAtCurrentLine > 0) { myIndentSymbolsToStripAtCurrentLine--; myStartOffset++; continue; } default: myIndentSymbolsToStripAtCurrentLine = 0; } } if (myStartOffset < endOffset) { builder.addText(myStartOffset + myOffsetShift, endOffset + myOffsetShift); myStartOffset = endOffset; } } void addCharacter(int position) { builder.addText(position + myOffsetShift, position + myOffsetShift + 1); } @NotNull public SyntaxInfo finish() { return builder.build(); } } }
platform/lang-impl/src/com/intellij/openapi/editor/richcopy/SyntaxInfoBuilder.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.richcopy; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.FontPreferences; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.ex.MarkupIterator; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.editor.impl.FontFallbackIterator; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.editor.richcopy.model.SyntaxInfo; import com.intellij.openapi.util.SystemInfo; import com.intellij.psi.TokenType; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.Arrays; import java.util.Comparator; public final class SyntaxInfoBuilder { private SyntaxInfoBuilder() { } @NotNull static MyMarkupIterator createMarkupIterator(@NotNull EditorHighlighter highlighter, @NotNull CharSequence text, @NotNull EditorColorsScheme schemeToUse, @NotNull MarkupModel markupModel, int startOffsetToUse, int endOffset) { CompositeRangeIterator iterator = new CompositeRangeIterator( schemeToUse, new HighlighterRangeIterator(highlighter, startOffsetToUse, endOffset), new MarkupModelRangeIterator(markupModel, schemeToUse, startOffsetToUse, endOffset) ); return new MyMarkupIterator(text, iterator, schemeToUse); } public interface RangeIterator { boolean atEnd(); void advance(); int getRangeStart(); int getRangeEnd(); TextAttributes getTextAttributes(); void dispose(); } static class MyMarkupIterator { private final SegmentIterator mySegmentIterator; private final RangeIterator myRangeIterator; private int myCurrentFontStyle; private Color myCurrentForegroundColor; private Color myCurrentBackgroundColor; MyMarkupIterator(@NotNull CharSequence charSequence, @NotNull RangeIterator rangeIterator, @NotNull EditorColorsScheme colorsScheme) { myRangeIterator = rangeIterator; mySegmentIterator = new SegmentIterator(charSequence, colorsScheme.getFontPreferences()); } public boolean atEnd() { return myRangeIterator.atEnd() && mySegmentIterator.atEnd(); } public void advance() { if (mySegmentIterator.atEnd()) { myRangeIterator.advance(); TextAttributes textAttributes = myRangeIterator.getTextAttributes(); myCurrentFontStyle = textAttributes == null ? Font.PLAIN : textAttributes.getFontType(); myCurrentForegroundColor = textAttributes == null ? null : textAttributes.getForegroundColor(); myCurrentBackgroundColor = textAttributes == null ? null : textAttributes.getBackgroundColor(); mySegmentIterator.reset(myRangeIterator.getRangeStart(), myRangeIterator.getRangeEnd(), myCurrentFontStyle); } mySegmentIterator.advance(); } public int getStartOffset() { return mySegmentIterator.getCurrentStartOffset(); } public int getEndOffset() { return mySegmentIterator.getCurrentEndOffset(); } public int getFontStyle() { return myCurrentFontStyle; } @NotNull public String getFontFamilyName() { return mySegmentIterator.getCurrentFontFamilyName(); } @Nullable public Color getForegroundColor() { return myCurrentForegroundColor; } @Nullable public Color getBackgroundColor() { return myCurrentBackgroundColor; } public void dispose() { myRangeIterator.dispose(); } } static class CompositeRangeIterator implements RangeIterator { private final @NotNull Color myDefaultForeground; private final @NotNull Color myDefaultBackground; private final IteratorWrapper[] myIterators; private final TextAttributes myMergedAttributes = new TextAttributes(); private int overlappingRangesCount; private int myCurrentStart; private int myCurrentEnd; // iterators have priority corresponding to their order in the parameter list - rightmost having the largest priority CompositeRangeIterator(@NotNull EditorColorsScheme colorsScheme, RangeIterator... iterators) { myDefaultForeground = colorsScheme.getDefaultForeground(); myDefaultBackground = colorsScheme.getDefaultBackground(); myIterators = new IteratorWrapper[iterators.length]; for (int i = 0; i < iterators.length; i++) { myIterators[i] = new IteratorWrapper(iterators[i], i); } } @Override public boolean atEnd() { boolean validIteratorExists = false; for (int i = 0; i < myIterators.length; i++) { IteratorWrapper wrapper = myIterators[i]; if (wrapper == null) { continue; } RangeIterator iterator = wrapper.iterator; if (!iterator.atEnd() || overlappingRangesCount > 0 && (i >= overlappingRangesCount || iterator.getRangeEnd() > myCurrentEnd)) { validIteratorExists = true; } } return !validIteratorExists; } @Override public void advance() { int max = overlappingRangesCount == 0 ? myIterators.length : overlappingRangesCount; for (int i = 0; i < max; i++) { IteratorWrapper wrapper = myIterators[i]; if (wrapper == null) { continue; } RangeIterator iterator = wrapper.iterator; if (overlappingRangesCount > 0 && iterator.getRangeEnd() > myCurrentEnd) { continue; } if (iterator.atEnd()) { iterator.dispose(); myIterators[i] = null; } else { iterator.advance(); } } Arrays.sort(myIterators, RANGE_SORTER); myCurrentStart = Math.max(myIterators[0].iterator.getRangeStart(), myCurrentEnd); myCurrentEnd = Integer.MAX_VALUE; //noinspection ForLoopReplaceableByForEach for (int i = 0; i < myIterators.length; i++) { IteratorWrapper wrapper = myIterators[i]; if (wrapper == null) { break; } RangeIterator iterator = wrapper.iterator; int nearestBound; if (iterator.getRangeStart() > myCurrentStart) { nearestBound = iterator.getRangeStart(); } else { nearestBound = iterator.getRangeEnd(); } myCurrentEnd = Math.min(myCurrentEnd, nearestBound); } for (overlappingRangesCount = 1; overlappingRangesCount < myIterators.length; overlappingRangesCount++) { IteratorWrapper wrapper = myIterators[overlappingRangesCount]; if (wrapper == null || wrapper.iterator.getRangeStart() > myCurrentStart) { break; } } } private final Comparator<IteratorWrapper> RANGE_SORTER = new Comparator<IteratorWrapper>() { @Override public int compare(IteratorWrapper o1, IteratorWrapper o2) { if (o1 == null) { return 1; } if (o2 == null) { return -1; } int startDiff = Math.max(o1.iterator.getRangeStart(), myCurrentEnd) - Math.max(o2.iterator.getRangeStart(), myCurrentEnd); if (startDiff != 0) { return startDiff; } return o2.order - o1.order; } }; @Override public int getRangeStart() { return myCurrentStart; } @Override public int getRangeEnd() { return myCurrentEnd; } @Override public TextAttributes getTextAttributes() { TextAttributes ta = myIterators[0].iterator.getTextAttributes(); myMergedAttributes.setAttributes(ta.getForegroundColor(), ta.getBackgroundColor(), null, null, null, ta.getFontType()); for (int i = 1; i < overlappingRangesCount; i++) { merge(myIterators[i].iterator.getTextAttributes()); } return myMergedAttributes; } private void merge(TextAttributes attributes) { Color myBackground = myMergedAttributes.getBackgroundColor(); if (myBackground == null || myDefaultBackground.equals(myBackground)) { myMergedAttributes.setBackgroundColor(attributes.getBackgroundColor()); } Color myForeground = myMergedAttributes.getForegroundColor(); if (myForeground == null || myDefaultForeground.equals(myForeground)) { myMergedAttributes.setForegroundColor(attributes.getForegroundColor()); } if (myMergedAttributes.getFontType() == Font.PLAIN) { myMergedAttributes.setFontType(attributes.getFontType()); } } @Override public void dispose() { for (IteratorWrapper wrapper : myIterators) { if (wrapper != null) { wrapper.iterator.dispose(); } } } private static class IteratorWrapper { private final RangeIterator iterator; private final int order; private IteratorWrapper(RangeIterator iterator, int order) { this.iterator = iterator; this.order = order; } } } private static class MarkupModelRangeIterator implements RangeIterator { private final boolean myUnsupportedModel; private final int myStartOffset; private final int myEndOffset; private final EditorColorsScheme myColorsScheme; private final Color myDefaultForeground; private final Color myDefaultBackground; private final MarkupIterator<RangeHighlighterEx> myIterator; private int myCurrentStart; private int myCurrentEnd; private TextAttributes myCurrentAttributes; private int myNextStart; private int myNextEnd; private TextAttributes myNextAttributes; private MarkupModelRangeIterator(@Nullable MarkupModel markupModel, @NotNull EditorColorsScheme colorsScheme, int startOffset, int endOffset) { myStartOffset = startOffset; myEndOffset = endOffset; myColorsScheme = colorsScheme; myDefaultForeground = colorsScheme.getDefaultForeground(); myDefaultBackground = colorsScheme.getDefaultBackground(); myUnsupportedModel = !(markupModel instanceof MarkupModelEx); if (myUnsupportedModel) { myIterator = null; return; } myIterator = ((MarkupModelEx)markupModel).overlappingIterator(startOffset, endOffset); try { findNextSuitableRange(); } catch (RuntimeException | Error e) { myIterator.dispose(); throw e; } } @Override public boolean atEnd() { return myUnsupportedModel || myNextAttributes == null; } @Override public void advance() { myCurrentStart = myNextStart; myCurrentEnd = myNextEnd; myCurrentAttributes = myNextAttributes; findNextSuitableRange(); } private void findNextSuitableRange() { myNextAttributes = null; while (myIterator.hasNext()) { RangeHighlighterEx highlighter = myIterator.next(); if (highlighter == null || !highlighter.isValid() || !isInterestedInLayer(highlighter.getLayer())) { continue; } // LINES_IN_RANGE highlighters are not supported currently myNextStart = Math.max(highlighter.getStartOffset(), myStartOffset); myNextEnd = Math.min(highlighter.getEndOffset(), myEndOffset); if (myNextStart >= myEndOffset) { break; } if (myNextStart < myCurrentEnd) { continue; // overlapping ranges withing document markup model are not supported currently } TextAttributes attributes = null; HighlightInfo info = HighlightInfo.fromRangeHighlighter(highlighter); if (info != null) { TextAttributesKey key = info.forcedTextAttributesKey; if (key == null) { HighlightInfoType type = info.type; key = type.getAttributesKey(); } if (key != null) { attributes = myColorsScheme.getAttributes(key); } } if (attributes == null) { continue; } Color foreground = attributes.getForegroundColor(); Color background = attributes.getBackgroundColor(); if ((foreground == null || myDefaultForeground.equals(foreground)) && (background == null || myDefaultBackground.equals(background)) && attributes.getFontType() == Font.PLAIN) { continue; } myNextAttributes = attributes; break; } } private static boolean isInterestedInLayer(int layer) { return layer != HighlighterLayer.CARET_ROW && layer != HighlighterLayer.SELECTION && layer != HighlighterLayer.ERROR && layer != HighlighterLayer.WARNING && layer != HighlighterLayer.ELEMENT_UNDER_CARET; } @Override public int getRangeStart() { return myCurrentStart; } @Override public int getRangeEnd() { return myCurrentEnd; } @Override public TextAttributes getTextAttributes() { return myCurrentAttributes; } @Override public void dispose() { if (myIterator != null) { myIterator.dispose(); } } } static class HighlighterRangeIterator implements RangeIterator { private static final TextAttributes EMPTY_ATTRIBUTES = new TextAttributes(); private final HighlighterIterator myIterator; private final int myStartOffset; private final int myEndOffset; private int myCurrentStart; private int myCurrentEnd; private TextAttributes myCurrentAttributes; HighlighterRangeIterator(@NotNull EditorHighlighter highlighter, int startOffset, int endOffset) { myStartOffset = startOffset; myEndOffset = endOffset; myIterator = highlighter.createIterator(startOffset); } @Override public boolean atEnd() { return myIterator.atEnd() || getCurrentStart() >= myEndOffset; } private int getCurrentStart() { return Math.max(myIterator.getStart(), myStartOffset); } private int getCurrentEnd() { return Math.min(myIterator.getEnd(), myEndOffset); } @Override public void advance() { myCurrentStart = getCurrentStart(); myCurrentEnd = getCurrentEnd(); myCurrentAttributes = myIterator.getTokenType() == TokenType.BAD_CHARACTER ? EMPTY_ATTRIBUTES : myIterator.getTextAttributes(); myIterator.advance(); } @Override public int getRangeStart() { return myCurrentStart; } @Override public int getRangeEnd() { return myCurrentEnd; } @Override public TextAttributes getTextAttributes() { return myCurrentAttributes; } @Override public void dispose() { } } private static class SegmentIterator { private final FontFallbackIterator myIterator = new FontFallbackIterator(); private final CharSequence myCharSequence; private int myEndOffset; private boolean myAdvanceCalled; private SegmentIterator(CharSequence charSequence, FontPreferences fontPreferences) { myCharSequence = charSequence; myIterator.setPreferredFonts(fontPreferences); } public void reset(int startOffset, int endOffset, int fontStyle) { myIterator.setFontStyle(fontStyle); myIterator.start(myCharSequence, startOffset, endOffset); myEndOffset = endOffset; myAdvanceCalled = false; } public boolean atEnd() { return myIterator.atEnd() || myIterator.getEnd() == myEndOffset; } public void advance() { if (!myAdvanceCalled) { myAdvanceCalled = true; return; } myIterator.advance(); } public int getCurrentStartOffset() { return myIterator.getStart(); } public int getCurrentEndOffset() { return myIterator.getEnd(); } public String getCurrentFontFamilyName() { return myIterator.getFont().getFamily(); } } static class Context { private final SyntaxInfo.Builder builder; @NotNull private final CharSequence myText; @NotNull private final Color myDefaultForeground; @NotNull private final Color myDefaultBackground; @Nullable private Color myBackground; @Nullable private Color myForeground; @Nullable private String myFontFamilyName; private final int myIndentSymbolsToStrip; private int myFontStyle = -1; private int myStartOffset = -1; private int myOffsetShift = 0; private int myIndentSymbolsToStripAtCurrentLine; Context(@NotNull CharSequence charSequence, @NotNull EditorColorsScheme scheme, int indentSymbolsToStrip) { myText = charSequence; myDefaultForeground = scheme.getDefaultForeground(); myDefaultBackground = scheme.getDefaultBackground(); int javaFontSize = scheme.getEditorFontSize(); float fontSize = SystemInfo.isMac || ApplicationManager.getApplication().isHeadlessEnvironment() ? javaFontSize : javaFontSize * 0.75f / UISettings.getDefFontScale(); // matching font size in external apps builder = new SyntaxInfo.Builder(myDefaultForeground, myDefaultBackground, fontSize); myIndentSymbolsToStrip = indentSymbolsToStrip; } public void reset(int offsetShiftDelta) { myStartOffset = -1; myOffsetShift += offsetShiftDelta; myIndentSymbolsToStripAtCurrentLine = 0; } public void iterate(MyMarkupIterator iterator, int endOffset) { while (!iterator.atEnd()) { iterator.advance(); int startOffset = iterator.getStartOffset(); if (startOffset >= endOffset) { break; } if (myStartOffset < 0) { myStartOffset = startOffset; } boolean whiteSpacesOnly = CharArrayUtil.isEmptyOrSpaces(myText, startOffset, iterator.getEndOffset()); processBackground(startOffset, iterator.getBackgroundColor()); if (!whiteSpacesOnly) { processForeground(startOffset, iterator.getForegroundColor()); processFontFamilyName(startOffset, iterator.getFontFamilyName()); processFontStyle(startOffset, iterator.getFontStyle()); } } addTextIfPossible(endOffset); } private void processFontStyle(int startOffset, int fontStyle) { if (fontStyle != myFontStyle) { addTextIfPossible(startOffset); builder.addFontStyle(fontStyle); myFontStyle = fontStyle; } } private void processFontFamilyName(int startOffset, String fontName) { String fontFamilyName = FontMapper.getPhysicalFontName(fontName); if (!fontFamilyName.equals(myFontFamilyName)) { addTextIfPossible(startOffset); builder.addFontFamilyName(fontFamilyName); myFontFamilyName = fontFamilyName; } } private void processForeground(int startOffset, Color foreground) { if (myForeground == null && foreground != null) { addTextIfPossible(startOffset); myForeground = foreground; builder.addForeground(foreground); } else if (myForeground != null) { Color c = foreground == null ? myDefaultForeground : foreground; if (!myForeground.equals(c)) { addTextIfPossible(startOffset); builder.addForeground(c); myForeground = c; } } } private void processBackground(int startOffset, Color background) { if (myBackground == null && background != null && !myDefaultBackground.equals(background)) { addTextIfPossible(startOffset); myBackground = background; builder.addBackground(background); } else if (myBackground != null) { Color c = background == null ? myDefaultBackground : background; if (!myBackground.equals(c)) { addTextIfPossible(startOffset); builder.addBackground(c); myBackground = c; } } } private void addTextIfPossible(int endOffset) { if (endOffset <= myStartOffset) { return; } for (int i = myStartOffset; i < endOffset; i++) { char c = myText.charAt(i); switch (c) { case '\r': if (i + 1 < myText.length() && myText.charAt(i + 1) == '\n') { myIndentSymbolsToStripAtCurrentLine = myIndentSymbolsToStrip; builder.addText(myStartOffset + myOffsetShift, i + myOffsetShift + 1); myStartOffset = i + 2; myOffsetShift--; //noinspection AssignmentToForLoopParameter i++; break; } // Intended fall-through. case '\n': myIndentSymbolsToStripAtCurrentLine = myIndentSymbolsToStrip; builder.addText(myStartOffset + myOffsetShift, i + myOffsetShift + 1); myStartOffset = i + 1; break; // Intended fall-through. case ' ': case '\t': if (myIndentSymbolsToStripAtCurrentLine > 0) { myIndentSymbolsToStripAtCurrentLine--; myStartOffset++; continue; } default: myIndentSymbolsToStripAtCurrentLine = 0; } } if (myStartOffset < endOffset) { builder.addText(myStartOffset + myOffsetShift, endOffset + myOffsetShift); myStartOffset = endOffset; } } void addCharacter(int position) { builder.addText(position + myOffsetShift, position + myOffsetShift + 1); } @NotNull public SyntaxInfo finish() { return builder.build(); } } }
EA-142496 - assert: TextWithMarkupProcessor.collectTransferableData GitOrigin-RevId: 4880837fcfae8ba18f506fc3aa99e4904a20a7d1
platform/lang-impl/src/com/intellij/openapi/editor/richcopy/SyntaxInfoBuilder.java
EA-142496 - assert: TextWithMarkupProcessor.collectTransferableData
<ide><path>latform/lang-impl/src/com/intellij/openapi/editor/richcopy/SyntaxInfoBuilder.java <ide> static MyMarkupIterator createMarkupIterator(@NotNull EditorHighlighter highlighter, <ide> @NotNull CharSequence text, <ide> @NotNull EditorColorsScheme schemeToUse, <del> @NotNull MarkupModel markupModel, <add> @Nullable MarkupModel markupModel, <ide> int startOffsetToUse, <ide> int endOffset) { <ide>
Java
apache-2.0
d45417cffa63e05c11ad959449e6c4e320a72c79
0
pveentjer/hazelcast-simulator,Danny-Hazelcast/hazelcast-stabilizer,hazelcast/hazelcast-simulator,jerrinot/hazelcast-stabilizer,Donnerbart/hazelcast-simulator,pveentjer/hazelcast-simulator,hasancelik/hazelcast-stabilizer,hasancelik/hazelcast-stabilizer,jerrinot/hazelcast-stabilizer,Danny-Hazelcast/hazelcast-stabilizer,hazelcast/hazelcast-simulator,Donnerbart/hazelcast-simulator,hazelcast/hazelcast-simulator
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.simulator.coordinator; import com.hazelcast.simulator.protocol.core.SimulatorAddress; import com.hazelcast.simulator.protocol.operation.FailureOperation; import com.hazelcast.simulator.protocol.registry.ComponentRegistry; import com.hazelcast.simulator.test.FailureType; import com.hazelcast.simulator.test.TestSuite; import com.hazelcast.simulator.utils.CommandLineExitException; import org.apache.log4j.Logger; import java.io.File; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.hazelcast.simulator.utils.CommonUtils.getElapsedSeconds; import static com.hazelcast.simulator.utils.CommonUtils.sleepMillis; import static com.hazelcast.simulator.utils.FileUtils.appendText; import static com.hazelcast.simulator.utils.FormatUtils.HORIZONTAL_RULER; import static java.lang.String.format; /** * Responsible for storing and formatting failures from Simulator workers. */ public class FailureContainer { static final int FINISHED_WORKER_TIMEOUT_SECONDS = 120; static final int FINISHED_WORKERS_SLEEP_MILLIS = 500; private static final Logger LOGGER = Logger.getLogger(FailureContainer.class); private final AtomicInteger failureCount = new AtomicInteger(); private final ConcurrentMap<SimulatorAddress, FailureType> finishedWorkers = new ConcurrentHashMap<SimulatorAddress, FailureType>(); private final ConcurrentHashMap<FailureListener, Boolean> listenerMap = new ConcurrentHashMap<FailureListener, Boolean>(); private final AtomicBoolean hasCriticalFailure = new AtomicBoolean(); private final ConcurrentMap<String, Boolean> hasCriticalFailuresMap = new ConcurrentHashMap<String, Boolean>(); private final File file; private final ComponentRegistry componentRegistry; private final Set<FailureType> nonCriticalFailures; public FailureContainer(TestSuite testSuite, ComponentRegistry componentRegistry) { this(testSuite.getId(), componentRegistry, testSuite.getTolerableFailures()); } public FailureContainer(String testSuiteId, ComponentRegistry componentRegistry) { this(testSuiteId, componentRegistry, Collections.<FailureType>emptySet()); } public FailureContainer(String testSuiteId, ComponentRegistry componentRegistry, Set<FailureType> nonCriticalFailures) { this.file = new File("failures-" + testSuiteId + ".txt"); this.componentRegistry = componentRegistry; this.nonCriticalFailures = nonCriticalFailures; } public void addListener(FailureListener listener) { listenerMap.put(listener, true); } public void addFailureOperation(FailureOperation operation) { FailureType failureType = operation.getType(); if (failureType.isWorkerFinishedFailure()) { SimulatorAddress workerAddress = operation.getWorkerAddress(); finishedWorkers.put(workerAddress, failureType); componentRegistry.removeWorker(workerAddress); } if (failureType.isPoisonPill()) { return; } int failureNumber = failureCount.incrementAndGet(); if (!nonCriticalFailures.contains(failureType)) { hasCriticalFailure.set(true); String testId = operation.getTestId(); if (testId != null) { hasCriticalFailuresMap.put(testId, true); } } LOGGER.error(operation.getLogMessage(failureNumber)); appendText(operation.getFileMessage(), file); for (FailureListener failureListener : listenerMap.keySet()) { failureListener.onFailure(operation); } } int getFailureCount() { return failureCount.get(); } boolean hasCriticalFailure() { return hasCriticalFailure.get(); } boolean hasCriticalFailure(String testId) { return hasCriticalFailuresMap.containsKey(testId); } Set<SimulatorAddress> getFinishedWorkers() { return finishedWorkers.keySet(); } boolean waitForWorkerShutdown(int expectedWorkerCount, int timeoutSeconds) { long started = System.nanoTime(); LOGGER.info(format("Waiting up to %d seconds for shutdown of %d Workers...", timeoutSeconds, expectedWorkerCount)); long timeoutTimestamp = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds); while (finishedWorkers.size() < expectedWorkerCount && System.currentTimeMillis() < timeoutTimestamp) { sleepMillis(FINISHED_WORKERS_SLEEP_MILLIS); } int remainingWorkers = expectedWorkerCount - finishedWorkers.size(); if (remainingWorkers > 0) { LOGGER.warn(format("Aborted waiting for shutdown of all Workers (%d still running)...", remainingWorkers)); return false; } LOGGER.info(format("Finished shutdown of all Workers (%d seconds)", getElapsedSeconds(started))); return true; } void logFailureInfo() { int tmpFailureCount = failureCount.get(); if (tmpFailureCount > 0) { if (hasCriticalFailure.get()) { LOGGER.fatal(HORIZONTAL_RULER); LOGGER.fatal(tmpFailureCount + " failures have been detected!!!"); LOGGER.fatal(HORIZONTAL_RULER); throw new CommandLineExitException(tmpFailureCount + " failures have been detected"); } else { LOGGER.fatal(HORIZONTAL_RULER); LOGGER.fatal(tmpFailureCount + " non-critical failures have been detected!"); LOGGER.fatal(HORIZONTAL_RULER); } return; } LOGGER.info(HORIZONTAL_RULER); LOGGER.info("No failures have been detected!"); LOGGER.info(HORIZONTAL_RULER); } }
simulator/src/main/java/com/hazelcast/simulator/coordinator/FailureContainer.java
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.simulator.coordinator; import com.hazelcast.simulator.protocol.core.SimulatorAddress; import com.hazelcast.simulator.protocol.operation.FailureOperation; import com.hazelcast.simulator.protocol.registry.ComponentRegistry; import com.hazelcast.simulator.test.FailureType; import com.hazelcast.simulator.test.TestSuite; import com.hazelcast.simulator.utils.CommandLineExitException; import org.apache.log4j.Logger; import java.io.File; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.hazelcast.simulator.utils.CommonUtils.getElapsedSeconds; import static com.hazelcast.simulator.utils.CommonUtils.sleepMillis; import static com.hazelcast.simulator.utils.FileUtils.appendText; import static com.hazelcast.simulator.utils.FormatUtils.HORIZONTAL_RULER; import static java.lang.String.format; /** * Responsible for storing and formatting failures from Simulator workers. */ public class FailureContainer { static final int FINISHED_WORKER_TIMEOUT_SECONDS = 120; static final int FINISHED_WORKERS_SLEEP_MILLIS = 500; private static final Logger LOGGER = Logger.getLogger(FailureContainer.class); private final AtomicInteger failureCount = new AtomicInteger(); private final ConcurrentMap<SimulatorAddress, FailureType> finishedWorkers = new ConcurrentHashMap<SimulatorAddress, FailureType>(); private final ConcurrentHashMap<FailureListener, Boolean> listenerMap = new ConcurrentHashMap<FailureListener, Boolean>(); private final AtomicBoolean hasCriticalFailure = new AtomicBoolean(); private final ConcurrentMap<String, Boolean> hasCriticalFailuresMap = new ConcurrentHashMap<String, Boolean>(); private final File file; private final ComponentRegistry componentRegistry; private final Set<FailureType> nonCriticalFailures; public FailureContainer(TestSuite testSuite, ComponentRegistry componentRegistry) { this(testSuite.getId(), componentRegistry, testSuite.getTolerableFailures()); } public FailureContainer(String testSuiteId, ComponentRegistry componentRegistry) { this(testSuiteId, componentRegistry, Collections.<FailureType>emptySet()); } public FailureContainer(String testSuiteId, ComponentRegistry componentRegistry, Set<FailureType> nonCriticalFailures) { this.file = new File("failures-" + testSuiteId + ".txt"); this.componentRegistry = componentRegistry; this.nonCriticalFailures = nonCriticalFailures; } public void addListener(FailureListener listener) { listenerMap.put(listener, true); } public void addFailureOperation(FailureOperation operation) { FailureType failureType = operation.getType(); if (failureType.isWorkerFinishedFailure()) { SimulatorAddress workerAddress = operation.getWorkerAddress(); finishedWorkers.put(workerAddress, failureType); componentRegistry.removeWorker(workerAddress); } if (failureType.isPoisonPill()) { return; } int failureNumber = failureCount.incrementAndGet(); if (!nonCriticalFailures.contains(failureType)) { hasCriticalFailure.set(true); String testId = operation.getTestId(); if (testId != null) { hasCriticalFailuresMap.put(testId, true); } } LOGGER.error(operation.getLogMessage(failureNumber)); appendText(operation.getFileMessage(), file); for (FailureListener failureListener : listenerMap.keySet()) { failureListener.onFailure(operation); } } int getFailureCount() { return failureCount.get(); } boolean hasCriticalFailure() { return hasCriticalFailure.get(); } boolean hasCriticalFailure(String testId) { return hasCriticalFailuresMap.containsKey(testId); } Set<SimulatorAddress> getFinishedWorkers() { return finishedWorkers.keySet(); } boolean waitForWorkerShutdown(int expectedFinishedWorkerCount, int timeoutSeconds) { long started = System.nanoTime(); LOGGER.info(format("Waiting %d seconds for shutdown of %d Workers...", timeoutSeconds, expectedFinishedWorkerCount)); long timeoutTimestamp = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds); while (finishedWorkers.size() < expectedFinishedWorkerCount && System.currentTimeMillis() < timeoutTimestamp) { sleepMillis(FINISHED_WORKERS_SLEEP_MILLIS); } int remainingWorkers = expectedFinishedWorkerCount - finishedWorkers.size(); if (remainingWorkers > 0) { LOGGER.warn(format("Aborted waiting for shutdown of all Workers (%d still running)...", remainingWorkers)); return false; } LOGGER.info(format("Finished shutdown of all Workers (%d seconds)", getElapsedSeconds(started))); return true; } void logFailureInfo() { int tmpFailureCount = failureCount.get(); if (tmpFailureCount > 0) { if (hasCriticalFailure.get()) { LOGGER.fatal(HORIZONTAL_RULER); LOGGER.fatal(tmpFailureCount + " failures have been detected!!!"); LOGGER.fatal(HORIZONTAL_RULER); throw new CommandLineExitException(tmpFailureCount + " failures have been detected"); } else { LOGGER.fatal(HORIZONTAL_RULER); LOGGER.fatal(tmpFailureCount + " non-critical failures have been detected!"); LOGGER.fatal(HORIZONTAL_RULER); } return; } LOGGER.info(HORIZONTAL_RULER); LOGGER.info("No failures have been detected!"); LOGGER.info(HORIZONTAL_RULER); } }
Enhanced worker shutdown log message.
simulator/src/main/java/com/hazelcast/simulator/coordinator/FailureContainer.java
Enhanced worker shutdown log message.
<ide><path>imulator/src/main/java/com/hazelcast/simulator/coordinator/FailureContainer.java <ide> return finishedWorkers.keySet(); <ide> } <ide> <del> boolean waitForWorkerShutdown(int expectedFinishedWorkerCount, int timeoutSeconds) { <add> boolean waitForWorkerShutdown(int expectedWorkerCount, int timeoutSeconds) { <ide> long started = System.nanoTime(); <del> LOGGER.info(format("Waiting %d seconds for shutdown of %d Workers...", timeoutSeconds, expectedFinishedWorkerCount)); <add> LOGGER.info(format("Waiting up to %d seconds for shutdown of %d Workers...", timeoutSeconds, expectedWorkerCount)); <ide> long timeoutTimestamp = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds); <del> while (finishedWorkers.size() < expectedFinishedWorkerCount && System.currentTimeMillis() < timeoutTimestamp) { <add> while (finishedWorkers.size() < expectedWorkerCount && System.currentTimeMillis() < timeoutTimestamp) { <ide> sleepMillis(FINISHED_WORKERS_SLEEP_MILLIS); <ide> } <del> int remainingWorkers = expectedFinishedWorkerCount - finishedWorkers.size(); <add> int remainingWorkers = expectedWorkerCount - finishedWorkers.size(); <ide> if (remainingWorkers > 0) { <ide> LOGGER.warn(format("Aborted waiting for shutdown of all Workers (%d still running)...", remainingWorkers)); <ide> return false;
Java
apache-2.0
35ee0e6c0b77719d552a22425158c1a02e206d5b
0
andreaturli/legacy-brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,neykov/incubator-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,aledsage/legacy-brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,andreaturli/legacy-brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,neykov/incubator-brooklyn,bmwshop/brooklyn
package brooklyn.location.basic; import static brooklyn.util.GroovyJavaMethods.truth; import groovy.lang.Closure; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.Reader; import java.net.InetAddress; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.jclouds.util.Throwables2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.config.BrooklynLogging; import brooklyn.location.Location; import brooklyn.location.MachineLocation; import brooklyn.location.OsDetails; import brooklyn.location.PortRange; import brooklyn.location.PortSupplier; import brooklyn.location.basic.PortRanges.BasicPortRange; import brooklyn.location.geo.HasHostGeoInfo; import brooklyn.location.geo.HostGeoInfo; import brooklyn.util.MutableMap; import brooklyn.util.ReaderInputStream; import brooklyn.util.ResourceUtils; import brooklyn.util.flags.SetFromFlag; import brooklyn.util.flags.TypeCoercions; import brooklyn.util.internal.SshTool; import brooklyn.util.internal.StreamGobbler; import brooklyn.util.internal.ssh.SshException; import brooklyn.util.internal.ssh.SshjTool; import brooklyn.util.mutex.MutexSupport; import brooklyn.util.mutex.WithMutexes; import brooklyn.util.pool.BasicPool; import brooklyn.util.pool.Pool; import brooklyn.util.task.Tasks; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Closeables; /** * Operations on a machine that is accessible via ssh. * <p> * We expose two ways of running scripts. * One (execCommands) passes lines to bash, that is lightweight but fragile. * Another (execScript) creates a script on the remote machine, more portable but heavier. * <p> * Additionally there are routines to copyTo, copyFrom; and installTo (which tries a curl, and falls back to copyTo * in event the source is accessible by the caller only). */ public class SshMachineLocation extends AbstractLocation implements MachineLocation, PortSupplier, WithMutexes, Closeable { public static final Logger LOG = LoggerFactory.getLogger(SshMachineLocation.class); public static final Logger logSsh = LoggerFactory.getLogger(BrooklynLogging.SSH_IO); protected interface ExecRunner { public int exec(SshTool ssh, Map<String,?> flags, List<String> cmds, Map<String,?> env); } @SetFromFlag("user") String user; @SetFromFlag("privateKeyData") String privateKeyData; @SetFromFlag(nullable = false) InetAddress address; @SetFromFlag Map config; @SetFromFlag transient WithMutexes mutexSupport; @SetFromFlag private Set<Integer> usedPorts; /** any property that should be passed as ssh config (connection-time) * can be prefixed with this and . and will be passed through (with the prefix removed), * e.g. (SSHCONFIG_PREFIX+"."+"StrictHostKeyChecking"):"yes" */ public static final String SSHCONFIG_PREFIX = "sshconfig"; /** properties which are passed to ssh */ public static final Collection<String> SSH_PROPS = ImmutableSet.of( "noStdoutLogging", "noStderrLogging", "logPrefix", "out", "err", "password", "permissions", "sshTries", "env", "allocatePTY", "privateKeyPassphrase", "privateKeyFile", "privateKeyData", // deprecated in 0.4.0 -- prefer privateKeyData/privateKeyFile // (confusion about whether other holds a file or data; and public not useful here) // they generate a warning where used "keyFiles", "publicKey", "privateKey"); //TODO remove once everything is prefixed SSHCONFIG_PREFIX or included above public static final Collection<String> NON_SSH_PROPS = ImmutableSet.of("latitude", "longitude", "backup", "sshPublicKeyData", "sshPrivateKeyData"); private transient Pool<SshTool> vanillaSshToolPool; public SshMachineLocation() { this(MutableMap.of()); } public SshMachineLocation(Map properties) { super(properties); usedPorts = (usedPorts != null) ? Sets.newLinkedHashSet(usedPorts) : Sets.<Integer>newLinkedHashSet(); vanillaSshToolPool = buildVanillaPool(); } private BasicPool<SshTool> buildVanillaPool() { return BasicPool.<SshTool>builder() .name(name+":"+address+":"+System.identityHashCode(this)) .supplier(new Supplier<SshTool>() { @Override public SshTool get() { return connectSsh(Collections.emptyMap()); }}) .viabilityChecker(new Predicate<SshTool>() { @Override public boolean apply(SshTool input) { return input != null && input.isConnected(); }}) .closer(new Function<SshTool,Void>() { @Override public Void apply(SshTool input) { try { input.disconnect(); } catch (Exception e) { if (logSsh.isDebugEnabled()) logSsh.debug("On machine "+SshMachineLocation.this+", ssh-disconnect failed", e); } return null; }}) .build(); } public void configure() { configure(MutableMap.of()); } public void configure(Map properties) { if (config==null) config = Maps.newLinkedHashMap(); super.configure(properties); // TODO Note that check for addresss!=null is done automatically in super-constructor, in FlagUtils.checkRequiredFields // Yikes, dangerous code for accessing fields of sub-class in super-class' constructor! But getting away with it so far! if (mutexSupport == null) { mutexSupport = new MutexSupport(); } boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class)); if (!deferConstructionChecks) { if (properties.containsKey("username")) { LOG.warn("Using deprecated ssh machine property 'username': use 'user' instead", new Throwable("source of deprecated ssh 'username' invocation")); user = ""+properties.get("username"); } if (name == null) { name = (truth(user) ? user+"@" : "") + address.getHostName(); } if (getHostGeoInfo() == null) { Location parentLocation = getParentLocation(); if ((parentLocation instanceof HasHostGeoInfo) && ((HasHostGeoInfo)parentLocation).getHostGeoInfo()!=null) setHostGeoInfo( ((HasHostGeoInfo)parentLocation).getHostGeoInfo() ); else setHostGeoInfo(HostGeoInfo.fromLocation(this)); } } } @Override public void close() { vanillaSshToolPool.closePool(); } @Override protected void finalize() throws Throwable { close(); } public InetAddress getAddress() { return address; } public String getUser() { return user; } public Map getConfig() { return config; } public int run(String command) { return run(MutableMap.of(), command, MutableMap.of()); } public int run(Map props, String command) { return run(props, command, MutableMap.of()); } public int run(String command, Map env) { return run(MutableMap.of(), command, env); } public int run(Map props, String command, Map env) { return run(props, ImmutableList.of(command), env); } /** * @deprecated in 1.4.1, @see execCommand and execScript */ public int run(List<String> commands) { return run(MutableMap.of(), commands, MutableMap.of()); } public int run(Map props, List<String> commands) { return run(props, commands, MutableMap.of()); } public int run(List<String> commands, Map env) { return run(MutableMap.of(), commands, env); } public int run(final Map props, final List<String> commands, final Map env) { if (commands == null || commands.isEmpty()) return 0; return execSsh(props, new Function<SshTool, Integer>() { public Integer apply(SshTool ssh) { return ssh.execScript(props, commands, env); }}); } protected <T> T execSsh(Map props, Function<SshTool,T> task) { if (props.isEmpty()) { return vanillaSshToolPool.exec(task); } else { SshTool ssh = connectSsh(props); try { return task.apply(ssh); } finally { ssh.disconnect(); } } } protected SshTool connectSsh() { return connectSsh(ImmutableMap.of()); } protected boolean previouslyConnected = false; protected SshTool connectSsh(Map props) { try { if (!truth(user)) user = System.getProperty("user.name"); Map<?,?> allprops = MutableMap.builder().putAll(config).putAll(leftoverProperties).putAll(props).build(); Map<String,Object> args = MutableMap.<String,Object>of("user", user, "host", address.getHostName()); for (Map.Entry<?, ?> entry : allprops.entrySet()) { String k = ""+entry.getKey(); Object v = entry.getValue(); if (SSH_PROPS.contains(k)) { args.put(k, v); } else if (k.startsWith(SSHCONFIG_PREFIX+".")) { args.put(k.substring(SSHCONFIG_PREFIX.length()+1), v); } else { // TODO remove once everything is included above and we no longer see these warnings if (!NON_SSH_PROPS.contains(k)) { LOG.warn("including legacy SSH config property "+k+" for "+this+"; either prefix with sshconfig or add to NON_SSH_PROPS"); args.put(k, v); } } } if (LOG.isTraceEnabled()) LOG.trace("creating ssh session for "+args); SshTool ssh = new SshjTool(args); Tasks.setBlockingDetails("Opening ssh connection"); try { ssh.connect(); } finally { Tasks.setBlockingDetails(null); } previouslyConnected = true; return ssh; } catch (Exception e) { if (previouslyConnected) throw Throwables.propagate(e); // subsequence connection (above) most likely network failure, our remarks below won't help // on first connection include additional information if we can't connect, to help with debugging String rootCause = Throwables.getRootCause(e).getMessage(); throw new IllegalStateException("Cannot establish ssh connection to "+user+" @ "+this+ (rootCause!=null && !rootCause.isEmpty() ? " ("+rootCause+")" : "")+". \n"+ "Ensure that passwordless and passphraseless ssh access is enabled using standard keys from ~/.ssh or " + "as configured in brooklyn.properties. " + "Check that the target host is accessible, that correct permissions are set on your keys, " + "and that there is sufficient random noise in /dev/random on both ends. " + "To debug less common causes, see the original error in the trace or log, and/or enable 'net.schmizz' (sshj) logging." , e); } } /** * Convenience for running commands using ssh {@literal exec} mode. * @deprecated in 1.4.1, @see execCommand and execScript */ public int exec(List<String> commands) { return exec(MutableMap.of(), commands, MutableMap.of()); } public int exec(Map props, List<String> commands) { return exec(props, commands, MutableMap.of()); } public int exec(List<String> commands, Map env) { return exec(MutableMap.of(), commands, env); } public int exec(final Map props, final List<String> commands, final Map env) { Preconditions.checkNotNull(address, "host address must be specified for ssh"); if (commands == null || commands.isEmpty()) return 0; return execSsh(props, new Function<SshTool, Integer>() { public Integer apply(SshTool ssh) { return ssh.execCommands(props, commands, env); }}); } // TODO submitCommands and submitScript which submit objects we can subsequently poll (cf JcloudsSshMachineLocation.submitRunScript) /** executes a set of commands, directly on the target machine (no wrapping in script). * joined using ' ; ' by default. * <p> * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use * the flag 'logPrefix'. * <p> * Currently runs the commands in an interactive/login shell * by passing each as a line to bash. To terminate early, use: * <pre> * foo || exit 1 * </pre> * It may be desirable instead, in some situations, to wrap as: * <pre> * { line1 ; } && { line2 ; } ... * </pre> * and run as a single command (possibly not as an interacitve/login * shell) causing the script to exit on the first command which fails. * <p> * Currently this has to be done by the caller. * (If desired we can add a flag {@code exitIfAnyNonZero} to support this mode, * and/or {@code commandPrepend} and {@code commandAppend} similar to * (currently supported in SshjTool) {@code separator}.) */ public int execCommands(String summaryForLogging, List<String> commands) { return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands) { return execCommands(props, summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execCommands(String summaryForLogging, List<String> commands, Map<String,?> env) { return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, env); } public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) { return execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() { @Override public int exec(SshTool ssh, Map<String,?> flags, List<String> cmds, Map<String,?> env) { return ssh.execCommands(flags, cmds, env); }}); } /** executes a set of commands, wrapped as a script sent to the remote machine. * <p> * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use * the flag 'logPrefix'. */ public int execScript(String summaryForLogging, List<String> commands) { return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands) { return execScript(props, summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execScript(String summaryForLogging, List<String> commands, Map<String,?> env) { return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, env); } public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) { return execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() { @Override public int exec(SshTool ssh, Map<String, ?> flags, List<String> cmds, Map<String, ?> env) { return ssh.execScript(flags, cmds, env); }}); } protected int execWithLogging(Map<String,?> props, String summaryForLogging, List<String> commands, Map env, final Closure<Integer> execCommand) { return execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() { @Override public int exec(SshTool ssh, Map<String, ?> flags, List<String> cmds, Map<String, ?> env) { return execCommand.call(ssh, flags, cmds, env); }}); } protected int execWithLogging(Map<String,?> props, final String summaryForLogging, final List<String> commands, final Map<String,?> env, final ExecRunner execCommand) { if (logSsh.isDebugEnabled()) logSsh.debug("{} on machine {}: {}", new Object[] {summaryForLogging, this, commands}); Preconditions.checkNotNull(address, "host address must be specified for ssh"); if (commands.isEmpty()) { logSsh.debug("{} on machine {} ending: no commands to run", summaryForLogging, this); return 0; } final Map<String,Object> execFlags = MutableMap.copyOf(props); final Map<String,Object> sshFlags = MutableMap.<String,Object>builder().putAll(props).removeAll("logPrefix", "out", "err").build(); PipedOutputStream outO = null; PipedOutputStream outE = null; StreamGobbler gO=null, gE=null; try { String logPrefix; if (execFlags.get("logPrefix") != null) { logPrefix = ""+execFlags.get("logPrefix"); } else { String hostname = getAddress().getHostName(); Object port = config.get("sshconfig.port"); if (port == null) port = leftoverProperties.get("sshconfig.port"); logPrefix = (user != null ? user+"@" : "") + hostname + (port != null ? ":"+port : ""); } if (!truth(execFlags.get("noStdoutLogging"))) { PipedInputStream insO = new PipedInputStream(); outO = new PipedOutputStream(insO); String stdoutLogPrefix = "["+(logPrefix != null ? logPrefix+":stdout" : "stdout")+"] "; gO = new StreamGobbler(insO, (OutputStream) execFlags.get("out"), logSsh).setLogPrefix(stdoutLogPrefix); gO.start(); execFlags.put("out", outO); } if (!truth(execFlags.get("noStdoutLogging"))) { PipedInputStream insE = new PipedInputStream(); outE = new PipedOutputStream(insE); String stderrLogPrefix = "["+(logPrefix != null ? logPrefix+":stderr" : "stderr")+"] "; gE = new StreamGobbler(insE, (OutputStream) execFlags.get("err"), logSsh).setLogPrefix(stderrLogPrefix); gE.start(); execFlags.put("err", outE); } Tasks.setBlockingDetails("SSH executing, "+summaryForLogging); try { return execSsh(sshFlags, new Function<SshTool, Integer>() { public Integer apply(SshTool ssh) { int result = execCommand.exec(ssh, execFlags, commands, env); if (logSsh.isDebugEnabled()) logSsh.debug("{} on machine {} completed: return status {}", new Object[] {summaryForLogging, this, result}); return result; }}); } finally { Tasks.setBlockingDetails(null); } } catch (IOException e) { if (logSsh.isDebugEnabled()) logSsh.debug("{} on machine {} failed: {}", new Object[] {summaryForLogging, this, e}); throw Throwables.propagate(e); } finally { // Must close the pipedOutStreams, otherwise input will never read -1 so StreamGobbler thread would never die if (outO!=null) try { outO.flush(); } catch (IOException e) {} if (outE!=null) try { outE.flush(); } catch (IOException e) {} Closeables.closeQuietly(outO); Closeables.closeQuietly(outE); try { if (gE!=null) { gE.join(); } if (gO!=null) { gO.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); Throwables.propagate(e); } } } public int copyTo(File src, File destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, File src, File destination) { return copyTo(props, src, destination.getPath()); } // FIXME the return code is not a reliable indicator of success or failure public int copyTo(File src, String destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, File src, String destination) { Preconditions.checkNotNull(address, "Host address must be specified for scp"); Preconditions.checkArgument(src.exists(), "File %s must exist for scp", src.getPath()); try { return copyTo(props, new FileInputStream(src), src.length(), destination); } catch (FileNotFoundException e) { throw Throwables.propagate(e); } } public int copyTo(Reader src, String destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, Reader src, String destination) { return copyTo(props, new ReaderInputStream(src), destination); } public int copyTo(InputStream src, String destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, InputStream src, String destination) { return copyTo(props, src, -1, destination); } public int copyTo(InputStream src, long filesize, String destination) { return copyTo(MutableMap.<String,Object>of(), src, filesize, destination); } public int copyTo(final Map<String,?> props, InputStream src, long filesize, final String destination) { final long finalFilesize; final InputStream finalSrc; if (filesize==-1) { try { File tempFile = ResourceUtils.writeToTempFile(src, "sshcopy", "data"); finalFilesize = tempFile.length(); finalSrc = new FileInputStream(tempFile); } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(src); } } else { finalFilesize = filesize; finalSrc = src; } return execSsh(props, new Function<SshTool,Integer>() { public Integer apply(SshTool ssh) { return ssh.createFile(props, destination, finalSrc, finalFilesize); }}); } // FIXME the return code is not a reliable indicator of success or failure public int copyFrom(String remote, String local) { return copyFrom(MutableMap.<String,Object>of(), remote, local); } public int copyFrom(final Map<String,?> props, final String remote, final String local) { return execSsh(props, new Function<SshTool,Integer>() { public Integer apply(SshTool ssh) { return ssh.transferFileFrom(props, remote, local); }}); } /** installs the given URL at the indicated destination. * attempts to curl the sourceUrl on the remote machine, * then if that fails, loads locally (from classpath or file) and transfers. * <p> * accepts either a path (terminated with /) or filename for the destination. **/ public int installTo(ResourceUtils loader, String url, String destination) { if (destination.endsWith("/")) { String destName = url; destName = destName.contains("?") ? destName.substring(0, destName.indexOf("?")) : destName; destName = destName.substring(destName.lastIndexOf('/')+1); destination = destination + destName; } LOG.debug("installing {} to {} on {}, attempting remote curl", new Object[] {url, destination, this}); try { PipedInputStream insO = new PipedInputStream(); OutputStream outO = new PipedOutputStream(insO); PipedInputStream insE = new PipedInputStream(); OutputStream outE = new PipedOutputStream(insE); new StreamGobbler(insO, null, LOG).setLogPrefix("[curl @ "+address+":stdout] ").start(); new StreamGobbler(insE, null, LOG).setLogPrefix("[curl @ "+address+":stdout] ").start(); int result = exec(MutableMap.of("out", outO, "err", outE), ImmutableList.of("curl "+url+" -L --silent --insecure --show-error --fail --connect-timeout 60 --max-time 600 --retry 5 -o "+destination)); if (result!=0 && loader!=null) { LOG.debug("installing {} to {} on {}, curl failed, attempting local fetch and copy", new Object[] {url, destination, this}); result = copyTo(loader.getResourceFromUrl(url), destination); } if (result==0) LOG.debug("installing {} complete; {} on {}", new Object[] {url, destination, this}); else LOG.warn("installing {} failed; {} on {}: {}", new Object[] {url, destination, this, result}); return result; } catch (IOException e) { throw Throwables.propagate(e); } } @Override public String toString() { return "SshMachineLocation["+name+":"+address+"]"; } /** * @see #obtainPort(PortRange) * @see BasicPortRange#ANY_HIGH_PORT */ public boolean obtainSpecificPort(int portNumber) { // TODO Does not yet check if the port really is free on this machine if (usedPorts.contains(portNumber)) { return false; } else { usedPorts.add(portNumber); return true; } } public int obtainPort(PortRange range) { for (int p: range) if (obtainSpecificPort(p)) return p; if (LOG.isDebugEnabled()) LOG.debug("unable to find port in {} on {}; returning -1", range, this); return -1; } public void releasePort(int portNumber) { usedPorts.remove((Object) portNumber); } public boolean isSshable() { String cmd = "date"; try { int result = run(cmd); if (result == 0) { return true; } else { if (LOG.isDebugEnabled()) LOG.debug("Not reachable: {}, executing `{}`, exit code {}", new Object[] {this, cmd, result}); return false; } } catch (SshException e) { if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e); return false; } catch (IllegalStateException e) { if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e); return false; } catch (RuntimeException e) { if (Throwables2.getFirstThrowableOfType(e, IOException.class) != null) { if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e); return false; } else { throw e; } } } @Override public OsDetails getOsDetails() { // TODO ssh and find out what we need to know, or use jclouds... return BasicOsDetails.Factory.ANONYMOUS_LINUX; } protected WithMutexes newMutexSupport() { return new MutexSupport(); } @Override public void acquireMutex(String mutexId, String description) throws InterruptedException { mutexSupport.acquireMutex(mutexId, description); } @Override public boolean tryAcquireMutex(String mutexId, String description) { return mutexSupport.tryAcquireMutex(mutexId, description); } @Override public void releaseMutex(String mutexId) { mutexSupport.releaseMutex(mutexId); } @Override public boolean hasMutex(String mutexId) { return mutexSupport.hasMutex(mutexId); } //We want want the SshMachineLocation to be serializable and therefor the pool needs to be dealt with correctly. //In this case we are not serializing the pool (we made the field transient) and create a new pool when deserialized. //This fix is currently needed for experiments, but isn't used in normal Brooklyn usage. private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); vanillaSshToolPool = buildVanillaPool(); } }
core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
package brooklyn.location.basic; import static brooklyn.util.GroovyJavaMethods.truth; import groovy.lang.Closure; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.Reader; import java.net.InetAddress; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.jclouds.util.Throwables2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.config.BrooklynLogging; import brooklyn.location.Location; import brooklyn.location.MachineLocation; import brooklyn.location.OsDetails; import brooklyn.location.PortRange; import brooklyn.location.PortSupplier; import brooklyn.location.basic.PortRanges.BasicPortRange; import brooklyn.location.geo.HasHostGeoInfo; import brooklyn.location.geo.HostGeoInfo; import brooklyn.util.MutableMap; import brooklyn.util.ReaderInputStream; import brooklyn.util.ResourceUtils; import brooklyn.util.flags.SetFromFlag; import brooklyn.util.flags.TypeCoercions; import brooklyn.util.internal.SshTool; import brooklyn.util.internal.StreamGobbler; import brooklyn.util.internal.ssh.SshException; import brooklyn.util.internal.ssh.SshjTool; import brooklyn.util.mutex.MutexSupport; import brooklyn.util.mutex.WithMutexes; import brooklyn.util.pool.BasicPool; import brooklyn.util.pool.Pool; import brooklyn.util.task.Tasks; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Closeables; /** * Operations on a machine that is accessible via ssh. * <p> * We expose two ways of running scripts. * One (execCommands) passes lines to bash, that is lightweight but fragile. * Another (execScript) creates a script on the remote machine, more portable but heavier. * <p> * Additionally there are routines to copyTo, copyFrom; and installTo (which tries a curl, and falls back to copyTo * in event the source is accessible by the caller only). */ public class SshMachineLocation extends AbstractLocation implements MachineLocation, PortSupplier, WithMutexes, Closeable { public static final Logger LOG = LoggerFactory.getLogger(SshMachineLocation.class); public static final Logger logSsh = LoggerFactory.getLogger(BrooklynLogging.SSH_IO); protected interface ExecRunner { public int exec(SshTool ssh, Map<String,?> flags, List<String> cmds, Map<String,?> env); } @SetFromFlag("user") String user; @SetFromFlag("privateKeyData") String privateKeyData; @SetFromFlag(nullable = false) InetAddress address; @SetFromFlag Map config; @SetFromFlag transient WithMutexes mutexSupport; @SetFromFlag private Set<Integer> usedPorts; /** any property that should be passed as ssh config (connection-time) * can be prefixed with this and . and will be passed through (with the prefix removed), * e.g. (SSHCONFIG_PREFIX+"."+"StrictHostKeyChecking"):"yes" */ public static final String SSHCONFIG_PREFIX = "sshconfig"; /** properties which are passed to ssh */ public static final Collection<String> SSH_PROPS = ImmutableSet.of( "noStdoutLogging", "noStderrLogging", "logPrefix", "out", "err", "password", "permissions", "sshTries", "env", "allocatePTY", "privateKeyPassphrase", "privateKeyFile", "privateKeyData", // deprecated in 0.4.0 -- prefer privateKeyData/privateKeyFile // (confusion about whether other holds a file or data; and public not useful here) // they generate a warning where used "keyFiles", "publicKey", "privateKey"); //TODO remove once everything is prefixed SSHCONFIG_PREFIX or included above public static final Collection<String> NON_SSH_PROPS = ImmutableSet.of("latitude", "longitude", "backup", "sshPublicKeyData", "sshPrivateKeyData"); private transient Pool<SshTool> vanillaSshToolPool; public SshMachineLocation() { this(MutableMap.of()); } public SshMachineLocation(Map properties) { super(properties); usedPorts = (usedPorts != null) ? Sets.newLinkedHashSet(usedPorts) : Sets.<Integer>newLinkedHashSet(); vanillaSshToolPool = buildVanillaPool(); } private BasicPool<SshTool> buildVanillaPool() { return BasicPool.<SshTool>builder() .name(name+":"+address+":"+System.identityHashCode(this)) .supplier(new Supplier<SshTool>() { @Override public SshTool get() { return connectSsh(Collections.emptyMap()); }}) .viabilityChecker(new Predicate<SshTool>() { @Override public boolean apply(SshTool input) { return input != null && input.isConnected(); }}) .closer(new Function<SshTool,Void>() { @Override public Void apply(SshTool input) { try { input.disconnect(); } catch (Exception e) { if (logSsh.isDebugEnabled()) logSsh.debug("On machine "+SshMachineLocation.this+", ssh-disconnect failed", e); } return null; }}) .build(); } public void configure() { configure(MutableMap.of()); } public void configure(Map properties) { if (config==null) config = Maps.newLinkedHashMap(); super.configure(properties); // TODO Note that check for addresss!=null is done automatically in super-constructor, in FlagUtils.checkRequiredFields // Yikes, dangerous code for accessing fields of sub-class in super-class' constructor! But getting away with it so far! if (mutexSupport == null) { mutexSupport = new MutexSupport(); } boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class)); if (!deferConstructionChecks) { if (properties.containsKey("username")) { LOG.warn("Using deprecated ssh machine property 'username': use 'user' instead", new Throwable("source of deprecated ssh 'username' invocation")); user = ""+properties.get("username"); } if (name == null) { name = (truth(user) ? user+"@" : "") + address.getHostName(); } if (getHostGeoInfo() == null) { Location parentLocation = getParentLocation(); if ((parentLocation instanceof HasHostGeoInfo) && ((HasHostGeoInfo)parentLocation).getHostGeoInfo()!=null) setHostGeoInfo( ((HasHostGeoInfo)parentLocation).getHostGeoInfo() ); else setHostGeoInfo(HostGeoInfo.fromLocation(this)); } } } @Override public void close() { vanillaSshToolPool.closePool(); } @Override protected void finalize() throws Throwable { close(); } public InetAddress getAddress() { return address; } public String getUser() { return user; } public Map getConfig() { return config; } public int run(String command) { return run(MutableMap.of(), command, MutableMap.of()); } public int run(Map props, String command) { return run(props, command, MutableMap.of()); } public int run(String command, Map env) { return run(MutableMap.of(), command, env); } public int run(Map props, String command, Map env) { return run(props, ImmutableList.of(command), env); } /** * @deprecated in 1.4.1, @see execCommand and execScript */ public int run(List<String> commands) { return run(MutableMap.of(), commands, MutableMap.of()); } public int run(Map props, List<String> commands) { return run(props, commands, MutableMap.of()); } public int run(List<String> commands, Map env) { return run(MutableMap.of(), commands, env); } public int run(final Map props, final List<String> commands, final Map env) { if (commands == null || commands.isEmpty()) return 0; return execSsh(props, new Function<SshTool, Integer>() { public Integer apply(SshTool ssh) { return ssh.execScript(props, commands, env); }}); } protected <T> T execSsh(Map props, Function<SshTool,T> task) { if (props.isEmpty()) { return vanillaSshToolPool.exec(task); } else { SshTool ssh = connectSsh(props); try { return task.apply(ssh); } finally { ssh.disconnect(); } } } protected SshTool connectSsh() { return connectSsh(ImmutableMap.of()); } protected boolean previouslyConnected = false; protected SshTool connectSsh(Map props) { try { if (!truth(user)) user = System.getProperty("user.name"); Map<?,?> allprops = MutableMap.builder().putAll(config).putAll(leftoverProperties).putAll(props).build(); Map<String,Object> args = MutableMap.<String,Object>of("user", user, "host", address.getHostName()); for (Map.Entry<?, ?> entry : allprops.entrySet()) { String k = ""+entry.getKey(); Object v = entry.getValue(); if (SSH_PROPS.contains(k)) { args.put(k, v); } else if (k.startsWith(SSHCONFIG_PREFIX+".")) { args.put(k.substring(SSHCONFIG_PREFIX.length()+1), v); } else { // TODO remove once everything is included above and we no longer see these warnings if (!NON_SSH_PROPS.contains(k)) { LOG.warn("including legacy SSH config property "+k+" for "+this+"; either prefix with sshconfig or add to NON_SSH_PROPS"); args.put(k, v); } } } if (LOG.isTraceEnabled()) LOG.trace("creating ssh session for "+args); SshTool ssh = new SshjTool(args); Tasks.setBlockingDetails("Opening ssh connection"); try { ssh.connect(); } finally { Tasks.setBlockingDetails(null); } previouslyConnected = true; return ssh; } catch (Exception e) { if (previouslyConnected) throw Throwables.propagate(e); // subsequence connection (above) most likely network failure, our remarks below won't help // on first connection include additional information if we can't connect, to help with debugging String rootCause = Throwables.getRootCause(e).getMessage(); throw new IllegalStateException("Cannot establish ssh connection to "+user+" @ "+this+ (rootCause!=null && !rootCause.isEmpty() ? " ("+rootCause+")" : "")+". \n"+ "Ensure that passwordless and passphraseless ssh access is enabled using standard keys from ~/.ssh or " + "as configured in brooklyn.properties. " + "Check that the target host is accessible, that correct permissions are set on your keys, " + "and that there is sufficient random noise in /dev/random on both ends. " + "To debug less common causes, see the original error in the trace or log, and/or enable 'net.schmizz' (sshj) logging." , e); } } /** * Convenience for running commands using ssh {@literal exec} mode. * @deprecated in 1.4.1, @see execCommand and execScript */ public int exec(List<String> commands) { return exec(MutableMap.of(), commands, MutableMap.of()); } public int exec(Map props, List<String> commands) { return exec(props, commands, MutableMap.of()); } public int exec(List<String> commands, Map env) { return exec(MutableMap.of(), commands, env); } public int exec(final Map props, final List<String> commands, final Map env) { Preconditions.checkNotNull(address, "host address must be specified for ssh"); if (commands == null || commands.isEmpty()) return 0; return execSsh(props, new Function<SshTool, Integer>() { public Integer apply(SshTool ssh) { return ssh.execCommands(props, commands, env); }}); } // TODO submitCommands and submitScript which submit objects we can subsequently poll (cf JcloudsSshMachineLocation.submitRunScript) /** executes a set of commands, directly on the target machine (no wrapping in script). * joined using ' ; ' by default. * <p> * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use * the flag 'logPrefix'. * <p> * Currently runs the commands in an interactive/login shell * by passing each as a line to bash. To terminate early, use: * <pre> * foo || exit 1 * </pre> * It may be desirable instead, in some situations, to wrap as: * <pre> * { line1 ; } && { line2 ; } ... * </pre> * and run as a single command (possibly not as an interacitve/login * shell) causing the script to exit on the first command which fails. * <p> * Currently this has to be done by the caller. * (If desired we can add a flag {@code exitIfAnyNonZero} to support this mode, * and/or {@code commandPrepend} and {@code commandAppend} similar to * (currently supported in SshjTool) {@code separator}.) */ public int execCommands(String summaryForLogging, List<String> commands) { return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands) { return execCommands(props, summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execCommands(String summaryForLogging, List<String> commands, Map<String,?> env) { return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, env); } public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) { return execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() { @Override public int exec(SshTool ssh, Map<String,?> flags, List<String> cmds, Map<String,?> env) { return ssh.execCommands(flags, cmds, env); }}); } /** executes a set of commands, wrapped as a script sent to the remote machine. * <p> * Stdout and stderr will be logged automatically to brooklyn.SSH logger, unless the * flags 'noStdoutLogging' and 'noStderrLogging' are set. To set a logging prefix, use * the flag 'logPrefix'. */ public int execScript(String summaryForLogging, List<String> commands) { return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands) { return execScript(props, summaryForLogging, commands, MutableMap.<String,Object>of()); } public int execScript(String summaryForLogging, List<String> commands, Map<String,?> env) { return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, env); } public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) { return execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() { @Override public int exec(SshTool ssh, Map<String, ?> flags, List<String> cmds, Map<String, ?> env) { return ssh.execScript(flags, cmds, env); }}); } protected int execWithLogging(Map<String,?> props, String summaryForLogging, List<String> commands, Map env, final Closure<Integer> execCommand) { return execWithLogging(props, summaryForLogging, commands, env, new ExecRunner() { @Override public int exec(SshTool ssh, Map<String, ?> flags, List<String> cmds, Map<String, ?> env) { return execCommand.call(ssh, flags, cmds, env); }}); } protected int execWithLogging(Map<String,?> props, final String summaryForLogging, final List<String> commands, final Map<String,?> env, final ExecRunner execCommand) { if (logSsh.isDebugEnabled()) logSsh.debug("{} on machine {}: {}", new Object[] {summaryForLogging, this, commands}); Preconditions.checkNotNull(address, "host address must be specified for ssh"); if (commands.isEmpty()) { logSsh.debug("{} on machine {} ending: no commands to run", summaryForLogging, this); return 0; } final Map<String,Object> execFlags = MutableMap.copyOf(props); final Map<String,Object> sshFlags = MutableMap.<String,Object>builder().putAll(props).removeAll("logPrefix", "out", "err").build(); PipedOutputStream outO = null; PipedOutputStream outE = null; StreamGobbler gO=null, gE=null; try { String logPrefix; if (execFlags.get("logPrefix") != null) { logPrefix = ""+execFlags.get("logPrefix"); } else { String hostname = getAddress().getHostName(); Object port = config.get("sshconfig.port"); if (port == null) port = leftoverProperties.get("sshconfig.port"); logPrefix = (user != null ? user+"@" : "") + hostname + (port != null ? ":"+port : ""); } if (!truth(execFlags.get("noStdoutLogging"))) { PipedInputStream insO = new PipedInputStream(); outO = new PipedOutputStream(insO); String stdoutLogPrefix = "["+(logPrefix != null ? logPrefix+":stdout" : "stdout")+"] "; gO = new StreamGobbler(insO, (OutputStream) execFlags.get("out"), logSsh).setLogPrefix(stdoutLogPrefix); gO.start(); execFlags.put("out", outO); } if (!truth(execFlags.get("noStdoutLogging"))) { PipedInputStream insE = new PipedInputStream(); outE = new PipedOutputStream(insE); String stderrLogPrefix = "["+(logPrefix != null ? logPrefix+":stderr" : "stderr")+"] "; gE = new StreamGobbler(insE, (OutputStream) execFlags.get("err"), logSsh).setLogPrefix(stderrLogPrefix); gE.start(); execFlags.put("err", outE); } Tasks.setBlockingDetails("SSH executing, "+summaryForLogging); try { return execSsh(sshFlags, new Function<SshTool, Integer>() { public Integer apply(SshTool ssh) { int result = execCommand.exec(ssh, execFlags, commands, env); if (logSsh.isDebugEnabled()) logSsh.debug("{} on machine {} completed: return status {}", new Object[] {summaryForLogging, this, result}); return result; }}); } finally { Tasks.setBlockingDetails(null); } } catch (IOException e) { if (logSsh.isDebugEnabled()) logSsh.debug("{} on machine {} failed: {}", new Object[] {summaryForLogging, this, e}); throw Throwables.propagate(e); } finally { // Must close the pipedOutStreams, otherwise input will never read -1 so StreamGobbler thread would never die if (outO!=null) try { outO.flush(); } catch (IOException e) {} if (outE!=null) try { outE.flush(); } catch (IOException e) {} Closeables.closeQuietly(outO); Closeables.closeQuietly(outE); try { if (gE!=null) { gE.join(); } if (gO!=null) { gO.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); Throwables.propagate(e); } } } public int copyTo(File src, File destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, File src, File destination) { return copyTo(props, src, destination.getPath()); } // FIXME the return code is not a reliable indicator of success or failure public int copyTo(File src, String destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, File src, String destination) { Preconditions.checkNotNull(address, "Host address must be specified for scp"); Preconditions.checkArgument(src.exists(), "File %s must exist for scp", src.getPath()); try { return copyTo(props, new FileInputStream(src), src.length(), destination); } catch (FileNotFoundException e) { throw Throwables.propagate(e); } } public int copyTo(Reader src, String destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, Reader src, String destination) { return copyTo(props, new ReaderInputStream(src), destination); } public int copyTo(InputStream src, String destination) { return copyTo(MutableMap.<String,Object>of(), src, destination); } public int copyTo(Map<String,?> props, InputStream src, String destination) { return copyTo(props, src, -1, destination); } public int copyTo(InputStream src, long filesize, String destination) { return copyTo(MutableMap.<String,Object>of(), src, filesize, destination); } public int copyTo(final Map<String,?> props, InputStream src, long filesize, final String destination) { final long finalFilesize; final InputStream finalSrc; if (filesize==-1) { try { File tempFile = ResourceUtils.writeToTempFile(src, "sshcopy", "data"); finalFilesize = tempFile.length(); finalSrc = new FileInputStream(tempFile); } catch (IOException e) { throw Throwables.propagate(e); } finally { Closeables.closeQuietly(src); } } else { finalFilesize = filesize; finalSrc = src; } return execSsh(props, new Function<SshTool,Integer>() { public Integer apply(SshTool ssh) { return ssh.createFile(props, destination, finalSrc, finalFilesize); }}); } // FIXME the return code is not a reliable indicator of success or failure public int copyFrom(String remote, String local) { return copyFrom(MutableMap.<String,Object>of(), remote, local); } public int copyFrom(final Map<String,?> props, final String remote, final String local) { return execSsh(props, new Function<SshTool,Integer>() { public Integer apply(SshTool ssh) { return ssh.transferFileFrom(props, remote, local); }}); } /** installs the given URL at the indicated destination. * attempts to curl the sourceUrl on the remote machine, * then if that fails, loads locally (from classpath or file) and transfers. * <p> * accepts either a path (terminated with /) or filename for the destination. **/ public int installTo(ResourceUtils loader, String url, String destination) { if (destination.endsWith("/")) { String destName = url; destName = destName.contains("?") ? destName.substring(0, destName.indexOf("?")) : destName; destName = destName.substring(destName.lastIndexOf('/')+1); destination = destination + destName; } LOG.debug("installing {} to {} on {}, attempting remote curl", new Object[] {url, destination, this}); try { PipedInputStream insO = new PipedInputStream(); OutputStream outO = new PipedOutputStream(insO); PipedInputStream insE = new PipedInputStream(); OutputStream outE = new PipedOutputStream(insE); new StreamGobbler(insO, null, LOG).setLogPrefix("[curl @ "+address+":stdout] ").start(); new StreamGobbler(insE, null, LOG).setLogPrefix("[curl @ "+address+":stdout] ").start(); int result = exec(MutableMap.of("out", outO, "err", outE), ImmutableList.of("curl "+url+" -L --silent --insecure --show-error --fail --connect-timeout 60 --max-time 600 --retry 5 -o "+destination)); if (result!=0 && loader!=null) { LOG.debug("installing {} to {} on {}, curl failed, attempting local fetch and copy", new Object[] {url, destination, this}); result = copyTo(loader.getResourceFromUrl(url), destination); } if (result==0) LOG.debug("installing {} complete; {} on {}", new Object[] {url, destination, this}); else LOG.warn("installing {} failed; {} on {}: {}", new Object[] {url, destination, this, result}); return result; } catch (IOException e) { throw Throwables.propagate(e); } } @Override public String toString() { return "SshMachineLocation["+name+":"+address+"]"; } /** * @see #obtainPort(PortRange) * @see BasicPortRange#ANY_HIGH_PORT */ public boolean obtainSpecificPort(int portNumber) { // TODO Does not yet check if the port really is free on this machine if (usedPorts.contains(portNumber)) { return false; } else { usedPorts.add(portNumber); return true; } } public int obtainPort(PortRange range) { for (int p: range) if (obtainSpecificPort(p)) return p; if (LOG.isDebugEnabled()) LOG.debug("unable to find port in {} on {}; returning -1", range, this); return -1; } public void releasePort(int portNumber) { usedPorts.remove((Object) portNumber); } public boolean isSshable() { String cmd = "date"; try { int result = run(cmd); if (result == 0) { return true; } else { if (LOG.isDebugEnabled()) LOG.debug("Not reachable: {}, executing `{}`, exit code {}", new Object[] {this, cmd, result}); return false; } } catch (SshException e) { if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e); return false; } catch (IllegalStateException e) { if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e); return false; } catch (RuntimeException e) { if (Throwables2.getFirstThrowableOfType(e, IOException.class) != null) { if (LOG.isDebugEnabled()) LOG.debug("Exception checking if "+this+" is reachable; assuming not", e); return false; } else { throw e; } } } @Override public OsDetails getOsDetails() { // TODO ssh and find out what we need to know, or use jclouds... return BasicOsDetails.Factory.ANONYMOUS_LINUX; } protected WithMutexes newMutexSupport() { return new MutexSupport(); } @Override public void acquireMutex(String mutexId, String description) throws InterruptedException { mutexSupport.acquireMutex(mutexId, description); } @Override public boolean tryAcquireMutex(String mutexId, String description) { return mutexSupport.tryAcquireMutex(mutexId, description); } @Override public void releaseMutex(String mutexId) { mutexSupport.releaseMutex(mutexId); } @Override public boolean hasMutex(String mutexId) { return mutexSupport.hasMutex(mutexId); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); vanillaSshToolPool = buildVanillaPool(); } }
Added comments why the SshMachineLocation support serialization
core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
Added comments why the SshMachineLocation support serialization
<ide><path>ore/src/main/java/brooklyn/location/basic/SshMachineLocation.java <ide> return mutexSupport.hasMutex(mutexId); <ide> } <ide> <add> //We want want the SshMachineLocation to be serializable and therefor the pool needs to be dealt with correctly. <add> //In this case we are not serializing the pool (we made the field transient) and create a new pool when deserialized. <add> //This fix is currently needed for experiments, but isn't used in normal Brooklyn usage. <ide> private void readObject(java.io.ObjectInputStream in) <ide> throws IOException, ClassNotFoundException { <ide> in.defaultReadObject();
Java
mpl-2.0
error: pathspec 'etomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java' did not match any file(s) known to git
96eb22e8c2bbd84c242b1959da2d320e951aec16
1
etomica/etomica,etomica/etomica,etomica/etomica
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.mappedDensity.positionOrientation; import etomica.action.BoxInflate; import etomica.action.activity.ActivityIntegrate; import etomica.atom.AtomType; import etomica.box.Box; import etomica.config.ConfigurationLattice; import etomica.config.ConformationChainLinear; import etomica.data.AccumulatorAverageCollapsing; import etomica.data.DataPumpListener; import etomica.data.meter.MeterPotentialEnergyFromIntegrator; import etomica.dcvgcmd.P1WCAWall; import etomica.graphics.ColorSchemeRandomByMolecule; import etomica.graphics.DisplayTextBoxesCAE; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorMC; import etomica.integrator.mcmove.MCMoveMolecule; import etomica.integrator.mcmove.MCMoveMoleculeRotate; import etomica.lattice.LatticeCubicFcc; import etomica.lattice.LatticeOrthorhombicHexagonal; import etomica.nbr.cell.PotentialMasterCell; import etomica.potential.BondingInfo; import etomica.potential.P2LennardJones; import etomica.potential.P2SoftSphericalTruncatedForceShifted; import etomica.potential.PotentialMaster; import etomica.potential.compute.PotentialComputeAggregate; import etomica.potential.compute.PotentialComputeField; import etomica.simulation.Simulation; import etomica.space.BoundaryRectangularSlit; import etomica.space.Space; import etomica.space.Vector; import etomica.species.SpeciesBuilder; import etomica.species.SpeciesGeneral; import etomica.units.Degree; import etomica.util.ParameterBase; import etomica.util.ParseArgs; import java.util.Arrays; /** * Simple Lennard-Jones molecular dynamics simulation in 3D */ public class LJMCDimer extends Simulation { public IntegratorMC integrator; public SpeciesGeneral species; public Box box; public P2LennardJones potential; public LJMCDimer(int D, int numMolecules, double density, double temperature) { super(Space.getInstance(D)); double a = Degree.UNIT.toSim(45); double[] a2 = new double[D-1]; Arrays.fill(a2, a); species = new SpeciesBuilder(space) .addCount(AtomType.simpleFromSim(this), 2) .setDynamic(true) .withConformation(new ConformationChainLinear(space, 1, a2)) .build(); addSpecies(species); double sigma = 1.0; box = this.makeBox(new BoundaryRectangularSlit(2, getSpace())); PotentialMaster potentialMaster = new PotentialMasterCell(this.getSpeciesManager(), box, 2, BondingInfo.noBonding()); P1WCAWall wall = new P1WCAWall(box, 1, 1); PotentialComputeField pcField = new PotentialComputeField(getSpeciesManager(), box); AtomType leafType = species.getLeafType(); pcField.setFieldPotential(leafType, wall); PotentialComputeAggregate pcAgg = new PotentialComputeAggregate(potentialMaster, pcField); integrator = new IntegratorMC(pcAgg, this.getRandom(), 1.0, box); integrator.setTemperature(temperature); integrator.getMoveManager().addMCMove(new MCMoveMolecule(this.getRandom(), pcAgg, box)); integrator.getMoveManager().addMCMove(new MCMoveMoleculeRotate(this.getRandom(), pcAgg, box)); box.setNMolecules(species, numMolecules); new BoxInflate(box, space, 1.2*density).actionPerformed(); potential = new P2LennardJones(sigma, 1.0); P2SoftSphericalTruncatedForceShifted p2 = new P2SoftSphericalTruncatedForceShifted(potential, 3.0); potentialMaster.setPairPotential(leafType, leafType, p2); ConfigurationLattice configuration = new ConfigurationLattice(D==3 ? new LatticeCubicFcc(space) : new LatticeOrthorhombicHexagonal(space), space); configuration.initializeCoordinates(box); Vector l = box.getBoundary().getBoxSize(); l.setX(2, l.getX(2)*1.2); box.getBoundary().setBoxSize(l); } public static void main(String[] args) { DimerParams params = new DimerParams(); if (args.length > 0) { ParseArgs.doParseArgs(params, args); } else { // override defaults here params.D = 2; } int numMolecules = params.numMolecules; double temperature = params.temperature; double density = params.density; int D = params.D; final LJMCDimer sim = new LJMCDimer(D, numMolecules, density, temperature); boolean graphics = true; MeterPotentialEnergyFromIntegrator energy = new MeterPotentialEnergyFromIntegrator(sim.integrator); if (graphics) { final String APP_NAME = "LJMDDimer"; sim.getController().addActivity(new ActivityIntegrate(sim.integrator)); final SimulationGraphic simGraphic = new SimulationGraphic(sim, APP_NAME, 3); AccumulatorAverageCollapsing avgEnergy = new AccumulatorAverageCollapsing(); avgEnergy.setPushInterval(10); DataPumpListener pump = new DataPumpListener(energy, avgEnergy, numMolecules); sim.integrator.getEventManager().addListener(pump); simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box)); simGraphic.getController().getDataStreamPumps().add(pump); simGraphic.getDisplayBox(sim.box).setColorScheme(new ColorSchemeRandomByMolecule(sim.getSpeciesManager(), sim.box, sim.getRandom())); simGraphic.makeAndDisplayFrame(APP_NAME); DisplayTextBoxesCAE display = new DisplayTextBoxesCAE(); display.setAccumulator(avgEnergy); simGraphic.add(display); return; } } public static class DimerParams extends ParameterBase { public int numMolecules = 256; public double temperature = 2; public double density = 0.4; public int D = 3; } }
etomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java
add confined dimer simulation
etomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java
add confined dimer simulation
<ide><path>tomica-apps/src/main/java/etomica/mappedDensity/positionOrientation/LJMCDimer.java <add>/* This Source Code Form is subject to the terms of the Mozilla Public <add> * License, v. 2.0. If a copy of the MPL was not distributed with this <add> * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <add> <add>package etomica.mappedDensity.positionOrientation; <add> <add>import etomica.action.BoxInflate; <add>import etomica.action.activity.ActivityIntegrate; <add>import etomica.atom.AtomType; <add>import etomica.box.Box; <add>import etomica.config.ConfigurationLattice; <add>import etomica.config.ConformationChainLinear; <add>import etomica.data.AccumulatorAverageCollapsing; <add>import etomica.data.DataPumpListener; <add>import etomica.data.meter.MeterPotentialEnergyFromIntegrator; <add>import etomica.dcvgcmd.P1WCAWall; <add>import etomica.graphics.ColorSchemeRandomByMolecule; <add>import etomica.graphics.DisplayTextBoxesCAE; <add>import etomica.graphics.SimulationGraphic; <add>import etomica.integrator.IntegratorMC; <add>import etomica.integrator.mcmove.MCMoveMolecule; <add>import etomica.integrator.mcmove.MCMoveMoleculeRotate; <add>import etomica.lattice.LatticeCubicFcc; <add>import etomica.lattice.LatticeOrthorhombicHexagonal; <add>import etomica.nbr.cell.PotentialMasterCell; <add>import etomica.potential.BondingInfo; <add>import etomica.potential.P2LennardJones; <add>import etomica.potential.P2SoftSphericalTruncatedForceShifted; <add>import etomica.potential.PotentialMaster; <add>import etomica.potential.compute.PotentialComputeAggregate; <add>import etomica.potential.compute.PotentialComputeField; <add>import etomica.simulation.Simulation; <add>import etomica.space.BoundaryRectangularSlit; <add>import etomica.space.Space; <add>import etomica.space.Vector; <add>import etomica.species.SpeciesBuilder; <add>import etomica.species.SpeciesGeneral; <add>import etomica.units.Degree; <add>import etomica.util.ParameterBase; <add>import etomica.util.ParseArgs; <add> <add>import java.util.Arrays; <add> <add>/** <add> * Simple Lennard-Jones molecular dynamics simulation in 3D <add> */ <add>public class LJMCDimer extends Simulation { <add> <add> public IntegratorMC integrator; <add> public SpeciesGeneral species; <add> public Box box; <add> public P2LennardJones potential; <add> <add> public LJMCDimer(int D, int numMolecules, double density, double temperature) { <add> super(Space.getInstance(D)); <add> <add> double a = Degree.UNIT.toSim(45); <add> double[] a2 = new double[D-1]; <add> Arrays.fill(a2, a); <add> species = new SpeciesBuilder(space) <add> .addCount(AtomType.simpleFromSim(this), 2) <add> .setDynamic(true) <add> .withConformation(new ConformationChainLinear(space, 1, a2)) <add> .build(); <add> addSpecies(species); <add> <add> double sigma = 1.0; <add> box = this.makeBox(new BoundaryRectangularSlit(2, getSpace())); <add> PotentialMaster potentialMaster = new PotentialMasterCell(this.getSpeciesManager(), box, 2, BondingInfo.noBonding()); <add> P1WCAWall wall = new P1WCAWall(box, 1, 1); <add> PotentialComputeField pcField = new PotentialComputeField(getSpeciesManager(), box); <add> AtomType leafType = species.getLeafType(); <add> pcField.setFieldPotential(leafType, wall); <add> PotentialComputeAggregate pcAgg = new PotentialComputeAggregate(potentialMaster, pcField); <add> <add> integrator = new IntegratorMC(pcAgg, this.getRandom(), 1.0, box); <add> integrator.setTemperature(temperature); <add> <add> integrator.getMoveManager().addMCMove(new MCMoveMolecule(this.getRandom(), pcAgg, box)); <add> integrator.getMoveManager().addMCMove(new MCMoveMoleculeRotate(this.getRandom(), pcAgg, box)); <add> <add> box.setNMolecules(species, numMolecules); <add> new BoxInflate(box, space, 1.2*density).actionPerformed(); <add> <add> potential = new P2LennardJones(sigma, 1.0); <add> P2SoftSphericalTruncatedForceShifted p2 = new P2SoftSphericalTruncatedForceShifted(potential, 3.0); <add> potentialMaster.setPairPotential(leafType, leafType, p2); <add> <add> ConfigurationLattice configuration = new ConfigurationLattice(D==3 ? new LatticeCubicFcc(space) : new LatticeOrthorhombicHexagonal(space), space); <add> configuration.initializeCoordinates(box); <add> Vector l = box.getBoundary().getBoxSize(); <add> l.setX(2, l.getX(2)*1.2); <add> box.getBoundary().setBoxSize(l); <add> } <add> <add> public static void main(String[] args) { <add> DimerParams params = new DimerParams(); <add> if (args.length > 0) { <add> ParseArgs.doParseArgs(params, args); <add> } <add> else { <add> // override defaults here <add> params.D = 2; <add> } <add> <add> int numMolecules = params.numMolecules; <add> double temperature = params.temperature; <add> double density = params.density; <add> int D = params.D; <add> <add> final LJMCDimer sim = new LJMCDimer(D, numMolecules, density, temperature); <add> <add> boolean graphics = true; <add> <add> MeterPotentialEnergyFromIntegrator energy = new MeterPotentialEnergyFromIntegrator(sim.integrator); <add> <add> if (graphics) { <add> final String APP_NAME = "LJMDDimer"; <add> sim.getController().addActivity(new ActivityIntegrate(sim.integrator)); <add> final SimulationGraphic simGraphic = new SimulationGraphic(sim, APP_NAME, 3); <add> <add> AccumulatorAverageCollapsing avgEnergy = new AccumulatorAverageCollapsing(); <add> avgEnergy.setPushInterval(10); <add> DataPumpListener pump = new DataPumpListener(energy, avgEnergy, numMolecules); <add> sim.integrator.getEventManager().addListener(pump); <add> <add> simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box)); <add> simGraphic.getController().getDataStreamPumps().add(pump); <add> simGraphic.getDisplayBox(sim.box).setColorScheme(new ColorSchemeRandomByMolecule(sim.getSpeciesManager(), sim.box, sim.getRandom())); <add> <add> simGraphic.makeAndDisplayFrame(APP_NAME); <add> <add> DisplayTextBoxesCAE display = new DisplayTextBoxesCAE(); <add> display.setAccumulator(avgEnergy); <add> simGraphic.add(display); <add> return; <add> } <add> } <add> <add> public static class DimerParams extends ParameterBase { <add> public int numMolecules = 256; <add> public double temperature = 2; <add> public double density = 0.4; <add> public int D = 3; <add> } <add>}
JavaScript
apache-2.0
bd86158ec8259efd8b955427020b883d9b8f830b
0
jbeezley/girder,RafaelPalomar/girder,kotfic/girder,kotfic/girder,RafaelPalomar/girder,data-exp-lab/girder,data-exp-lab/girder,jbeezley/girder,Kitware/girder,Kitware/girder,Xarthisius/girder,RafaelPalomar/girder,Xarthisius/girder,Xarthisius/girder,sutartmelson/girder,sutartmelson/girder,Xarthisius/girder,girder/girder,RafaelPalomar/girder,adsorensen/girder,manthey/girder,sutartmelson/girder,girder/girder,Xarthisius/girder,adsorensen/girder,Kitware/girder,adsorensen/girder,kotfic/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,jbeezley/girder,Kitware/girder,girder/girder,girder/girder,jbeezley/girder,sutartmelson/girder,manthey/girder,sutartmelson/girder,manthey/girder,adsorensen/girder,adsorensen/girder,kotfic/girder,data-exp-lab/girder,kotfic/girder,data-exp-lab/girder
module.exports = function(config) { config.module.loaders.push({ test: /\.glsl$/, loader: 'shader', include: [/node_modules(\/|\\)vtk\.js(\/|\\)/], }); config.module.loaders.push({ test: /\.js$/, include: [/node_modules(\/|\\)vtk\.js(\/|\\)/], loader: 'babel?presets[]=es2015,presets[]=react!string-replace?{"multiple":[{"search":"vtkDebugMacro","replace":"console.debug","flags":"g"},{"search":"vtkErrorMacro","replace":"console.error","flags":"g"},{"search":"vtkWarningMacro","replace":"console.warn","flags":"g"},{"search":"test.onlyIfWebGL","replace":"test","flags":"g"}]}', }); return config; }
plugins/dicom_viewer/webpack.helper.js
module.exports = function(config) { config.module.loaders.push({ test: /\.json$/, loader: 'json', include: [ /node_modules(\/|\\)vtk\.js(\/|\\)/, /node_modules(\/|\\)diffie-hellman(\/|\\)/, /node_modules(\/|\\)elliptic(\/|\\)/, /node_modules(\/|\\)parse-asn1(\/|\\)/, ], }); config.module.loaders.push({ test: /\.glsl$/, loader: 'shader', include: [/node_modules(\/|\\)vtk\.js(\/|\\)/], }); config.module.loaders.push({ test: /\.js$/, include: [/node_modules(\/|\\)vtk\.js(\/|\\)/], loader: 'babel?presets[]=es2015,presets[]=react!string-replace?{"multiple":[{"search":"vtkDebugMacro","replace":"console.debug","flags":"g"},{"search":"vtkErrorMacro","replace":"console.error","flags":"g"},{"search":"vtkWarningMacro","replace":"console.warn","flags":"g"},{"search":"test.onlyIfWebGL","replace":"test","flags":"g"}]}', }); return config; }
remove json loader in webpack helper
plugins/dicom_viewer/webpack.helper.js
remove json loader in webpack helper
<ide><path>lugins/dicom_viewer/webpack.helper.js <ide> module.exports = function(config) { <del> config.module.loaders.push({ <del> test: /\.json$/, <del> loader: 'json', <del> include: [ <del> /node_modules(\/|\\)vtk\.js(\/|\\)/, <del> /node_modules(\/|\\)diffie-hellman(\/|\\)/, <del> /node_modules(\/|\\)elliptic(\/|\\)/, <del> /node_modules(\/|\\)parse-asn1(\/|\\)/, <del> ], <del> }); <ide> config.module.loaders.push({ <ide> test: /\.glsl$/, <ide> loader: 'shader',
Java
agpl-3.0
e9355878572afb4b18fedb86c6b2342de0b8a2cd
0
bharavi/jPOS,jpos/jPOS,atancasis/jPOS,c0deh4xor/jPOS,juanibdn/jPOS,alcarraz/jPOS,jpos/jPOS,atancasis/jPOS,c0deh4xor/jPOS,bharavi/jPOS,poynt/jPOS,sebastianpacheco/jPOS,sebastianpacheco/jPOS,barspi/jPOS,barspi/jPOS,juanibdn/jPOS,alcarraz/jPOS,atancasis/jPOS,poynt/jPOS,jpos/jPOS,poynt/jPOS,bharavi/jPOS,yinheli/jPOS,barspi/jPOS,c0deh4xor/jPOS,juanibdn/jPOS,sebastianpacheco/jPOS,yinheli/jPOS,yinheli/jPOS,alcarraz/jPOS
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2015 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.transaction; import org.jdom.Element; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.*; import org.jpos.util.*; import java.io.Serializable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import org.jpos.iso.ISOUtil; @SuppressWarnings("unchecked unused") public class TransactionManager extends QBeanSupport implements Runnable, TransactionConstants, TransactionManagerMBean { public static final String HEAD = "$HEAD"; public static final String TAIL = "$TAIL"; public static final String CONTEXT = "$CONTEXT."; public static final String STATE = "$STATE."; public static final String GROUPS = "$GROUPS."; public static final String TAILLOCK = "$TAILLOCK"; public static final String RETRY_QUEUE = "$RETRY_QUEUE"; public static final Integer PREPARING = 0; public static final Integer COMMITTING = 1; public static final Integer DONE = 2; public static final String DEFAULT_GROUP = ""; public static final long MAX_PARTICIPANTS = 1000; // loop prevention public static final long MAX_WAIT = 15000L; public static final long TIMER_PURGE_INTERVAL = 1000L; protected Map<String,List<TransactionParticipant>> groups; private static final ThreadLocal<Serializable> tlContext = new ThreadLocal<Serializable>(); private static final ThreadLocal<Long> tlId = new ThreadLocal<Long>(); Space sp; Space psp; Space isp; // input space String queue; String tailLock; List<Thread> threads; final List<TransactionStatusListener> statusListeners = new ArrayList<TransactionStatusListener>(); boolean hasStatusListeners; boolean debug; boolean profiler; boolean doRecover; boolean callSelectorOnAbort; int sessions; int maxSessions; int threshold; int maxActiveSessions; AtomicInteger activeSessions = new AtomicInteger(); long head, tail; long retryInterval = 5000L; long retryTimeout = 60000L; long pauseTimeout = 0L; Runnable retryTask = null; TPS tps; final Timer timer = DefaultTimer.getTimer(); @Override public void initService () throws ConfigurationException { queue = cfg.get ("queue", null); if (queue == null) throw new ConfigurationException ("queue property not specified"); sp = SpaceFactory.getSpace (cfg.get ("space")); isp = SpaceFactory.getSpace (cfg.get ("input-space", cfg.get ("space"))); psp = SpaceFactory.getSpace (cfg.get ("persistent-space", this.toString())); tail = initCounter (TAIL, cfg.getLong ("initial-tail", 1)); head = Math.max (initCounter (HEAD, tail), tail); initTailLock (); groups = new HashMap<String,List<TransactionParticipant>>(); initParticipants (getPersist()); initStatusListeners (getPersist()); } @Override public void startService () throws Exception { NameRegistrar.register(getName(), this); recover (); threads = Collections.synchronizedList(new ArrayList(maxSessions)); if (tps != null) tps.stop(); tps = new TPS (cfg.getBoolean ("auto-update-tps", true)); for (int i=0; i<sessions; i++) { new Thread(this).start(); } if (psp.rdp (RETRY_QUEUE) != null) checkRetryTask(); } @Override public void stopService () throws Exception { NameRegistrar.unregister (getName ()); Thread[] tt = threads.toArray(new Thread[threads.size()]); for (int i=0; i < tt.length; i++) { isp.out(queue, Boolean.FALSE, 60 * 1000); } for (Thread thread : tt) { try { thread.join (60*1000); threads.remove(thread); } catch (InterruptedException e) { getLog().warn ("Session " + thread.getName() +" does not respond - attempting to interrupt"); thread.interrupt(); } } tps.stop(); } public void queue (Serializable context) { isp.out(queue, context); } public void push (Serializable context) { isp.push(queue, context); } @SuppressWarnings("unused") public String getQueueName() { return queue; } public Space getSpace() { return sp; } public Space getInputSpace() { return isp; } public Space getPersistentSpace() { return psp; } @Override public void run () { long id = 0; int session = 0; // FIXME List<TransactionParticipant> members = null; Iterator<TransactionParticipant> iter = null; PausedTransaction pt; boolean abort = false; LogEvent evt = null; Profiler prof = null; long startTime = 0L; boolean paused; Thread thread = Thread.currentThread(); if (threads.size() < maxSessions) { threads.add(thread); session = threads.indexOf(thread); activeSessions.incrementAndGet(); } else { getLog().warn ("Max sessions reached, new session not created"); return; } getLog().info ("start " + thread); while (running()) { Serializable context = null; prof = null; paused = false; thread.setName (getName() + "-" + session + ":idle"); try { if (hasStatusListeners) notifyStatusListeners (session, TransactionStatusEvent.State.READY, id, "", null); Object obj = isp.in (queue, MAX_WAIT); if (obj == Boolean.FALSE) continue; // stopService ``hack'' if (obj == null) { if (session > sessions && getActiveSessions() > sessions) break; // we are an extra session, exit else continue; } if (session < sessions && // only initial sessions create extra sessions maxSessions > sessions && getActiveSessions() < maxSessions && getOutstandingTransactions() > threshold) { new Thread(this).start(); } if (!(obj instanceof Serializable)) { getLog().error ( "non serializable '" + obj.getClass().getName() + "' on queue '" + queue + "'" ); continue; } context = (Serializable) obj; if (obj instanceof Pausable) { Pausable pausable = (Pausable) obj; pt = pausable.getPausedTransaction(); if (pt != null) { pt.cancelExpirationMonitor(); id = pt.id(); members = pt.members(); iter = pt.iterator(); abort = pt.isAborting(); prof = pt.getProfiler(); if (prof != null) prof.reenable(); } } else pt = null; if (pt == null) { int running = getRunningSessions(); if (maxActiveSessions > 0 && running >= maxActiveSessions) { evt = getLog().createLogEvent ("warn", Thread.currentThread().getName() + ": emergency retry, running-sessions=" + running + ", max-active-sessions=" + maxActiveSessions ); evt.addMessage (obj); psp.out (RETRY_QUEUE, obj, retryTimeout); checkRetryTask(); continue; } abort = false; id = nextId (); members = new ArrayList (); iter = getParticipants (DEFAULT_GROUP).iterator(); } if (debug) { evt = getLog().createLogEvent ("debug", Thread.currentThread().getName() + ":" + Long.toString(id) + (pt != null ? " [resuming]" : "") ); if (prof == null) prof = new Profiler(); else prof.checkPoint("resume"); startTime = System.currentTimeMillis(); } snapshot (id, context, PREPARING); setThreadLocal(id, context); int action = prepare (session, id, context, members, iter, abort, evt, prof); removeThreadLocal(); switch (action) { case PAUSE: paused = true; if (id % TIMER_PURGE_INTERVAL == 0) timer.purge(); break; case PREPARED: setState (id, COMMITTING); setThreadLocal(id, context); commit (session, id, context, members, false, evt, prof); removeThreadLocal(); break; case ABORTED: setThreadLocal(id, context); abort (session, id, context, members, false, evt, prof); removeThreadLocal(); break; case RETRY: psp.out (RETRY_QUEUE, context); checkRetryTask(); break; case NO_JOIN: break; } if ((action & PAUSE) == 0) { snapshot (id, null, DONE); if (id == tail) { checkTail (); } tps.tick(); } } catch (Throwable t) { if (evt == null) getLog().fatal (t); // should never happen else evt.addMessage (t); } finally { removeThreadLocal(); if (hasStatusListeners) { notifyStatusListeners ( session, paused ? TransactionStatusEvent.State.PAUSED : TransactionStatusEvent.State.DONE, id, "", context); } if (getInTransit() > Math.max(maxActiveSessions, activeSessions.get()) * 100) { if (evt == null) evt = getLog().createLogEvent ("warn"); evt.addMessage("WARNING: IN-TRANSIT TOO HIGH"); } if (evt != null) { evt.addMessage ( String.format ("in-transit=%d, head=%d, tail=%d, outstanding=%d, active-sessions=%d/%d, %s, elapsed=%dms", getInTransit(), head, tail, getOutstandingTransactions(), getActiveSessions(), maxSessions, tps.toString(), System.currentTimeMillis() - startTime ) ); if (prof != null) evt.addMessage (prof); Logger.log (evt); evt = null; } } } threads.remove(thread); int currentActiveSessions = activeSessions.decrementAndGet(); getLog().info ("stop " + Thread.currentThread() + ", active sessions=" + currentActiveSessions); } @Override public long getTail () { return tail; } @Override public long getHead () { return head; } public long getInTransit () { return head - tail; } @Override public void setConfiguration (Configuration cfg) throws ConfigurationException { super.setConfiguration (cfg); debug = cfg.getBoolean ("debug"); profiler = cfg.getBoolean ("profiler", debug); if (profiler) debug = true; // profiler needs debug doRecover = cfg.getBoolean ("recover", true); retryInterval = cfg.getLong ("retry-interval", retryInterval); retryTimeout = cfg.getLong ("retry-timeout", retryTimeout); pauseTimeout = cfg.getLong ("pause-timeout", pauseTimeout); maxActiveSessions = cfg.getInt ("max-active-sessions", 0); sessions = cfg.getInt ("sessions", 1); threshold = cfg.getInt ("threshold", sessions / 2); maxSessions = cfg.getInt ("max-sessions", sessions); if (maxSessions < sessions) throw new ConfigurationException("max-sessions < sessions"); if (maxActiveSessions > 0) { if (maxActiveSessions < sessions) throw new ConfigurationException("max-active-sessions < sessions"); if (maxActiveSessions < maxSessions) throw new ConfigurationException("max-active-sessions < max-sessions"); } callSelectorOnAbort = cfg.getBoolean("call-selector-on-abort", true); } public void addListener (TransactionStatusListener l) { synchronized (statusListeners) { statusListeners.add (l); hasStatusListeners = true; } } public void removeListener (TransactionStatusListener l) { synchronized (statusListeners) { statusListeners.remove (l); hasStatusListeners = !statusListeners.isEmpty(); } } public TPS getTPS() { return tps; } @Override public String getTPSAsString() { return tps.toString(); } @Override public float getTPSAvg() { return tps.getAvg(); } @Override public int getTPSPeak() { return tps.getPeak(); } @Override public Date getTPSPeakWhen() { return new Date(tps.getPeakWhen()); } @Override public long getTPSElapsed() { return tps.getElapsed(); } @Override public void resetTPS() { tps.reset(); } protected void commit (int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) { for (TransactionParticipant p :members) { if (recover && p instanceof ContextRecovery) { context = ((ContextRecovery) p).recover (id, context, true); if (evt != null) evt.addMessage (" commit-recover: " + p.getClass().getName()); } if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.COMMITING, id, p.getClass().getName(), context ); commit (p, id, context); if (evt != null) { evt.addMessage (" commit: " + p.getClass().getName()); if (prof != null) prof.checkPoint (" commit: " + p.getClass().getName()); } } } protected void abort (int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) { for (TransactionParticipant p :members) { if (recover && p instanceof ContextRecovery) { context = ((ContextRecovery) p).recover (id, context, false); if (evt != null) evt.addMessage (" abort-recover: " + p.getClass().getName()); } if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.ABORTING, id, p.getClass().getName(), context ); abort (p, id, context); if (evt != null) { evt.addMessage (" abort: " + p.getClass().getName()); if (prof != null) prof.checkPoint (" abort: " + p.getClass().getName()); } } } protected int prepareForAbort (TransactionParticipant p, long id, Serializable context) { try { if (p instanceof AbortParticipant) { setThreadName(id, "prepareForAbort", p); return ((AbortParticipant)p).prepareForAbort (id, context); } } catch (Throwable t) { getLog().warn ("PREPARE-FOR-ABORT: " + Long.toString (id), t); } return ABORTED | NO_JOIN; } protected int prepare (TransactionParticipant p, long id, Serializable context) { try { setThreadName(id, "prepare", p); return p.prepare (id, context); } catch (Throwable t) { getLog().warn ("PREPARE: " + Long.toString (id), t); } return ABORTED; } protected void commit (TransactionParticipant p, long id, Serializable context) { try { setThreadName(id, "commit", p); p.commit (id, context); } catch (Throwable t) { getLog().warn ("COMMIT: " + Long.toString (id), t); } } protected void abort (TransactionParticipant p, long id, Serializable context) { try { setThreadName(id, "abort", p); p.abort (id, context); } catch (Throwable t) { getLog().warn ("ABORT: " + Long.toString (id), t); } } protected int prepare (int session, long id, Serializable context, List<TransactionParticipant> members, Iterator<TransactionParticipant> iter, boolean abort, LogEvent evt, Profiler prof) { boolean retry = false; boolean pause = false; for (int i=0; iter.hasNext (); i++) { int action; if (i > MAX_PARTICIPANTS) { getLog().warn ( "loop detected - transaction " +id + " aborted." ); return ABORTED; } TransactionParticipant p = iter.next(); if (abort) { if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.PREPARING_FOR_ABORT, id, p.getClass().getName(), context ); action = prepareForAbort (p, id, context); if (evt != null && p instanceof AbortParticipant) evt.addMessage ("prepareForAbort: " + p.getClass().getName()); } else { if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.PREPARING, id, p.getClass().getName(), context ); action = prepare (p, id, context); abort = (action & PREPARED) == ABORTED; retry = (action & RETRY) == RETRY; pause = (action & PAUSE) == PAUSE; if (evt != null) { evt.addMessage (" prepare: " + p.getClass().getName() + (abort ? " ABORTED" : "") + (retry ? " RETRY" : "") + (pause ? " PAUSE" : "") + ((action & READONLY) == READONLY ? " READONLY" : "") + ((action & NO_JOIN) == NO_JOIN ? " NO_JOIN" : "")); if (prof != null) prof.checkPoint ("prepare: " + p.getClass().getName()); } } if ((action & READONLY) == 0) { snapshot (id, context); } if ((action & NO_JOIN) == 0) { members.add (p); } if (p instanceof GroupSelector && ((action & PREPARED) == PREPARED || callSelectorOnAbort)) { String groupName = null; try { groupName = ((GroupSelector)p).select (id, context); } catch (Exception e) { if (evt != null) evt.addMessage (" selector: " + p.getClass().getName() + " " + e.getMessage()); else getLog().error (" selector: " + p.getClass().getName() + " " + e.getMessage()); } if (evt != null) { evt.addMessage (" selector: " + groupName); } if (groupName != null) { StringTokenizer st = new StringTokenizer (groupName, " ,"); List participants = new ArrayList(); while (st.hasMoreTokens ()) { String grp = st.nextToken(); addGroup (id, grp); participants.addAll (getParticipants (grp)); } while (iter.hasNext()) participants.add (iter.next()); iter = participants.iterator(); continue; } } if (pause) { if (context instanceof Pausable) { Pausable pausable = (Pausable) context; long t = pausable.getTimeout(); if (t == 0) t = pauseTimeout; TimerTask expirationMonitor = null; if (t > 0) expirationMonitor = new PausedMonitor (pausable); PausedTransaction pt = new PausedTransaction ( this, id, members, iter, abort, expirationMonitor, prof ); pausable.setPausedTransaction (pt); if (expirationMonitor != null) { synchronized (context) { if (!pt.isResumed()) { timer.schedule ( expirationMonitor, t ); } } } } else { throw new RuntimeException ("Unable to PAUSE transaction - Context is not Pausable"); } return PAUSE; } } return members.isEmpty() ? NO_JOIN : abort ? retry ? RETRY : ABORTED : PREPARED; } protected List<TransactionParticipant> getParticipants (String groupName) { List<TransactionParticipant> participants = groups.get (groupName); if (participants == null) participants = new ArrayList(); return participants; } protected List<TransactionParticipant> getParticipants (long id) { // Use a local copy of participant to avoid adding the // GROUP participant to the DEFAULT_GROUP List<TransactionParticipant> participantsChain = new ArrayList(); List<TransactionParticipant> participants = getParticipants (DEFAULT_GROUP); // Add DEFAULT_GROUP participants participantsChain.addAll(participants); String key = getKey(GROUPS, id); String grp; // now add participants of Group while ( (grp = (String) psp.inp (key)) != null) { participantsChain.addAll (getParticipants (grp)); } return participantsChain; } protected void initStatusListeners (Element config) throws ConfigurationException{ final Iterator iter = config.getChildren ("status-listener").iterator(); while (iter.hasNext()) { final Element e = (Element) iter.next(); final QFactory factory = getFactory(); final TransactionStatusListener listener = (TransactionStatusListener) factory.newInstance (e.getAttributeValue ("class")); factory.setConfiguration (listener, config); addListener(listener); } } protected void initParticipants (Element config) throws ConfigurationException { groups.put (DEFAULT_GROUP, initGroup (config)); for (Element e :(List<Element>)config.getChildren("group")) { String name = e.getAttributeValue ("name"); if (name == null) throw new ConfigurationException ("missing group name"); if (groups.containsKey(name)) { throw new ConfigurationException ( "Group '" + name + "' already defined" ); } groups.put (name, initGroup (e)); } } protected List<TransactionParticipant> initGroup (Element e) throws ConfigurationException { List group = new ArrayList (); for (Element el :(List<Element>)e.getChildren ("participant")) { group.add(createParticipant(el)); } return group; } public TransactionParticipant createParticipant (Element e) throws ConfigurationException { QFactory factory = getFactory(); TransactionParticipant participant = (TransactionParticipant) factory.newInstance (e.getAttributeValue ("class") ); factory.setLogger (participant, e); QFactory.invoke (participant, "setTransactionManager", this, TransactionManager.class); factory.setConfiguration (participant, e); return participant; } @Override public int getOutstandingTransactions() { if (isp instanceof LocalSpace) return ((LocalSpace)isp).size(queue); return -1; } protected String getKey (String prefix, long id) { StringBuilder sb = new StringBuilder (getName()); sb.append ('.'); sb.append (prefix); sb.append (Long.toString (id)); return sb.toString (); } protected long initCounter (String name, long defValue) { Long L = (Long) psp.rdp (name); if (L == null) { L = defValue; psp.out (name, L); } return L; } protected void commitOff (Space sp) { if (sp instanceof JDBMSpace) { ((JDBMSpace) sp).setAutoCommit (false); } } protected void commitOn (Space sp) { if (sp instanceof JDBMSpace) { JDBMSpace jsp = (JDBMSpace) sp; jsp.commit (); jsp.setAutoCommit (true); } } protected void syncTail () { synchronized (psp) { commitOff (psp); psp.inp (TAIL); psp.out (TAIL, tail); commitOn (psp); } } protected void initTailLock () { tailLock = TAILLOCK + "." + Integer.toString (this.hashCode()); sp.put (tailLock, TAILLOCK); } protected void checkTail () { Object lock = sp.in (tailLock); while (tailDone()) { // if (debug) { // getLog().debug ("tailDone " + tail); // } tail++; } syncTail (); sp.out (tailLock, lock); } protected boolean tailDone () { String stateKey = getKey (STATE, tail); if (DONE.equals (psp.rdp (stateKey))) { purge (tail); return true; } return false; } protected long nextId () { long h; synchronized (psp) { commitOff (psp); psp.in (HEAD); h = head; psp.out (HEAD, ++head); commitOn (psp); } return h; } protected void snapshot (long id, Serializable context) { snapshot (id, context, null); } protected void snapshot (long id, Serializable context, Integer status) { String contextKey = getKey (CONTEXT, id); synchronized (psp) { commitOff (psp); SpaceUtil.wipe(psp, contextKey); if (context != null) psp.out (contextKey, context); if (status != null) { String stateKey = getKey (STATE, id); psp.put (stateKey, status); } commitOn (psp); } } protected void setState (long id, Integer state) { String stateKey = getKey (STATE, id); synchronized (psp) { commitOff (psp); SpaceUtil.wipe(psp, stateKey); if (state!= null) psp.out (stateKey, state); commitOn (psp); } } protected void addGroup (long id, String groupName) { if (groupName != null) psp.out (getKey (GROUPS, id), groupName); } protected void purge (long id) { String stateKey = getKey (STATE, id); String contextKey = getKey (CONTEXT, id); String groupsKey = getKey (GROUPS, id); synchronized (psp) { commitOff (psp); SpaceUtil.wipe(psp, stateKey); SpaceUtil.wipe(psp, contextKey); SpaceUtil.wipe(psp, groupsKey); commitOn (psp); } } protected void recover () { if (doRecover) { if (tail < head) { getLog().info ("recover - tail=" +tail+", head="+head); } while (tail < head) { recover (0, tail++); } } else tail = head; syncTail (); } protected void recover (int session, long id) { LogEvent evt = getLog().createLogEvent ("recover"); Profiler prof = new Profiler(); evt.addMessage ("<id>" + id + "</id>"); try { String stateKey = getKey (STATE, id); String contextKey = getKey (CONTEXT, id); Integer state = (Integer) psp.rdp (stateKey); if (state == null) { evt.addMessage ("unknown stateKey " + stateKey); SpaceUtil.wipe (psp, contextKey); // just in case ... return; } Serializable context = (Serializable) psp.rdp (contextKey); if (context != null) evt.addMessage (context); if (DONE.equals (state)) { evt.addMessage ("<done/>"); } else if (COMMITTING.equals (state)) { commit (session, id, context, getParticipants (id), true, evt, prof); } else if (PREPARING.equals (state)) { abort (session, id, context, getParticipants (id), true, evt, prof); } purge (id); } finally { evt.addMessage (prof); Logger.log (evt); } } protected synchronized void checkRetryTask () { if (retryTask == null) { retryTask = new RetryTask(); new Thread(retryTask).start(); } } public static class PausedMonitor extends TimerTask { Pausable context; public PausedMonitor (Pausable context) { super(); this.context = context; } @Override public void run() { cancel(); context.getPausedTransaction().forceAbort(); context.resume(); } } public class RetryTask implements Runnable { @Override public void run() { Thread.currentThread().setName (getName()+"-retry-task"); while (running()) { for (Serializable context; (context = (Serializable)psp.rdp (RETRY_QUEUE)) != null;) { isp.out (queue, context, retryTimeout); psp.inp (RETRY_QUEUE); } ISOUtil.sleep(retryInterval); } } } @Override public void setDebug (boolean debug) { this.debug = debug; } @Override public boolean getDebug() { return debug; } @Override public int getActiveSessions() { return activeSessions.intValue(); } public int getRunningSessions() { return (int) (head - tail); } public static Serializable getSerializable() { return tlContext.get(); } public static Context getContext() { return (Context) tlContext.get(); } public static Long getId() { return tlId.get(); } private void notifyStatusListeners (int session, TransactionStatusEvent.State state, long id, String info, Serializable context) { TransactionStatusEvent e = new TransactionStatusEvent(session, state, id, info, context); synchronized (statusListeners) { for (TransactionStatusListener l : statusListeners) { l.update (e); } } } private void setThreadName (long id, String method, TransactionParticipant p) { Thread.currentThread().setName( String.format("%s:%d %s %s", getName(), id, method, p.getClass().getName()) ); } private void setThreadLocal (long id, Serializable context) { tlId.set(id); tlContext.set(context); } private void removeThreadLocal() { tlId.remove(); tlContext.remove(); } }
jpos/src/main/java/org/jpos/transaction/TransactionManager.java
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2015 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.transaction; import org.jdom.Element; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.*; import org.jpos.util.*; import java.io.Serializable; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import org.jpos.iso.ISOUtil; @SuppressWarnings("unchecked unused") public class TransactionManager extends QBeanSupport implements Runnable, TransactionConstants, TransactionManagerMBean { public static final String HEAD = "$HEAD"; public static final String TAIL = "$TAIL"; public static final String CONTEXT = "$CONTEXT."; public static final String STATE = "$STATE."; public static final String GROUPS = "$GROUPS."; public static final String TAILLOCK = "$TAILLOCK"; public static final String RETRY_QUEUE = "$RETRY_QUEUE"; public static final Integer PREPARING = 0; public static final Integer COMMITTING = 1; public static final Integer DONE = 2; public static final String DEFAULT_GROUP = ""; public static final long MAX_PARTICIPANTS = 1000; // loop prevention public static final long MAX_WAIT = 15000L; public static final long TIMER_PURGE_INTERVAL = 1000L; protected Map<String,List<TransactionParticipant>> groups; private static final ThreadLocal<Serializable> tlContext = new ThreadLocal<Serializable>(); private static final ThreadLocal<Long> tlId = new ThreadLocal<Long>(); Space sp; Space psp; Space isp; // input space String queue; String tailLock; List<Thread> threads; final List<TransactionStatusListener> statusListeners = new ArrayList<TransactionStatusListener>(); boolean hasStatusListeners; boolean debug; boolean profiler; boolean doRecover; boolean callSelectorOnAbort; int sessions; int maxSessions; int threshold; int maxActiveSessions; AtomicInteger activeSessions = new AtomicInteger(); long head, tail; long retryInterval = 5000L; long retryTimeout = 60000L; long pauseTimeout = 0L; Runnable retryTask = null; TPS tps; final Timer timer = DefaultTimer.getTimer(); @Override public void initService () throws ConfigurationException { queue = cfg.get ("queue", null); if (queue == null) throw new ConfigurationException ("queue property not specified"); sp = SpaceFactory.getSpace (cfg.get ("space")); isp = SpaceFactory.getSpace (cfg.get ("input-space", cfg.get ("space"))); psp = SpaceFactory.getSpace (cfg.get ("persistent-space", this.toString())); tail = initCounter (TAIL, cfg.getLong ("initial-tail", 1)); head = Math.max (initCounter (HEAD, tail), tail); initTailLock (); groups = new HashMap<String,List<TransactionParticipant>>(); initParticipants (getPersist()); initStatusListeners (getPersist()); } @Override public void startService () throws Exception { NameRegistrar.register(getName(), this); recover (); threads = Collections.synchronizedList(new ArrayList(maxSessions)); if (tps != null) tps.stop(); tps = new TPS (cfg.getBoolean ("auto-update-tps", true)); for (int i=0; i<sessions; i++) { new Thread(this).start(); } if (psp.rdp (RETRY_QUEUE) != null) checkRetryTask(); } @Override public void stopService () throws Exception { NameRegistrar.unregister (getName ()); Thread[] tt = threads.toArray(new Thread[threads.size()]); for (int i=0; i < tt.length; i++) { isp.out(queue, Boolean.FALSE, 60 * 1000); } for (Thread thread : tt) { try { thread.join (60*1000); threads.remove(thread); } catch (InterruptedException e) { getLog().warn ("Session " + thread.getName() +" does not respond - attempting to interrupt"); thread.interrupt(); } } tps.stop(); } public void queue (Serializable context) { isp.out(queue, context); } public void push (Serializable context) { isp.push(queue, context); } @SuppressWarnings("unused") public String getQueueName() { return queue; } public Space getSpace() { return sp; } public Space getInputSpace() { return isp; } public Space getPersistentSpace() { return psp; } @Override public void run () { long id = 0; int session = 0; // FIXME List<TransactionParticipant> members = null; Iterator<TransactionParticipant> iter = null; PausedTransaction pt; boolean abort = false; LogEvent evt = null; Profiler prof = null; long startTime = 0L; boolean paused; Thread thread = Thread.currentThread(); if (threads.size() < maxSessions) { threads.add(thread); session = threads.indexOf(thread); activeSessions.incrementAndGet(); } else { getLog().warn ("Max sessions reached, new session not created"); return; } getLog().info ("start " + thread); while (running()) { Serializable context = null; prof = null; paused = false; thread.setName (getName() + "-" + session + ":idle"); try { if (hasStatusListeners) notifyStatusListeners (session, TransactionStatusEvent.State.READY, id, "", null); Object obj = isp.in (queue, MAX_WAIT); if (obj == Boolean.FALSE) continue; // stopService ``hack'' if (obj == null) { if (session > sessions && getActiveSessions() > sessions) break; // we are an extra session, exit else continue; } if (session < sessions && // only initial sessions create extra sessions maxSessions > sessions && getActiveSessions() < maxSessions && getOutstandingTransactions() > threshold) { new Thread(this).start(); } if (!(obj instanceof Serializable)) { getLog().error ( "non serializable '" + obj.getClass().getName() + "' on queue '" + queue + "'" ); continue; } context = (Serializable) obj; if (obj instanceof Pausable) { Pausable pausable = (Pausable) obj; pt = pausable.getPausedTransaction(); if (pt != null) { pt.cancelExpirationMonitor(); id = pt.id(); members = pt.members(); iter = pt.iterator(); abort = pt.isAborting(); prof = pt.getProfiler(); if (prof != null) prof.reenable(); } } else pt = null; if (pt == null) { int running = getRunningSessions(); if (maxActiveSessions > 0 && running >= maxActiveSessions) { evt = getLog().createLogEvent ("warn", Thread.currentThread().getName() + ": emergency retry, running-sessions=" + running + ", max-active-sessions=" + maxActiveSessions ); evt.addMessage (obj); psp.out (RETRY_QUEUE, obj, retryTimeout); checkRetryTask(); continue; } abort = false; id = nextId (); members = new ArrayList (); iter = getParticipants (DEFAULT_GROUP).iterator(); } if (debug) { evt = getLog().createLogEvent ("debug", Thread.currentThread().getName() + ":" + Long.toString(id) + (pt != null ? " [resuming]" : "") ); if (prof == null) prof = new Profiler(); startTime = System.currentTimeMillis(); } snapshot (id, context, PREPARING); setThreadLocal(id, context); int action = prepare (session, id, context, members, iter, abort, evt, prof); removeThreadLocal(); switch (action) { case PAUSE: paused = true; if (id % TIMER_PURGE_INTERVAL == 0) timer.purge(); break; case PREPARED: setState (id, COMMITTING); setThreadLocal(id, context); commit (session, id, context, members, false, evt, prof); removeThreadLocal(); break; case ABORTED: setThreadLocal(id, context); abort (session, id, context, members, false, evt, prof); removeThreadLocal(); break; case RETRY: psp.out (RETRY_QUEUE, context); checkRetryTask(); break; case NO_JOIN: break; } if ((action & PAUSE) == 0) { snapshot (id, null, DONE); if (id == tail) { checkTail (); } tps.tick(); } } catch (Throwable t) { if (evt == null) getLog().fatal (t); // should never happen else evt.addMessage (t); } finally { removeThreadLocal(); if (hasStatusListeners) { notifyStatusListeners ( session, paused ? TransactionStatusEvent.State.PAUSED : TransactionStatusEvent.State.DONE, id, "", context); } if (getInTransit() > Math.max(maxActiveSessions, activeSessions.get()) * 100) { if (evt == null) evt = getLog().createLogEvent ("warn"); evt.addMessage("WARNING: IN-TRANSIT TOO HIGH"); } if (evt != null) { evt.addMessage ( String.format ("in-transit=%d, head=%d, tail=%d, outstanding=%d, active-sessions=%d/%d, %s, elapsed=%dms", getInTransit(), head, tail, getOutstandingTransactions(), getActiveSessions(), maxSessions, tps.toString(), System.currentTimeMillis() - startTime ) ); if (prof != null) evt.addMessage (prof); Logger.log (evt); evt = null; } } } threads.remove(thread); int currentActiveSessions = activeSessions.decrementAndGet(); getLog().info ("stop " + Thread.currentThread() + ", active sessions=" + currentActiveSessions); } @Override public long getTail () { return tail; } @Override public long getHead () { return head; } public long getInTransit () { return head - tail; } @Override public void setConfiguration (Configuration cfg) throws ConfigurationException { super.setConfiguration (cfg); debug = cfg.getBoolean ("debug"); profiler = cfg.getBoolean ("profiler", debug); if (profiler) debug = true; // profiler needs debug doRecover = cfg.getBoolean ("recover", true); retryInterval = cfg.getLong ("retry-interval", retryInterval); retryTimeout = cfg.getLong ("retry-timeout", retryTimeout); pauseTimeout = cfg.getLong ("pause-timeout", pauseTimeout); maxActiveSessions = cfg.getInt ("max-active-sessions", 0); sessions = cfg.getInt ("sessions", 1); threshold = cfg.getInt ("threshold", sessions / 2); maxSessions = cfg.getInt ("max-sessions", sessions); if (maxSessions < sessions) throw new ConfigurationException("max-sessions < sessions"); if (maxActiveSessions > 0) { if (maxActiveSessions < sessions) throw new ConfigurationException("max-active-sessions < sessions"); if (maxActiveSessions < maxSessions) throw new ConfigurationException("max-active-sessions < max-sessions"); } callSelectorOnAbort = cfg.getBoolean("call-selector-on-abort", true); } public void addListener (TransactionStatusListener l) { synchronized (statusListeners) { statusListeners.add (l); hasStatusListeners = true; } } public void removeListener (TransactionStatusListener l) { synchronized (statusListeners) { statusListeners.remove (l); hasStatusListeners = !statusListeners.isEmpty(); } } public TPS getTPS() { return tps; } @Override public String getTPSAsString() { return tps.toString(); } @Override public float getTPSAvg() { return tps.getAvg(); } @Override public int getTPSPeak() { return tps.getPeak(); } @Override public Date getTPSPeakWhen() { return new Date(tps.getPeakWhen()); } @Override public long getTPSElapsed() { return tps.getElapsed(); } @Override public void resetTPS() { tps.reset(); } protected void commit (int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) { for (TransactionParticipant p :members) { if (recover && p instanceof ContextRecovery) { context = ((ContextRecovery) p).recover (id, context, true); if (evt != null) evt.addMessage (" commit-recover: " + p.getClass().getName()); } if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.COMMITING, id, p.getClass().getName(), context ); commit (p, id, context); if (evt != null) { evt.addMessage (" commit: " + p.getClass().getName()); if (prof != null) prof.checkPoint (" commit: " + p.getClass().getName()); } } } protected void abort (int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) { for (TransactionParticipant p :members) { if (recover && p instanceof ContextRecovery) { context = ((ContextRecovery) p).recover (id, context, false); if (evt != null) evt.addMessage (" abort-recover: " + p.getClass().getName()); } if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.ABORTING, id, p.getClass().getName(), context ); abort (p, id, context); if (evt != null) { evt.addMessage (" abort: " + p.getClass().getName()); if (prof != null) prof.checkPoint (" abort: " + p.getClass().getName()); } } } protected int prepareForAbort (TransactionParticipant p, long id, Serializable context) { try { if (p instanceof AbortParticipant) { setThreadName(id, "prepareForAbort", p); return ((AbortParticipant)p).prepareForAbort (id, context); } } catch (Throwable t) { getLog().warn ("PREPARE-FOR-ABORT: " + Long.toString (id), t); } return ABORTED | NO_JOIN; } protected int prepare (TransactionParticipant p, long id, Serializable context) { try { setThreadName(id, "prepare", p); return p.prepare (id, context); } catch (Throwable t) { getLog().warn ("PREPARE: " + Long.toString (id), t); } return ABORTED; } protected void commit (TransactionParticipant p, long id, Serializable context) { try { setThreadName(id, "commit", p); p.commit (id, context); } catch (Throwable t) { getLog().warn ("COMMIT: " + Long.toString (id), t); } } protected void abort (TransactionParticipant p, long id, Serializable context) { try { setThreadName(id, "abort", p); p.abort (id, context); } catch (Throwable t) { getLog().warn ("ABORT: " + Long.toString (id), t); } } protected int prepare (int session, long id, Serializable context, List<TransactionParticipant> members, Iterator<TransactionParticipant> iter, boolean abort, LogEvent evt, Profiler prof) { boolean retry = false; boolean pause = false; for (int i=0; iter.hasNext (); i++) { int action; if (i > MAX_PARTICIPANTS) { getLog().warn ( "loop detected - transaction " +id + " aborted." ); return ABORTED; } TransactionParticipant p = iter.next(); if (abort) { if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.PREPARING_FOR_ABORT, id, p.getClass().getName(), context ); action = prepareForAbort (p, id, context); if (evt != null && p instanceof AbortParticipant) evt.addMessage ("prepareForAbort: " + p.getClass().getName()); } else { if (hasStatusListeners) notifyStatusListeners ( session, TransactionStatusEvent.State.PREPARING, id, p.getClass().getName(), context ); action = prepare (p, id, context); abort = (action & PREPARED) == ABORTED; retry = (action & RETRY) == RETRY; pause = (action & PAUSE) == PAUSE; if (evt != null) { evt.addMessage (" prepare: " + p.getClass().getName() + (abort ? " ABORTED" : "") + (retry ? " RETRY" : "") + (pause ? " PAUSE" : "") + ((action & READONLY) == READONLY ? " READONLY" : "") + ((action & NO_JOIN) == NO_JOIN ? " NO_JOIN" : "")); if (prof != null) prof.checkPoint ("prepare: " + p.getClass().getName()); } } if ((action & READONLY) == 0) { snapshot (id, context); } if ((action & NO_JOIN) == 0) { members.add (p); } if (p instanceof GroupSelector && ((action & PREPARED) == PREPARED || callSelectorOnAbort)) { String groupName = null; try { groupName = ((GroupSelector)p).select (id, context); } catch (Exception e) { if (evt != null) evt.addMessage (" selector: " + p.getClass().getName() + " " + e.getMessage()); else getLog().error (" selector: " + p.getClass().getName() + " " + e.getMessage()); } if (evt != null) { evt.addMessage (" selector: " + groupName); } if (groupName != null) { StringTokenizer st = new StringTokenizer (groupName, " ,"); List participants = new ArrayList(); while (st.hasMoreTokens ()) { String grp = st.nextToken(); addGroup (id, grp); participants.addAll (getParticipants (grp)); } while (iter.hasNext()) participants.add (iter.next()); iter = participants.iterator(); continue; } } if (pause) { if (context instanceof Pausable) { Pausable pausable = (Pausable) context; long t = pausable.getTimeout(); if (t == 0) t = pauseTimeout; TimerTask expirationMonitor = null; if (t > 0) expirationMonitor = new PausedMonitor (pausable); PausedTransaction pt = new PausedTransaction ( this, id, members, iter, abort, expirationMonitor, prof ); pausable.setPausedTransaction (pt); if (expirationMonitor != null) { synchronized (context) { if (!pt.isResumed()) { timer.schedule ( expirationMonitor, t ); } } } } else { throw new RuntimeException ("Unable to PAUSE transaction - Context is not Pausable"); } return PAUSE; } } return members.isEmpty() ? NO_JOIN : abort ? retry ? RETRY : ABORTED : PREPARED; } protected List<TransactionParticipant> getParticipants (String groupName) { List<TransactionParticipant> participants = groups.get (groupName); if (participants == null) participants = new ArrayList(); return participants; } protected List<TransactionParticipant> getParticipants (long id) { // Use a local copy of participant to avoid adding the // GROUP participant to the DEFAULT_GROUP List<TransactionParticipant> participantsChain = new ArrayList(); List<TransactionParticipant> participants = getParticipants (DEFAULT_GROUP); // Add DEFAULT_GROUP participants participantsChain.addAll(participants); String key = getKey(GROUPS, id); String grp; // now add participants of Group while ( (grp = (String) psp.inp (key)) != null) { participantsChain.addAll (getParticipants (grp)); } return participantsChain; } protected void initStatusListeners (Element config) throws ConfigurationException{ final Iterator iter = config.getChildren ("status-listener").iterator(); while (iter.hasNext()) { final Element e = (Element) iter.next(); final QFactory factory = getFactory(); final TransactionStatusListener listener = (TransactionStatusListener) factory.newInstance (e.getAttributeValue ("class")); factory.setConfiguration (listener, config); addListener(listener); } } protected void initParticipants (Element config) throws ConfigurationException { groups.put (DEFAULT_GROUP, initGroup (config)); for (Element e :(List<Element>)config.getChildren("group")) { String name = e.getAttributeValue ("name"); if (name == null) throw new ConfigurationException ("missing group name"); if (groups.containsKey(name)) { throw new ConfigurationException ( "Group '" + name + "' already defined" ); } groups.put (name, initGroup (e)); } } protected List<TransactionParticipant> initGroup (Element e) throws ConfigurationException { List group = new ArrayList (); for (Element el :(List<Element>)e.getChildren ("participant")) { group.add(createParticipant(el)); } return group; } public TransactionParticipant createParticipant (Element e) throws ConfigurationException { QFactory factory = getFactory(); TransactionParticipant participant = (TransactionParticipant) factory.newInstance (e.getAttributeValue ("class") ); factory.setLogger (participant, e); QFactory.invoke (participant, "setTransactionManager", this, TransactionManager.class); factory.setConfiguration (participant, e); return participant; } @Override public int getOutstandingTransactions() { if (isp instanceof LocalSpace) return ((LocalSpace)isp).size(queue); return -1; } protected String getKey (String prefix, long id) { StringBuilder sb = new StringBuilder (getName()); sb.append ('.'); sb.append (prefix); sb.append (Long.toString (id)); return sb.toString (); } protected long initCounter (String name, long defValue) { Long L = (Long) psp.rdp (name); if (L == null) { L = defValue; psp.out (name, L); } return L; } protected void commitOff (Space sp) { if (sp instanceof JDBMSpace) { ((JDBMSpace) sp).setAutoCommit (false); } } protected void commitOn (Space sp) { if (sp instanceof JDBMSpace) { JDBMSpace jsp = (JDBMSpace) sp; jsp.commit (); jsp.setAutoCommit (true); } } protected void syncTail () { synchronized (psp) { commitOff (psp); psp.inp (TAIL); psp.out (TAIL, tail); commitOn (psp); } } protected void initTailLock () { tailLock = TAILLOCK + "." + Integer.toString (this.hashCode()); sp.put (tailLock, TAILLOCK); } protected void checkTail () { Object lock = sp.in (tailLock); while (tailDone()) { // if (debug) { // getLog().debug ("tailDone " + tail); // } tail++; } syncTail (); sp.out (tailLock, lock); } protected boolean tailDone () { String stateKey = getKey (STATE, tail); if (DONE.equals (psp.rdp (stateKey))) { purge (tail); return true; } return false; } protected long nextId () { long h; synchronized (psp) { commitOff (psp); psp.in (HEAD); h = head; psp.out (HEAD, ++head); commitOn (psp); } return h; } protected void snapshot (long id, Serializable context) { snapshot (id, context, null); } protected void snapshot (long id, Serializable context, Integer status) { String contextKey = getKey (CONTEXT, id); synchronized (psp) { commitOff (psp); SpaceUtil.wipe(psp, contextKey); if (context != null) psp.out (contextKey, context); if (status != null) { String stateKey = getKey (STATE, id); psp.put (stateKey, status); } commitOn (psp); } } protected void setState (long id, Integer state) { String stateKey = getKey (STATE, id); synchronized (psp) { commitOff (psp); SpaceUtil.wipe(psp, stateKey); if (state!= null) psp.out (stateKey, state); commitOn (psp); } } protected void addGroup (long id, String groupName) { if (groupName != null) psp.out (getKey (GROUPS, id), groupName); } protected void purge (long id) { String stateKey = getKey (STATE, id); String contextKey = getKey (CONTEXT, id); String groupsKey = getKey (GROUPS, id); synchronized (psp) { commitOff (psp); SpaceUtil.wipe(psp, stateKey); SpaceUtil.wipe(psp, contextKey); SpaceUtil.wipe(psp, groupsKey); commitOn (psp); } } protected void recover () { if (doRecover) { if (tail < head) { getLog().info ("recover - tail=" +tail+", head="+head); } while (tail < head) { recover (0, tail++); } } else tail = head; syncTail (); } protected void recover (int session, long id) { LogEvent evt = getLog().createLogEvent ("recover"); Profiler prof = new Profiler(); evt.addMessage ("<id>" + id + "</id>"); try { String stateKey = getKey (STATE, id); String contextKey = getKey (CONTEXT, id); Integer state = (Integer) psp.rdp (stateKey); if (state == null) { evt.addMessage ("unknown stateKey " + stateKey); SpaceUtil.wipe (psp, contextKey); // just in case ... return; } Serializable context = (Serializable) psp.rdp (contextKey); if (context != null) evt.addMessage (context); if (DONE.equals (state)) { evt.addMessage ("<done/>"); } else if (COMMITTING.equals (state)) { commit (session, id, context, getParticipants (id), true, evt, prof); } else if (PREPARING.equals (state)) { abort (session, id, context, getParticipants (id), true, evt, prof); } purge (id); } finally { evt.addMessage (prof); Logger.log (evt); } } protected synchronized void checkRetryTask () { if (retryTask == null) { retryTask = new RetryTask(); new Thread(retryTask).start(); } } public static class PausedMonitor extends TimerTask { Pausable context; public PausedMonitor (Pausable context) { super(); this.context = context; } @Override public void run() { cancel(); context.getPausedTransaction().forceAbort(); context.resume(); } } public class RetryTask implements Runnable { @Override public void run() { Thread.currentThread().setName (getName()+"-retry-task"); while (running()) { for (Serializable context; (context = (Serializable)psp.rdp (RETRY_QUEUE)) != null;) { isp.out (queue, context, retryTimeout); psp.inp (RETRY_QUEUE); } ISOUtil.sleep(retryInterval); } } } @Override public void setDebug (boolean debug) { this.debug = debug; } @Override public boolean getDebug() { return debug; } @Override public int getActiveSessions() { return activeSessions.intValue(); } public int getRunningSessions() { return (int) (head - tail); } public static Serializable getSerializable() { return tlContext.get(); } public static Context getContext() { return (Context) tlContext.get(); } public static Long getId() { return tlId.get(); } private void notifyStatusListeners (int session, TransactionStatusEvent.State state, long id, String info, Serializable context) { TransactionStatusEvent e = new TransactionStatusEvent(session, state, id, info, context); synchronized (statusListeners) { for (TransactionStatusListener l : statusListeners) { l.update (e); } } } private void setThreadName (long id, String method, TransactionParticipant p) { Thread.currentThread().setName( String.format("%s:%d %s %s", getName(), id, method, p.getClass().getName()) ); } private void setThreadLocal (long id, Serializable context) { tlId.set(id); tlContext.set(context); } private void removeThreadLocal() { tlId.remove(); tlContext.remove(); } }
prof.checkPoint on resume
jpos/src/main/java/org/jpos/transaction/TransactionManager.java
prof.checkPoint on resume
<ide><path>pos/src/main/java/org/jpos/transaction/TransactionManager.java <ide> ); <ide> if (prof == null) <ide> prof = new Profiler(); <add> else <add> prof.checkPoint("resume"); <ide> startTime = System.currentTimeMillis(); <ide> } <ide> snapshot (id, context, PREPARING);
Java
agpl-3.0
error: pathspec 'arbil/src/main/java/nl/mpi/arbil/ui/ArbilIconCellRenderer.java' did not match any file(s) known to git
4c4825dbce3fb98388ce65357cc830e84ddeae61
1
TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil,TheLanguageArchive/Arbil
package nl.mpi.arbil.ui; import java.awt.BorderLayout; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; /** * Document : ArbilIconCellRenderer * Panel that wraps the table cell renderer allowing an icon to be added at either end of the label * Created on : Aug 8, 2012, 11:53:10 AM * Author : Peter Withers */ public class ArbilIconCellRenderer extends JPanel { // the this class overrides any events that might cause issues in the parent table: // validate, invalidate, revalidate, repaint, and firePropertyChange methods are no-ops and isOpaque is overriden final private JLabel cellRendererComponent; public ArbilIconCellRenderer(JLabel cellRendererComponent) { this.cellRendererComponent = cellRendererComponent; this.setLayout(new BorderLayout()); this.add(cellRendererComponent, BorderLayout.CENTER); this.add(rightIconLabel, BorderLayout.LINE_END); } public void setIcons(Icon leftIcon, Icon rightIcon) { cellRendererComponent.setIcon(leftIcon); cellRendererComponent.setHorizontalTextPosition(SwingConstants.LEADING); rightIconLabel.setIcon(rightIcon); rightIconLabel.setHorizontalTextPosition(SwingConstants.TRAILING); rightIconLabel.setBackground(cellRendererComponent.getBackground()); } JLabel rightIconLabel = new JLabel() { @Override public void validate() { } @Override public void invalidate() { } @Override public void revalidate() { } @Override public void repaint() { } @Override public void repaint(long tm) { } @Override public void repaint(int x, int y, int width, int height) { } @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) { } @Override public void firePropertyChange(String propertyName, char oldValue, char newValue) { } @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { } @Override public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { } @Override public void firePropertyChange(String propertyName, short oldValue, short newValue) { } @Override public void firePropertyChange(String propertyName, long oldValue, long newValue) { } @Override public void firePropertyChange(String propertyName, float oldValue, float newValue) { } @Override public void firePropertyChange(String propertyName, double oldValue, double newValue) { } @Override public boolean isOpaque() { return cellRendererComponent.isOpaque(); } }; // @Override // public void validate() { // } @Override public void invalidate() { } @Override public void revalidate() { } @Override public void repaint() { } @Override public void repaint(long tm) { } @Override public void repaint(int x, int y, int width, int height) { } @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) { } @Override public void firePropertyChange(String propertyName, char oldValue, char newValue) { } @Override protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { } @Override public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { } @Override public void firePropertyChange(String propertyName, short oldValue, short newValue) { } @Override public void firePropertyChange(String propertyName, long oldValue, long newValue) { } @Override public void firePropertyChange(String propertyName, float oldValue, float newValue) { } @Override public void firePropertyChange(String propertyName, double oldValue, double newValue) { } @Override public boolean isOpaque() { return cellRendererComponent.isOpaque(); } }
arbil/src/main/java/nl/mpi/arbil/ui/ArbilIconCellRenderer.java
Created a table cell renderer that conforms to the EDT requirements and displays icons at either end of the label. Addressed reasons for the table cell renderer not being rendered correctly due to EDT issues. #2229
arbil/src/main/java/nl/mpi/arbil/ui/ArbilIconCellRenderer.java
Created a table cell renderer that conforms to the EDT requirements and displays icons at either end of the label. Addressed reasons for the table cell renderer not being rendered correctly due to EDT issues. #2229
<ide><path>rbil/src/main/java/nl/mpi/arbil/ui/ArbilIconCellRenderer.java <add>package nl.mpi.arbil.ui; <add> <add>import java.awt.BorderLayout; <add>import javax.swing.Icon; <add>import javax.swing.JLabel; <add>import javax.swing.JPanel; <add>import javax.swing.SwingConstants; <add> <add>/** <add> * Document : ArbilIconCellRenderer <add> * Panel that wraps the table cell renderer allowing an icon to be added at either end of the label <add> * Created on : Aug 8, 2012, 11:53:10 AM <add> * Author : Peter Withers <add> */ <add>public class ArbilIconCellRenderer extends JPanel { <add> <add> // the this class overrides any events that might cause issues in the parent table: <add> // validate, invalidate, revalidate, repaint, and firePropertyChange methods are no-ops and isOpaque is overriden <add> final private JLabel cellRendererComponent; <add> <add> public ArbilIconCellRenderer(JLabel cellRendererComponent) { <add> this.cellRendererComponent = cellRendererComponent; <add> this.setLayout(new BorderLayout()); <add> this.add(cellRendererComponent, BorderLayout.CENTER); <add> this.add(rightIconLabel, BorderLayout.LINE_END); <add> } <add> <add> public void setIcons(Icon leftIcon, Icon rightIcon) { <add> cellRendererComponent.setIcon(leftIcon); <add> cellRendererComponent.setHorizontalTextPosition(SwingConstants.LEADING); <add> rightIconLabel.setIcon(rightIcon); <add> rightIconLabel.setHorizontalTextPosition(SwingConstants.TRAILING); <add> rightIconLabel.setBackground(cellRendererComponent.getBackground()); <add> } <add> JLabel rightIconLabel = new JLabel() { <add> <add> @Override <add> public void validate() { <add> } <add> <add> @Override <add> public void invalidate() { <add> } <add> <add> @Override <add> public void revalidate() { <add> } <add> <add> @Override <add> public void repaint() { <add> } <add> <add> @Override <add> public void repaint(long tm) { <add> } <add> <add> @Override <add> public void repaint(int x, int y, int width, int height) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, int oldValue, int newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, char oldValue, char newValue) { <add> } <add> <add> @Override <add> protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, short oldValue, short newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, long oldValue, long newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, float oldValue, float newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, double oldValue, double newValue) { <add> } <add> <add> @Override <add> public boolean isOpaque() { <add> return cellRendererComponent.isOpaque(); <add> } <add> }; <add> <add>// @Override <add>// public void validate() { <add>// } <add> <add> @Override <add> public void invalidate() { <add> } <add> <add> @Override <add> public void revalidate() { <add> } <add> <add> @Override <add> public void repaint() { <add> } <add> <add> @Override <add> public void repaint(long tm) { <add> } <add> <add> @Override <add> public void repaint(int x, int y, int width, int height) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, int oldValue, int newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, char oldValue, char newValue) { <add> } <add> <add> @Override <add> protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, short oldValue, short newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, long oldValue, long newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, float oldValue, float newValue) { <add> } <add> <add> @Override <add> public void firePropertyChange(String propertyName, double oldValue, double newValue) { <add> } <add> <add> @Override <add> public boolean isOpaque() { <add> return cellRendererComponent.isOpaque(); <add> } <add>}
Java
apache-2.0
11d6950730a16c3e3dde17dacb177de2e2798f2d
0
cdegroot/river,pfirmstone/river-internet,pfirmstone/JGDMS,pfirmstone/JGDMS,cdegroot/river,pfirmstone/river-internet,pfirmstone/JGDMS,pfirmstone/river-internet,pfirmstone/JGDMS
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jini.loader.pref; import com.sun.jini.loader.pref.internal.PreferredResources; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FilePermission; import java.net.HttpURLConnection; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.SocketPermission; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.security.AccessControlContext; import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.ProtectionDomain; import java.security.Policy; import java.security.Principal; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Set; import java.util.HashSet; import net.jini.loader.ClassAnnotation; import net.jini.loader.DownloadPermission; /** * A class loader that supports preferred classes. * * <p>A preferred class is a class that is to be loaded by a class * loader without the loader delegating to its parent class loader * first. Resources may also be preferred. * * <p>Like {@link java.net.URLClassLoader}, * <code>PreferredClassLoader</code> loads classes and resources from * a search path of URLs. If a URL in the path ends with a * <code>'/'</code>, it is assumed to refer to a directory; otherwise, * the URL is assumed to refer to a JAR file. * * <p>The location of the first URL in the path can contain a * <i>preferred list</i> for the entire path. A preferred list * declares names of certain classes and other resources throughout * the path as being <i>preferred</i> or not. When a * <code>PreferredClassLoader</code> is asked to load a class or * resource that is preferred (according to the preferred list) and * the class or resource exists in the loader's path of URLs, the * loader will not delegate first to its parent class loader as it * otherwise would do; instead, it will attempt to load the class or * resource from its own path of URLs only. * * <p>The preferred list for a path of URLs, if one exists, is located * relative to the first URL in the path. If the first URL refers to * a JAR file, then the preferred list is the contents of the file * named <code>"META-INF/PREFERRED.LIST"</code> within that JAR file. * If the first URL refers to a directory, then the preferred list is * the contents of the file at the location * <code>"META-INF/PREFERRED.LIST"</code> relative to that directory * URL. If there is no preferred list at the required location, then * no classes or resources are preferred for the path of URLs. A * preferred list at any other location (such as relative to one of * the other URLs in the path) is ignored. * * <p>Note that a class or resource is only considered to be preferred * if the preferred list declares the name of the class or resource as * being preferred and the class or resource actually exists in the * path of URLs. * * <h3>Preferred List Syntax</h3> * * A preferred list is a UTF-8 encoded text file, with lines separated * by CR&nbsp;LF, LF, or CR (not followed by an LF). Multiple * whitespace characters in a line are equivalent to a single * whitespace character, and whitespace characters at the beginning or * end of a line are ignored. If the first non-whitespace character * of a line is <code>'#'</code>, the line is a comment and is * equivalent to a blank line. * * <p>The first line of a preferred list must contain a version * number in the following format: * * <pre> * PreferredResources-Version: 1.<i>x</i> * </pre> * * This specification defines only version 1.0, but * <code>PreferredClassLoader</code> will parse any version * 1.<i>x</i>, <i>x</i>>=0 with the format and semantics specified * here. * * <p>After the version number line, a preferred list comprises an * optional default preferred entry followed by zero or more named * preferred entries. A preferred list must contain either a default * preferred entry or at least one named preferred entry. Blank lines * are allowed before and after preferred entries, as well as between * the lines of a named preferred entry. * * <p>A default preferred entry is a single line in the following * format: * * <pre> * Preferred: <i>preferred-setting</i> * </pre> * * where <i>preferred-setting</i> is a non-empty sequence of * characters. If <i>preferred-setting</i> equals <code>"true"</code> * (case insensitive), then resource names not matched by any of the * named preferred entries are by default preferred; otherwise, * resource names not matched by any of the named preferred entries * are by default not preferred. If there is no default preferred * entry, then resource names are by default not preferred. * * <p>A named preferred entry is two lines in the following format: * * <pre> * Name: <i>name-expression</i> * Preferred: <i>preferred-setting</i> * </pre> * * where <i>name-expression</i> and <i>preferred-setting</i> are * non-empty sequences of characters. If <i>preferred-setting</i> * equals <code>"true"</code> (case insensitive), then resource names * that are matched by <i>name-expression</i> (and not any more * specific named preferred entries) are preferred; otherwise, * resource names that are matched by <i>name-expression</i> (and not * any more specific named preferred entries) are not preferred. * * <p>If <i>name-expression</i> ends with <code>".class"</code>, it * matches a class whose binary name is <i>name-expression</i> without * the <code>".class"</code> suffix and with each <code>'/'</code> * character replaced with a <code>'.'</code>. It also matches any * class whose binary name starts with that same value followed by a * <code>'$'</code>; this rule is intended to match nested classes * that have an enclosing class of that name, so that the preferred * settings of a class and all of its nested classes are the same by * default. It is possible, but strongly discouraged, to override the * preferred setting of a nested class with a named preferred entry * that explicitly matches the nested class's binary name. * * <p><i>name-expression</i> may match arbitrary resource names as * well as class names, with path elements separated by * <code>'/'</code> characters. * * <p>If <i>name-expression</i> ends with <code>"/"</code> or * <code>"/*"</code>, then the entry is a directory wildcard entry * that matches all resources (including classes) in the named * directory. If <i>name-expression</i> ends with <code>"/-"</code>, * then the entry is a namespace wildcard entry that matches all * resources (including classes) in the named directory and all of its * subdirectories. * * <p>When more than one named preferred entry matches a class or * resource name, then the most specific entry takes precedence. A * non-wildcard entry is more specific than a wildcard entry. A * directory wildcard entry is more specific than a namespace wildcard * entry. A namespace wildcard entry with more path elements is more * specific than a namespace wildcard entry with fewer path elements. * Given two non-wildcard entries, the entry with the longer * <i>name-expression</i> is more specific (this rule is only * significant when matching a class). The order of named preferred * entries is insignificant. * * <h3>Example Preferred List</h3> * * <p>Following is an example preferred list: * * <pre> * PreferredResources-Version: 1.0 * Preferred: false * * Name: com/foo/FooBar.class * Preferred: true * * Name: com/foo/* * Preferred: false * * Name: com/foo/- * Preferred: true * * Name: image-files/* * Preferred: mumble * </pre> * * <p>The class <code>com.foo.FooBar</code> is preferred, as well as * any nested classes that have it as an enclosing class. All other * classes in the <code>com.foo</code> package are not preferred * because of the directory wildcard entry. Classes in subpackages of * <code>com.foo</code> are preferred because of the namespace * wildcard entry. Resources in the directory <code>"com/foo/"</code> * are not preferred, and resources in subdirectories of * <code>"com/foo/"</code> are preferred. Resources in the directory * <code>"image-files/"</code> are not preferred because preferred * settings other than <code>"true"</code> are interpreted as false. * Classes that are in a package named <code>com.bar</code> are not * preferred because of the default preferred entry. * * @author Sun Microsystems, Inc. * @since 2.0 **/ public class PreferredClassLoader extends URLClassLoader implements ClassAnnotation { /** * well known name of resource that contains the preferred list in * a path of URLs **/ private static final String PREF_NAME = "META-INF/PREFERRED.LIST"; /** first URL in the path, or null if none */ private final URL firstURL; /** class annotation string for classes defined by this loader */ private final String exportAnnotation; /** permissions required to access loader through public API */ private final PermissionCollection permissions; /** security context for loading classes and resources */ private final AccessControlContext acc; /** permission required to download code? */ private final boolean requireDlPerm; /** URLStreamHandler to use when creating new "jar:" URLs */ private final URLStreamHandler jarHandler; /** PreferredResources for this loader (null if no preferred list) */ private PreferredResources preferredResources; /** true if preferredResources has been successfully initialized */ private boolean preferredResourcesInitialized = false; private static final Permission downloadPermission = new DownloadPermission(); /** * Creates a new <code>PreferredClassLoader</code> that loads * classes and resources from the specified path of URLs and * delegates to the specified parent class loader. * * <p>If <code>exportAnnotation</code> is not <code>null</code>, * then it will be used as the return value of the loader's {@link * #getClassAnnotation getClassAnnotation} method. If * <code>exportAnnotation</code> is <code>null</code>, the * loader's <code>getClassAnnotation</code> method will return a * space-separated list of the URLs in the specified path. The * <code>exportAnnotation</code> parameter can be used to specify * so-called "export" URLs, from which other parties should load * classes defined by the loader and which are different from the * "import" URLs that the classes are actually loaded from. * * <p>If <code>requireDlPerm</code> is <code>true</code>, the * loader's {@link #getPermissions getPermissions} method will * require that the {@link CodeSource} of any class defined by the * loader is granted {@link DownloadPermission}. * * @param urls the path of URLs to load classes and resources from * * @param parent the parent class loader for delegation * * @param exportAnnotation the export class annotation string to * use for classes defined by this loader, or <code>null</code> * * @param requireDlPerm if <code>true</code>, the loader will only * define classes with a {@link CodeSource} that is granted {@link * DownloadPermission} * * @throws SecurityException if there is a security manager and an * invocation of its {@link SecurityManager#checkCreateClassLoader * checkCreateClassLoader} method fails **/ public PreferredClassLoader(URL[] urls, ClassLoader parent, String exportAnnotation, boolean requireDlPerm) { this(urls, parent, exportAnnotation, requireDlPerm, null); } /** * Creates a new <code>PreferredClassLoader</code> that loads * classes and resources from the specified path of URLs, * delegates to the specified parent class loader, and uses the * specified {@link URLStreamHandlerFactory} when creating new URL * objects. This constructor passes <code>factory</code> to the * superclass constructor that has a * <code>URLStreamHandlerFactory</code> parameter. * * <p>If <code>exportAnnotation</code> is not <code>null</code>, * then it will be used as the return value of the loader's {@link * #getClassAnnotation getClassAnnotation} method. If * <code>exportAnnotation</code> is <code>null</code>, the * loader's <code>getClassAnnotation</code> method will return a * space-separated list of the URLs in the specified path. The * <code>exportAnnotation</code> parameter can be used to specify * so-called "export" URLs, from which other parties should load * classes defined by the loader and which are different from the * "import" URLs that the classes are actually loaded from. * * <p>If <code>requireDlPerm</code> is <code>true</code>, the * loader's {@link #getPermissions getPermissions} method will * require that the {@link CodeSource} of any class defined by the * loader is granted {@link DownloadPermission}. * * @param urls the path of URLs to load classes and resources from * * @param parent the parent class loader for delegation * * @param exportAnnotation the export class annotation string to * use for classes defined by this loader, or <code>null</code> * * @param requireDlPerm if <code>true</code>, the loader will only * define classes with a {@link CodeSource} that is granted {@link * DownloadPermission} * * @param factory the <code>URLStreamHandlerFactory</code> to use * when creating new URL objects, or <code>null</code> * * @throws SecurityException if there is a security manager and an * invocation of its {@link SecurityManager#checkCreateClassLoader * checkCreateClassLoader} method fails * * @since 2.1 **/ public PreferredClassLoader(URL[] urls, ClassLoader parent, String exportAnnotation, boolean requireDlPerm, URLStreamHandlerFactory factory) { super(urls, parent, factory); firstURL = (urls.length > 0 ? urls[0] : null); if (exportAnnotation != null) { this.exportAnnotation = exportAnnotation; } else { /* * Caching the value of class annotation string here * assumes that the protected method addURL() is never * called on this class loader. */ this.exportAnnotation = urlsToPath(urls); } this.requireDlPerm = requireDlPerm; if (factory != null) { jarHandler = factory.createURLStreamHandler("jar"); } else { jarHandler = null; } acc = AccessController.getContext(); /* * Precompute the permissions required to access the loader. */ permissions = new Permissions(); addPermissionsForURLs(urls, permissions, false); } /** * Convert an array of URL objects into a corresponding string * containing a space-separated list of URLs. * * Note that if the array has zero elements, the return value is * null, not the empty string. */ static String urlsToPath(URL[] urls) { if (urls.length == 0) { return null; } else if (urls.length == 1) { return urls[0].toExternalForm(); } else { StringBuffer path = new StringBuffer(urls[0].toExternalForm()); for (int i = 1; i < urls.length; i++) { path.append(' '); path.append(urls[i].toExternalForm()); } return path.toString(); } } /** * Creates a new instance of <code>PreferredClassLoader</code> * that loads classes and resources from the specified path of * URLs and delegates to the specified parent class loader. * * <p>The <code>exportAnnotation</code> and * <code>requireDlPerm</code> parameters have the same semantics * as they do for the constructors. * * <p>The {@link #loadClass loadClass} method of the returned * <code>PreferredClassLoader</code> will, if there is a security * manager, invoke its {@link SecurityManager#checkPackageAccess * checkPackageAccess} method with the package name of the class * to load before attempting to load the class; this could result * in a <code>SecurityException</code> being thrown from * <code>loadClass</code>. * * @param urls the path of URLs to load classes and resources from * * @param parent the parent class loader for delegation * * @param exportAnnotation the export class annotation string to * use for classes defined by this loader, or <code>null</code> * * @param requireDlPerm if <code>true</code>, the loader will only * define classes with a {@link CodeSource} that is granted {@link * DownloadPermission} * * @return the new <code>PreferredClassLoader</code> instance * * @throws SecurityException if the current security context does * not have the permissions necessary to connect to all of the * URLs in <code>urls</code> **/ public static PreferredClassLoader newInstance(final URL[] urls, final ClassLoader parent, final String exportAnnotation, final boolean requireDlPerm) { /* ensure caller has permission to access all urls */ PermissionCollection perms = new Permissions(); addPermissionsForURLs(urls, perms, false); checkPermissions(perms); AccessControlContext acc = getLoaderAccessControlContext(urls); /* Use privileged status to return a new class loader instance */ return (PreferredClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new PreferredFactoryClassLoader(urls, parent, exportAnnotation, requireDlPerm); } }, acc); } /** * If a preferred list exists relative to the first URL of this * loader's path, sets this loader's PreferredResources according * to that preferred list. If no preferred list exists relative * to the first URL, leaves this loader's PreferredResources null. * * Throws IOException if an I/O exception occurs from which the * existence of a preferred list relative to the first URL cannot * be definitely determined. * * This method must only be invoked while synchronized on this * PreferredClassLoader, and it must not be invoked again after it * has completed successfully. **/ private void initializePreferredResources() throws IOException { assert Thread.holdsLock(this); assert preferredResources == null; if (firstURL != null) { InputStream prefIn = getPreferredInputStream(firstURL); if (prefIn != null) { try { preferredResources = new PreferredResources(prefIn); } finally { try { prefIn.close(); } catch (IOException e) { } } } } } /** * Returns an InputStream from which the preferred list relative * to the specified URL can be read, or null if the there is * definitely no preferred list relative to the URL. If the URL's * path ends with "/", then the preferred list is sought at the * location "META-INF/PREFERRED.LIST" relative to the URL; * otherwise, the URL is assumed to refer to a JAR file, and the * preferred list is sought within that JAR file, as the entry * named "META-INF/PREFERRED.LIST". * * Throws IOException if an I/O exception occurs from which the * existence of a preferred list relative to the specified URL * cannot be definitely determined. **/ private InputStream getPreferredInputStream(URL firstURL) throws IOException { URL prefListURL = null; try { URL baseURL; // base URL to load PREF_NAME relative to if (firstURL.getFile().endsWith("/")) { // REMIND: track 4915051 baseURL = firstURL; } else { /* * First try to get a definite answer about the existence of a * PREFERRED.LIST that doesn't by-pass a JAR file cache, if * any. If that fails we determine if the JAR file exists by * attempting to access it directly, without using a "jar:" URL, * because the "jar:" URL handler can mask the distinction * between definite lack of existence and less definitive * errors. Unfortunately, this direct access circumvents the JAR * file caching done by the "jar:" handler, so it ends up * causing duplicate requests of the JAR file on first use when * our first attempt fails. (For HTTP-protocol URLs, the initial * request will use HEAD instead of GET.) * * After determining that the JAR file exists, attempt to * retrieve the preferred list using a "jar:" URL, like * URLClassLoader uses to load resources from a JAR file. */ if (jarExists(firstURL)) { baseURL = getBaseJarURL(firstURL); } else { return null; } } prefListURL = new URL(baseURL, PREF_NAME); URLConnection preferredConnection = getPreferredConnection(prefListURL, false); if (preferredConnection != null) { return preferredConnection.getInputStream(); } else { return null; } } catch (IOException e) { /* * Assume that any IOException thrown while attempting to * access a "file:" URL and any FileNotFoundException * implies that there is definitely no preferred list * relative to the specified URL. */ if (firstURL.getProtocol().equals("file") || e instanceof FileNotFoundException) { return null; } else { throw e; } } } /* cache existence of jar files referenced by codebase urls */ private static final Set<String> existSet = new HashSet<String>(11); /* * Determine if a jar file in a given URL location exists. If the * jar exists record the jar file's URL in a cache of URL strings. * * Recording the existence of the jar prevents the need to * re-determine the jar's existence on subsequent downloads of the * jar in potentially different preferred class loaders. */ private boolean jarExists(URL firstURL) throws IOException { boolean exists; synchronized (existSet) { // The comment says in a cache of URL strings, URL in Set, bad. exists = existSet.contains(firstURL.toString()); } if (!exists) { /* * first try to get a definite answer of the existence of a JAR * file, if no IOException is thrown when obtaining it through the * "jar:" protocol we can safely assume the JAR file is locally * available upon the attempt (elsewhere) to obtain the preferred * list */ URL baseURL = getBaseJarURL(firstURL); try { ((JarURLConnection) baseURL.openConnection()).getManifest(); exists = true; } catch (IOException e) { // we still have no definite answer on whether the JAR file // and therefore the PREFERRED.LIST exists } catch (NullPointerException e){ // Sun Bug ID: 6536522 // NullPointerException is thrown instead of MalformedURLException // Case is the same as above, we have no definite answer on // whether the JAR file and therefore the PREFERRED.LIST exists. System.err.println("NPE thrown while trying to open connection :" + baseURL); e.printStackTrace(System.err); } if (!exists) { exists = (getPreferredConnection(firstURL, true) != null); } if (exists) { synchronized (existSet) { existSet.add(firstURL.toString()); } } } return exists; } /** * Returns a "jar:" URL for the root directory of the JAR file at * the specified URL. If this loader was constructed with a * URLStreamHandlerFactory, then the returned URL will have a * URLStreamHandler that was created by the factory. **/ private URL getBaseJarURL(final URL url) throws MalformedURLException { if (jarHandler == null) { return new URL("jar", "", -1, url + "!/"); } else { try { return (URL) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws MalformedURLException { return new URL("jar", "", -1, url + "!/", jarHandler); } }); } catch (PrivilegedActionException e) { throw (MalformedURLException) e.getCause(); } } } /** * Obtain a url connection from which an input stream that * contains a preferred list can be obtained. * * For http urls, attempts to use http response codes to * determine if a preferred list exists or is definitely not * found. Simply attempts to open a connection to other kinds * of non-file urls. If the attempt fails, an IOException is * thrown to user code. * * Returns null if the preferred list definitely does not * exist. Rethrows all indefinite IOExceptions generated * while trying to open a connection to the preferred list. * * The caller has the option to close the connection after the * resource has been detected (as will happen when probing for a * PREFERRED.LIST). */ private URLConnection getPreferredConnection(URL url, boolean closeAfter) throws IOException { if (url.getProtocol().equals("file")) { return url.openConnection(); } URLConnection closeConn = null; URLConnection conn = null; try { closeConn = url.openConnection(); conn = closeConn; /* check status of http urls */ if (conn instanceof HttpURLConnection) { HttpURLConnection hconn = (HttpURLConnection) conn; if (closeAfter) { hconn.setRequestMethod("HEAD"); } int responseCode = hconn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: /* the preferred list exists */ break; /* 404, not found appears to be handled by * HttpURLConnection (FileNotFoundException is * thrown), but to be safe do the right thing here as * well. */ case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_GONE: /* list definitely does not exist */ conn = null; break; default: /* indefinite response code */ throw new IOException("Indefinite http response for " + "preferred list request:" + hconn.getResponseMessage()); } } } finally { if (closeAfter && (closeConn != null)) { /* clean up after... */ try { closeConn.getInputStream().close(); } catch (IOException e) { } catch (NullPointerException e){ // Sun Bug ID: 6536522 } } } return conn; } /** * Returns <code>true</code> if a class or resource with the * specified name is preferred for this class loader, and * <code>false</code> if a class or resource with the specified * name is not preferred for this loader. * * <p>If <code>isClass</code> is <code>true</code>, then * <code>name</code> is interpreted as the binary name of a class; * otherwise, <code>name</code> is interpreted as the full path of * a resource. * * <p>This method only returns <code>true</code> if a class or * resource with the specified name exists in the this loader's * path of URLs and the name is preferred in the preferred list. * This method returns <code>false</code> if the name is not * preferred in the preferred list or if the name is preferred * with the default preferred entry or a wildcard preferred entry * and the class or resource does not exist in the path of URLs. * * @param name the name of the class or resource * * @param isClass <code>true</code> if <code>name</code> is a * binary class name, and <code>false</code> if <code>name</code> * is the full path of a resource * * @return <code>true</code> if a class or resource named * <code>name</code> is preferred for this loader, and * <code>false</code> if a class or resource named * <code>name</code> is not preferred for this loader * * @throws IOException if the preferred list cannot definitely be * determined to exist or not exist, or if the preferred list * contains a syntax error, or if the name is preferred with the * default preferred entry or a wildcard preferred entry and the * class or resource cannot definitely be determined to exist or * not exist in the path of URLs, or if the name is preferred with * a non-wildcard entry and the class or resource does not exist * or cannot definitely be determined to exist in the path of URLs **/ protected boolean isPreferredResource(final String name, final boolean isClass) throws IOException { try { return ((Boolean) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException { boolean b = isPreferredResource0(name, isClass); return Boolean.valueOf(b); } }, acc)).booleanValue(); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } } /* * Perform the work to determine if a resource name is preferred. */ private synchronized boolean isPreferredResource0(String name, boolean isClass) throws IOException { if (!preferredResourcesInitialized) { initializePreferredResources(); preferredResourcesInitialized = true; } if (preferredResources == null) { return false; // no preferred list: nothing is preferred } String resourceName = name; if (isClass) { /* class name -> resource name */ resourceName = name.replace('.', '/') + ".class"; } /* * Determine if the class name is preferred. Making this * distinction is somewhat tricky because we need to cache the * preferred state (i.e. if the name is preferred and its * resource exists) in a way that avoids duplication of * preferred information - state information is stored back * into the preferred resources object for this class loader * and not held in a separate preferred settings cache. */ boolean resourcePreferred = false; int state = preferredResources.getNameState(resourceName, isClass); switch (state) { case PreferredResources.NAME_NOT_PREFERRED: resourcePreferred = false; break; case PreferredResources.NAME_PREFERRED_RESOURCE_EXISTS: resourcePreferred = true; break; case PreferredResources.NAME_NO_PREFERENCE: Boolean wildcardPref = preferredResources.getWildcardPreference(resourceName); if (wildcardPref == null) { /* preferredDefault counts as a wild card */ wildcardPref = preferredResources.getDefaultPreference(); } if (wildcardPref.booleanValue()) { resourcePreferred = findResourceUpdateState(name, resourceName); } break; case PreferredResources.NAME_PREFERRED: resourcePreferred = findResourceUpdateState(name, resourceName); if (!resourcePreferred) { throw new IOException("no resource found for " + "complete preferred name"); } break; default: throw new Error("unknown preference state"); } return resourcePreferred; } /* * Determine if a resource for a given preferred name exists. If * the resource exists record its new state in the * preferredResources object. * * This method must only be invoked while synchronized on this * PreferredClassLoader. */ private boolean findResourceUpdateState(String name, String resourceName) throws IOException { assert Thread.holdsLock(this); boolean resourcePreferred = false; if (findResource(resourceName) != null) { /* the resource is know to exist */ preferredResources.setNameState(resourceName, PreferredResources.NAME_PREFERRED_RESOURCE_EXISTS); resourcePreferred = true; } return resourcePreferred; } /** * Loads a class with the specified name. * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>This method first invokes {@link #findLoadedClass * findLoadedClass} with <code>name</code>; if * <code>findLoadedClass</code> returns a non-<code>null</code> * <code>Class</code>, then this method returns that * <code>Class</code>. * * <p>Otherwise, this method invokes {@link #isPreferredResource * isPreferredResource} with <code>name</code> as the first * argument and <code>true</code> as the second argument: * * <ul> * * <li>If <code>isPreferredResource</code> throws an * <code>IOException</code>, then this method throws a * <code>ClassNotFoundException</code> containing the * <code>IOException</code> as its cause. * * <li>If <code>isPreferredResource</code> returns * <code>true</code>, then this method invokes {@link #findClass * findClass} with <code>name</code>. If <code>findClass</code> * throws an exception, then this method throws that exception. * Otherwise, this method returns the <code>Class</code> returned * by <code>findClass</code>, and if <code>resolve</code> is * <code>true</code>, {@link #resolveClass resolveClass} is * invoked with the <code>Class</code> before returning. * * <li>If <code>isPreferredResource</code> returns * <code>false</code>, then this method invokes the superclass * implementation of {@link ClassLoader#loadClass(String,boolean) * loadClass} with <code>name</code> and <code>resolve</code> and * returns the result. If the superclass's <code>loadClass</code> * throws an exception, then this method throws that exception. * * </ul> * * @param name the binary name of the class to load * * @param resolve if <code>true</code>, then {@link #resolveClass * resolveClass} will be invoked with the loaded class before * returning * * @return the loaded class * * @throws ClassNotFoundException if the class could not be found **/ protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { boolean preferred; try { preferred = isPreferredResource(name, true); } catch (IOException e) { throw new ClassNotFoundException(name + " (could not determine preferred setting; " + (firstURL != null ? "first URL: \"" + firstURL + "\"" : "no URLs") + ")", e); } if (preferred) { c = findClass(name); if (resolve) { resolveClass(c); } return c; } else { return super.loadClass(name, resolve); } } return c; } /** * Gets a resource with the specified name. * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>This method invokes {@link #isPreferredResource * isPreferredResource} with <code>name</code> as the first * argument and <code>false</code> as the second argument: * * <ul> * * <li>If <code>isPreferredResource</code> throws an * <code>IOException</code>, then this method returns * <code>null</code>. * * <li>If <code>isPreferredResource</code> returns * <code>true</code>, then this method invokes {@link * #findResource findResource} with <code>name</code> and returns * the result. * * <li>If <code>isPreferredResource</code> returns * <code>false</code>, then this method invokes the superclass * implementation of {@link ClassLoader#getResource getResource} * with <code>name</code> and returns the result. * * </ul> * * @param name the name of the resource to get * * @return a <code>URL</code> for the resource, or * <code>null</code> if the resource could not be found **/ public URL getResource(String name) { try { return (isPreferredResource(name, false) ? findResource(name) : super.getResource(name)); } catch (IOException e) { } return null; } /* * Work around 4841786: wrap ClassLoader.definePackage so that if * it throws an IllegalArgumentException because an ancestor * loader "defined" the named package since the last time that * ClassLoader.getPackage was invoked, then just return the * result of invoking ClassLoader.getPackage again here. * Fortunately, URLClassLoader.defineClass ignores the value * returned by this method. */ protected Package definePackage(String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase) { try { return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); } catch (IllegalArgumentException e) { return getPackage(name); } } protected Class<?> findClass(final String name) throws ClassNotFoundException { /* TODO: Override and create our own CodeSource * implementation that contains permissions.perm * After we retrieve the manifest, class bytes and * certificates, create the CodeSource we call * defineClass(String name, byte[]b, int off, int len, CodeSource cs) * * This will be utilised by a class that overrides * BasicProxyPreparer.getPermissions() * to retrieve the advisory permissions. */ return super.findClass(name); } /** * {@inheritDoc} * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>If this <code>PreferredClassLoader</code> was constructed * with a non-<code>null</code> export class annotation string, * then this method returns that string. Otherwise, this method * returns a space-separated list of this loader's path of URLs. **/ public String getClassAnnotation() { return exportAnnotation; } /** * Check that the current access control context has all of the * permissions necessary to load classes from this loader. */ void checkPermissions() { checkPermissions(permissions); } /** * Check that the current access control context has all of the * given permissions. */ private static void checkPermissions(PermissionCollection perms) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // should never be null? Enumeration en = perms.elements(); while (en.hasMoreElements()) { sm.checkPermission((Permission) en.nextElement()); } } } /** * Returns the static permissions to be automatically granted to * classes loaded from the specified {@link CodeSource} and * defined by this class loader. * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>If there is a security manager and this * <code>PreferredClassLoader</code> was constructed to enforce * {@link DownloadPermission}, then this method checks that the * current security policy grants the specified * <code>CodeSource</code> the permission * <code>DownloadPermission("permit")</code>; if that check fails, * then this method throws a <code>SecurityException</code>. * * <p>Then this method invokes the superclass implementation of * {@link #getPermissions getPermissions} and returns the result. * * @param codeSource the <code>CodeSource</code> to return the * permissions to be granted to * * @return the permissions to be granted to the * <code>CodeSource</code> * * @throws SecurityException if there is a security manager, this * <code>PreferredClassLoader</code> was constructed to enforce * <code>DownloadPermission</code>, and the current security * policy does not grant the specified <code>CodeSource</code> the * permission <code>DownloadPermission("permit")</code> **/ protected PermissionCollection getPermissions(CodeSource codeSource) { if (requireDlPerm) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { ProtectionDomain pd = new ProtectionDomain(codeSource, null, this, null); if (!pd.implies(downloadPermission)) { throw new SecurityException( "CodeSource not permitted to define class: " + codeSource); } } } return super.getPermissions(codeSource); } /** * Returns a string representation of this class loader. **/ public String toString() { return super.toString() + "[\"" + exportAnnotation + "\"]"; } /** * Return the access control context that a loader for the given * codebase URL path should execute with. */ static AccessControlContext getLoaderAccessControlContext(URL[] urls) { /* * The approach used here is taken from the similar method * getAccessControlContext() in the sun.applet.AppletPanel class. */ // begin with permissions granted to all code in current policy PermissionCollection perms = (PermissionCollection) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { CodeSource codesource = new CodeSource(null, (Certificate[]) null); Policy p = java.security.Policy.getPolicy(); if (p != null) { return p.getPermissions(codesource); } else { return new Permissions(); } } }); // createClassLoader permission needed to create loader in context perms.add(new RuntimePermission("createClassLoader")); // add permissions to read any "java.*" property perms.add(new java.util.PropertyPermission("java.*","read")); // add permissions required to load from codebase URL path addPermissionsForURLs(urls, perms, true); /* * Create an AccessControlContext that consists of a single * protection domain with only the permissions calculated above. * Comment added 7th May 2010 by Peter Firmstone: * This did call the pre java 1.4 constructor which causes the * ProtectionDomain to not consult the Policy, this * had the effect of not allowing Dynamic Permission changes to be * effected by the Policy. It doesn't affect the existing * DynamicPolicy implementation as it returns the Permissions * allowing the ProtectionDomain domain combiner to combine * cached permissions with those from the Policy. * ProtectionDomain(CodeSource, PermissionCollection) * By utilising this earlier constructor it also prevents * RevokeableDynamicPolicy, hence the constructor change. */ ProtectionDomain pd = new ProtectionDomain( new CodeSource((urls.length > 0 ? urls[0] : null), (Certificate[]) null), perms, null, null); return new AccessControlContext(new ProtectionDomain[] { pd }); } /** * Adds to the specified permission collection the permissions * necessary to load classes from a loader with the specified URL * path; if "forLoader" is true, also adds URL-specific * permissions necessary for the security context that such a * loader operates within, such as permissions necessary for * granting automatic permissions to classes defined by the * loader. A given permission is only added to the collection if * it is not already implied by the collection. **/ static void addPermissionsForURLs(URL[] urls, PermissionCollection perms, boolean forLoader) { for (int i = 0; i < urls.length; i++) { URL url = urls[i]; try { URLConnection urlConnection = url.openConnection(); Permission p = urlConnection.getPermission(); if (p != null) { if (p instanceof FilePermission) { /* * If the codebase is a file, the permission required * to actually read classes from the codebase URL is * the permission to read all files beneath the last * directory in the file path, either because JAR * files can refer to other JAR files in the same * directory, or because permission to read a * directory is not implied by permission to read the * contents of a directory, which all that might be * granted. */ String path = p.getName(); int endIndex = path.lastIndexOf(File.separatorChar); if (endIndex != -1) { path = path.substring(0, endIndex+1); if (path.endsWith(File.separator)) { path += "-"; } Permission p2 = new FilePermission(path, "read"); if (!perms.implies(p2)) { perms.add(p2); } } else { /* * No directory separator: use permission to * read the file. */ if (!perms.implies(p)) { perms.add(p); } } } else { if (!perms.implies(p)) { perms.add(p); } /* * If the purpose of these permissions is to grant * them to an instance of a URLClassLoader subclass, * we must add permission to connect to and accept * from the host of non-"file:" URLs, otherwise the * getPermissions() method of URLClassLoader will * throw a security exception. */ if (forLoader) { // get URL with meaningful host component URL hostURL = url; for (URLConnection conn = urlConnection; conn instanceof JarURLConnection;) { hostURL = ((JarURLConnection) conn).getJarFileURL(); conn = hostURL.openConnection(); } String host = hostURL.getHost(); if (host != null && p.implies(new SocketPermission(host, "resolve"))) { Permission p2 = new SocketPermission(host, "connect,accept"); if (!perms.implies(p2)) { perms.add(p2); } } } } } } catch (IOException e) { /* * This shouldn't happen, although it is declared to be * thrown by openConnection() and getPermission(). If it * does, don't bother granting or requiring any permissions * for this URL. */ } catch (NullPointerException e){ // Sun Bug ID: 6536522 } } } }
src/net/jini/loader/pref/PreferredClassLoader.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 net.jini.loader.pref; import com.sun.jini.loader.pref.internal.PreferredResources; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FilePermission; import java.net.HttpURLConnection; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.SocketPermission; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.security.AccessControlContext; import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.ProtectionDomain; import java.security.Policy; import java.security.Principal; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Set; import java.util.HashSet; import net.jini.loader.ClassAnnotation; import net.jini.loader.DownloadPermission; /** * A class loader that supports preferred classes. * * <p>A preferred class is a class that is to be loaded by a class * loader without the loader delegating to its parent class loader * first. Resources may also be preferred. * * <p>Like {@link java.net.URLClassLoader}, * <code>PreferredClassLoader</code> loads classes and resources from * a search path of URLs. If a URL in the path ends with a * <code>'/'</code>, it is assumed to refer to a directory; otherwise, * the URL is assumed to refer to a JAR file. * * <p>The location of the first URL in the path can contain a * <i>preferred list</i> for the entire path. A preferred list * declares names of certain classes and other resources throughout * the path as being <i>preferred</i> or not. When a * <code>PreferredClassLoader</code> is asked to load a class or * resource that is preferred (according to the preferred list) and * the class or resource exists in the loader's path of URLs, the * loader will not delegate first to its parent class loader as it * otherwise would do; instead, it will attempt to load the class or * resource from its own path of URLs only. * * <p>The preferred list for a path of URLs, if one exists, is located * relative to the first URL in the path. If the first URL refers to * a JAR file, then the preferred list is the contents of the file * named <code>"META-INF/PREFERRED.LIST"</code> within that JAR file. * If the first URL refers to a directory, then the preferred list is * the contents of the file at the location * <code>"META-INF/PREFERRED.LIST"</code> relative to that directory * URL. If there is no preferred list at the required location, then * no classes or resources are preferred for the path of URLs. A * preferred list at any other location (such as relative to one of * the other URLs in the path) is ignored. * * <p>Note that a class or resource is only considered to be preferred * if the preferred list declares the name of the class or resource as * being preferred and the class or resource actually exists in the * path of URLs. * * <h3>Preferred List Syntax</h3> * * A preferred list is a UTF-8 encoded text file, with lines separated * by CR&nbsp;LF, LF, or CR (not followed by an LF). Multiple * whitespace characters in a line are equivalent to a single * whitespace character, and whitespace characters at the beginning or * end of a line are ignored. If the first non-whitespace character * of a line is <code>'#'</code>, the line is a comment and is * equivalent to a blank line. * * <p>The first line of a preferred list must contain a version * number in the following format: * * <pre> * PreferredResources-Version: 1.<i>x</i> * </pre> * * This specification defines only version 1.0, but * <code>PreferredClassLoader</code> will parse any version * 1.<i>x</i>, <i>x</i>>=0 with the format and semantics specified * here. * * <p>After the version number line, a preferred list comprises an * optional default preferred entry followed by zero or more named * preferred entries. A preferred list must contain either a default * preferred entry or at least one named preferred entry. Blank lines * are allowed before and after preferred entries, as well as between * the lines of a named preferred entry. * * <p>A default preferred entry is a single line in the following * format: * * <pre> * Preferred: <i>preferred-setting</i> * </pre> * * where <i>preferred-setting</i> is a non-empty sequence of * characters. If <i>preferred-setting</i> equals <code>"true"</code> * (case insensitive), then resource names not matched by any of the * named preferred entries are by default preferred; otherwise, * resource names not matched by any of the named preferred entries * are by default not preferred. If there is no default preferred * entry, then resource names are by default not preferred. * * <p>A named preferred entry is two lines in the following format: * * <pre> * Name: <i>name-expression</i> * Preferred: <i>preferred-setting</i> * </pre> * * where <i>name-expression</i> and <i>preferred-setting</i> are * non-empty sequences of characters. If <i>preferred-setting</i> * equals <code>"true"</code> (case insensitive), then resource names * that are matched by <i>name-expression</i> (and not any more * specific named preferred entries) are preferred; otherwise, * resource names that are matched by <i>name-expression</i> (and not * any more specific named preferred entries) are not preferred. * * <p>If <i>name-expression</i> ends with <code>".class"</code>, it * matches a class whose binary name is <i>name-expression</i> without * the <code>".class"</code> suffix and with each <code>'/'</code> * character replaced with a <code>'.'</code>. It also matches any * class whose binary name starts with that same value followed by a * <code>'$'</code>; this rule is intended to match nested classes * that have an enclosing class of that name, so that the preferred * settings of a class and all of its nested classes are the same by * default. It is possible, but strongly discouraged, to override the * preferred setting of a nested class with a named preferred entry * that explicitly matches the nested class's binary name. * * <p><i>name-expression</i> may match arbitrary resource names as * well as class names, with path elements separated by * <code>'/'</code> characters. * * <p>If <i>name-expression</i> ends with <code>"/"</code> or * <code>"/*"</code>, then the entry is a directory wildcard entry * that matches all resources (including classes) in the named * directory. If <i>name-expression</i> ends with <code>"/-"</code>, * then the entry is a namespace wildcard entry that matches all * resources (including classes) in the named directory and all of its * subdirectories. * * <p>When more than one named preferred entry matches a class or * resource name, then the most specific entry takes precedence. A * non-wildcard entry is more specific than a wildcard entry. A * directory wildcard entry is more specific than a namespace wildcard * entry. A namespace wildcard entry with more path elements is more * specific than a namespace wildcard entry with fewer path elements. * Given two non-wildcard entries, the entry with the longer * <i>name-expression</i> is more specific (this rule is only * significant when matching a class). The order of named preferred * entries is insignificant. * * <h3>Example Preferred List</h3> * * <p>Following is an example preferred list: * * <pre> * PreferredResources-Version: 1.0 * Preferred: false * * Name: com/foo/FooBar.class * Preferred: true * * Name: com/foo/* * Preferred: false * * Name: com/foo/- * Preferred: true * * Name: image-files/* * Preferred: mumble * </pre> * * <p>The class <code>com.foo.FooBar</code> is preferred, as well as * any nested classes that have it as an enclosing class. All other * classes in the <code>com.foo</code> package are not preferred * because of the directory wildcard entry. Classes in subpackages of * <code>com.foo</code> are preferred because of the namespace * wildcard entry. Resources in the directory <code>"com/foo/"</code> * are not preferred, and resources in subdirectories of * <code>"com/foo/"</code> are preferred. Resources in the directory * <code>"image-files/"</code> are not preferred because preferred * settings other than <code>"true"</code> are interpreted as false. * Classes that are in a package named <code>com.bar</code> are not * preferred because of the default preferred entry. * * @author Sun Microsystems, Inc. * @since 2.0 **/ public class PreferredClassLoader extends URLClassLoader implements ClassAnnotation { /** * well known name of resource that contains the preferred list in * a path of URLs **/ private static final String PREF_NAME = "META-INF/PREFERRED.LIST"; /** first URL in the path, or null if none */ private final URL firstURL; /** class annotation string for classes defined by this loader */ private final String exportAnnotation; /** permissions required to access loader through public API */ private final PermissionCollection permissions; /** security context for loading classes and resources */ private final AccessControlContext acc; /** permission required to download code? */ private final boolean requireDlPerm; /** URLStreamHandler to use when creating new "jar:" URLs */ private final URLStreamHandler jarHandler; /** PreferredResources for this loader (null if no preferred list) */ private PreferredResources preferredResources; /** true if preferredResources has been successfully initialized */ private boolean preferredResourcesInitialized = false; private static final Permission downloadPermission = new DownloadPermission(); /** * Creates a new <code>PreferredClassLoader</code> that loads * classes and resources from the specified path of URLs and * delegates to the specified parent class loader. * * <p>If <code>exportAnnotation</code> is not <code>null</code>, * then it will be used as the return value of the loader's {@link * #getClassAnnotation getClassAnnotation} method. If * <code>exportAnnotation</code> is <code>null</code>, the * loader's <code>getClassAnnotation</code> method will return a * space-separated list of the URLs in the specified path. The * <code>exportAnnotation</code> parameter can be used to specify * so-called "export" URLs, from which other parties should load * classes defined by the loader and which are different from the * "import" URLs that the classes are actually loaded from. * * <p>If <code>requireDlPerm</code> is <code>true</code>, the * loader's {@link #getPermissions getPermissions} method will * require that the {@link CodeSource} of any class defined by the * loader is granted {@link DownloadPermission}. * * @param urls the path of URLs to load classes and resources from * * @param parent the parent class loader for delegation * * @param exportAnnotation the export class annotation string to * use for classes defined by this loader, or <code>null</code> * * @param requireDlPerm if <code>true</code>, the loader will only * define classes with a {@link CodeSource} that is granted {@link * DownloadPermission} * * @throws SecurityException if there is a security manager and an * invocation of its {@link SecurityManager#checkCreateClassLoader * checkCreateClassLoader} method fails **/ public PreferredClassLoader(URL[] urls, ClassLoader parent, String exportAnnotation, boolean requireDlPerm) { this(urls, parent, exportAnnotation, requireDlPerm, null); } /** * Creates a new <code>PreferredClassLoader</code> that loads * classes and resources from the specified path of URLs, * delegates to the specified parent class loader, and uses the * specified {@link URLStreamHandlerFactory} when creating new URL * objects. This constructor passes <code>factory</code> to the * superclass constructor that has a * <code>URLStreamHandlerFactory</code> parameter. * * <p>If <code>exportAnnotation</code> is not <code>null</code>, * then it will be used as the return value of the loader's {@link * #getClassAnnotation getClassAnnotation} method. If * <code>exportAnnotation</code> is <code>null</code>, the * loader's <code>getClassAnnotation</code> method will return a * space-separated list of the URLs in the specified path. The * <code>exportAnnotation</code> parameter can be used to specify * so-called "export" URLs, from which other parties should load * classes defined by the loader and which are different from the * "import" URLs that the classes are actually loaded from. * * <p>If <code>requireDlPerm</code> is <code>true</code>, the * loader's {@link #getPermissions getPermissions} method will * require that the {@link CodeSource} of any class defined by the * loader is granted {@link DownloadPermission}. * * @param urls the path of URLs to load classes and resources from * * @param parent the parent class loader for delegation * * @param exportAnnotation the export class annotation string to * use for classes defined by this loader, or <code>null</code> * * @param requireDlPerm if <code>true</code>, the loader will only * define classes with a {@link CodeSource} that is granted {@link * DownloadPermission} * * @param factory the <code>URLStreamHandlerFactory</code> to use * when creating new URL objects, or <code>null</code> * * @throws SecurityException if there is a security manager and an * invocation of its {@link SecurityManager#checkCreateClassLoader * checkCreateClassLoader} method fails * * @since 2.1 **/ public PreferredClassLoader(URL[] urls, ClassLoader parent, String exportAnnotation, boolean requireDlPerm, URLStreamHandlerFactory factory) { super(urls, parent, factory); firstURL = (urls.length > 0 ? urls[0] : null); if (exportAnnotation != null) { this.exportAnnotation = exportAnnotation; } else { /* * Caching the value of class annotation string here * assumes that the protected method addURL() is never * called on this class loader. */ this.exportAnnotation = urlsToPath(urls); } this.requireDlPerm = requireDlPerm; if (factory != null) { jarHandler = factory.createURLStreamHandler("jar"); } else { jarHandler = null; } acc = AccessController.getContext(); /* * Precompute the permissions required to access the loader. */ permissions = new Permissions(); addPermissionsForURLs(urls, permissions, false); } /** * Convert an array of URL objects into a corresponding string * containing a space-separated list of URLs. * * Note that if the array has zero elements, the return value is * null, not the empty string. */ static String urlsToPath(URL[] urls) { if (urls.length == 0) { return null; } else if (urls.length == 1) { return urls[0].toExternalForm(); } else { StringBuffer path = new StringBuffer(urls[0].toExternalForm()); for (int i = 1; i < urls.length; i++) { path.append(' '); path.append(urls[i].toExternalForm()); } return path.toString(); } } /** * Creates a new instance of <code>PreferredClassLoader</code> * that loads classes and resources from the specified path of * URLs and delegates to the specified parent class loader. * * <p>The <code>exportAnnotation</code> and * <code>requireDlPerm</code> parameters have the same semantics * as they do for the constructors. * * <p>The {@link #loadClass loadClass} method of the returned * <code>PreferredClassLoader</code> will, if there is a security * manager, invoke its {@link SecurityManager#checkPackageAccess * checkPackageAccess} method with the package name of the class * to load before attempting to load the class; this could result * in a <code>SecurityException</code> being thrown from * <code>loadClass</code>. * * @param urls the path of URLs to load classes and resources from * * @param parent the parent class loader for delegation * * @param exportAnnotation the export class annotation string to * use for classes defined by this loader, or <code>null</code> * * @param requireDlPerm if <code>true</code>, the loader will only * define classes with a {@link CodeSource} that is granted {@link * DownloadPermission} * * @return the new <code>PreferredClassLoader</code> instance * * @throws SecurityException if the current security context does * not have the permissions necessary to connect to all of the * URLs in <code>urls</code> **/ public static PreferredClassLoader newInstance(final URL[] urls, final ClassLoader parent, final String exportAnnotation, final boolean requireDlPerm) { /* ensure caller has permission to access all urls */ PermissionCollection perms = new Permissions(); addPermissionsForURLs(urls, perms, false); checkPermissions(perms); AccessControlContext acc = getLoaderAccessControlContext(urls); /* Use privileged status to return a new class loader instance */ return (PreferredClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return new PreferredFactoryClassLoader(urls, parent, exportAnnotation, requireDlPerm); } }, acc); } /** * If a preferred list exists relative to the first URL of this * loader's path, sets this loader's PreferredResources according * to that preferred list. If no preferred list exists relative * to the first URL, leaves this loader's PreferredResources null. * * Throws IOException if an I/O exception occurs from which the * existence of a preferred list relative to the first URL cannot * be definitely determined. * * This method must only be invoked while synchronized on this * PreferredClassLoader, and it must not be invoked again after it * has completed successfully. **/ private void initializePreferredResources() throws IOException { assert Thread.holdsLock(this); assert preferredResources == null; if (firstURL != null) { InputStream prefIn = getPreferredInputStream(firstURL); if (prefIn != null) { try { preferredResources = new PreferredResources(prefIn); } finally { try { prefIn.close(); } catch (IOException e) { } } } } } /** * Returns an InputStream from which the preferred list relative * to the specified URL can be read, or null if the there is * definitely no preferred list relative to the URL. If the URL's * path ends with "/", then the preferred list is sought at the * location "META-INF/PREFERRED.LIST" relative to the URL; * otherwise, the URL is assumed to refer to a JAR file, and the * preferred list is sought within that JAR file, as the entry * named "META-INF/PREFERRED.LIST". * * Throws IOException if an I/O exception occurs from which the * existence of a preferred list relative to the specified URL * cannot be definitely determined. **/ private InputStream getPreferredInputStream(URL firstURL) throws IOException { URL prefListURL = null; try { URL baseURL; // base URL to load PREF_NAME relative to if (firstURL.getFile().endsWith("/")) { // REMIND: track 4915051 baseURL = firstURL; } else { /* * First try to get a definite answer about the existence of a * PREFERRED.LIST that doesn't by-pass a JAR file cache, if * any. If that fails we determine if the JAR file exists by * attempting to access it directly, without using a "jar:" URL, * because the "jar:" URL handler can mask the distinction * between definite lack of existence and less definitive * errors. Unfortunately, this direct access circumvents the JAR * file caching done by the "jar:" handler, so it ends up * causing duplicate requests of the JAR file on first use when * our first attempt fails. (For HTTP-protocol URLs, the initial * request will use HEAD instead of GET.) * * After determining that the JAR file exists, attempt to * retrieve the preferred list using a "jar:" URL, like * URLClassLoader uses to load resources from a JAR file. */ if (jarExists(firstURL)) { baseURL = getBaseJarURL(firstURL); } else { return null; } } prefListURL = new URL(baseURL, PREF_NAME); URLConnection preferredConnection = getPreferredConnection(prefListURL, false); if (preferredConnection != null) { return preferredConnection.getInputStream(); } else { return null; } } catch (IOException e) { /* * Assume that any IOException thrown while attempting to * access a "file:" URL and any FileNotFoundException * implies that there is definitely no preferred list * relative to the specified URL. */ if (firstURL.getProtocol().equals("file") || e instanceof FileNotFoundException) { return null; } else { throw e; } } } /* cache existence of jar files referenced by codebase urls */ private static final Set<String> existSet = new HashSet<String>(11); /* * Determine if a jar file in a given URL location exists. If the * jar exists record the jar file's URL in a cache of URL strings. * * Recording the existence of the jar prevents the need to * re-determine the jar's existence on subsequent downloads of the * jar in potentially different preferred class loaders. */ private boolean jarExists(URL firstURL) throws IOException { boolean exists; synchronized (existSet) { // The comment says in a cache of URL strings, URL in Set, bad. exists = existSet.contains(firstURL.toString()); } if (!exists) { /* * first try to get a definite answer of the existence of a JAR * file, if no IOException is thrown when obtaining it through the * "jar:" protocol we can safely assume the JAR file is locally * available upon the attempt (elsewhere) to obtain the preferred * list */ URL baseURL = getBaseJarURL(firstURL); try { ((JarURLConnection) baseURL.openConnection()).getManifest(); exists = true; } catch (IOException e) { // we still have no definite answer on whether the JAR file // and therefore the PREFERRED.LIST exists } catch (NullPointerException e){ // Sun Bug ID: 6536522 // NullPointerException is thrown instead of MalformedURLException // Case is the same as above, we have no definite answer on // whether the JAR file and therefore the PREFERRED.LIST exists. System.err.println("NPE thrown while trying to open connection :" + baseURL); e.printStackTrace(System.err); } if (!exists) { exists = (getPreferredConnection(firstURL, true) != null); } if (exists) { synchronized (existSet) { existSet.add(firstURL.toString()); } } } return exists; } /** * Returns a "jar:" URL for the root directory of the JAR file at * the specified URL. If this loader was constructed with a * URLStreamHandlerFactory, then the returned URL will have a * URLStreamHandler that was created by the factory. **/ private URL getBaseJarURL(final URL url) throws MalformedURLException { if (jarHandler == null) { return new URL("jar", "", -1, url + "!/"); } else { try { return (URL) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws MalformedURLException { return new URL("jar", "", -1, url + "!/", jarHandler); } }); } catch (PrivilegedActionException e) { throw (MalformedURLException) e.getCause(); } } } /** * Obtain a url connection from which an input stream that * contains a preferred list can be obtained. * * For http urls, attempts to use http response codes to * determine if a preferred list exists or is definitely not * found. Simply attempts to open a connection to other kinds * of non-file urls. If the attempt fails, an IOException is * thrown to user code. * * Returns null if the preferred list definitely does not * exist. Rethrows all indefinite IOExceptions generated * while trying to open a connection to the preferred list. * * The caller has the option to close the connection after the * resource has been detected (as will happen when probing for a * PREFERRED.LIST). */ private URLConnection getPreferredConnection(URL url, boolean closeAfter) throws IOException { if (url.getProtocol().equals("file")) { return url.openConnection(); } URLConnection closeConn = null; URLConnection conn = null; try { closeConn = url.openConnection(); conn = closeConn; /* check status of http urls */ if (conn instanceof HttpURLConnection) { HttpURLConnection hconn = (HttpURLConnection) conn; if (closeAfter) { hconn.setRequestMethod("HEAD"); } int responseCode = hconn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: /* the preferred list exists */ break; /* 404, not found appears to be handled by * HttpURLConnection (FileNotFoundException is * thrown), but to be safe do the right thing here as * well. */ case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_GONE: /* list definitely does not exist */ conn = null; break; default: /* indefinite response code */ throw new IOException("Indefinite http response for " + "preferred list request:" + hconn.getResponseMessage()); } } } finally { if (closeAfter && (closeConn != null)) { /* clean up after... */ try { closeConn.getInputStream().close(); } catch (IOException e) { } catch (NullPointerException e){ // Sun Bug ID: 6536522 } } } return conn; } /** * Returns <code>true</code> if a class or resource with the * specified name is preferred for this class loader, and * <code>false</code> if a class or resource with the specified * name is not preferred for this loader. * * <p>If <code>isClass</code> is <code>true</code>, then * <code>name</code> is interpreted as the binary name of a class; * otherwise, <code>name</code> is interpreted as the full path of * a resource. * * <p>This method only returns <code>true</code> if a class or * resource with the specified name exists in the this loader's * path of URLs and the name is preferred in the preferred list. * This method returns <code>false</code> if the name is not * preferred in the preferred list or if the name is preferred * with the default preferred entry or a wildcard preferred entry * and the class or resource does not exist in the path of URLs. * * @param name the name of the class or resource * * @param isClass <code>true</code> if <code>name</code> is a * binary class name, and <code>false</code> if <code>name</code> * is the full path of a resource * * @return <code>true</code> if a class or resource named * <code>name</code> is preferred for this loader, and * <code>false</code> if a class or resource named * <code>name</code> is not preferred for this loader * * @throws IOException if the preferred list cannot definitely be * determined to exist or not exist, or if the preferred list * contains a syntax error, or if the name is preferred with the * default preferred entry or a wildcard preferred entry and the * class or resource cannot definitely be determined to exist or * not exist in the path of URLs, or if the name is preferred with * a non-wildcard entry and the class or resource does not exist * or cannot definitely be determined to exist in the path of URLs **/ protected boolean isPreferredResource(final String name, final boolean isClass) throws IOException { try { return ((Boolean) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws IOException { boolean b = isPreferredResource0(name, isClass); return Boolean.valueOf(b); } }, acc)).booleanValue(); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } } /* * Perform the work to determine if a resource name is preferred. */ private synchronized boolean isPreferredResource0(String name, boolean isClass) throws IOException { if (!preferredResourcesInitialized) { initializePreferredResources(); preferredResourcesInitialized = true; } if (preferredResources == null) { return false; // no preferred list: nothing is preferred } String resourceName = name; if (isClass) { /* class name -> resource name */ resourceName = name.replace('.', '/') + ".class"; } /* * Determine if the class name is preferred. Making this * distinction is somewhat tricky because we need to cache the * preferred state (i.e. if the name is preferred and its * resource exists) in a way that avoids duplication of * preferred information - state information is stored back * into the preferred resources object for this class loader * and not held in a separate preferred settings cache. */ boolean resourcePreferred = false; int state = preferredResources.getNameState(resourceName, isClass); switch (state) { case PreferredResources.NAME_NOT_PREFERRED: resourcePreferred = false; break; case PreferredResources.NAME_PREFERRED_RESOURCE_EXISTS: resourcePreferred = true; break; case PreferredResources.NAME_NO_PREFERENCE: Boolean wildcardPref = preferredResources.getWildcardPreference(resourceName); if (wildcardPref == null) { /* preferredDefault counts as a wild card */ wildcardPref = preferredResources.getDefaultPreference(); } if (wildcardPref.booleanValue()) { resourcePreferred = findResourceUpdateState(name, resourceName); } break; case PreferredResources.NAME_PREFERRED: resourcePreferred = findResourceUpdateState(name, resourceName); if (!resourcePreferred) { throw new IOException("no resource found for " + "complete preferred name"); } break; default: throw new Error("unknown preference state"); } return resourcePreferred; } /* * Determine if a resource for a given preferred name exists. If * the resource exists record its new state in the * preferredResources object. * * This method must only be invoked while synchronized on this * PreferredClassLoader. */ private boolean findResourceUpdateState(String name, String resourceName) throws IOException { assert Thread.holdsLock(this); boolean resourcePreferred = false; if (findResource(resourceName) != null) { /* the resource is know to exist */ preferredResources.setNameState(resourceName, PreferredResources.NAME_PREFERRED_RESOURCE_EXISTS); resourcePreferred = true; } return resourcePreferred; } /** * Loads a class with the specified name. * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>This method first invokes {@link #findLoadedClass * findLoadedClass} with <code>name</code>; if * <code>findLoadedClass</code> returns a non-<code>null</code> * <code>Class</code>, then this method returns that * <code>Class</code>. * * <p>Otherwise, this method invokes {@link #isPreferredResource * isPreferredResource} with <code>name</code> as the first * argument and <code>true</code> as the second argument: * * <ul> * * <li>If <code>isPreferredResource</code> throws an * <code>IOException</code>, then this method throws a * <code>ClassNotFoundException</code> containing the * <code>IOException</code> as its cause. * * <li>If <code>isPreferredResource</code> returns * <code>true</code>, then this method invokes {@link #findClass * findClass} with <code>name</code>. If <code>findClass</code> * throws an exception, then this method throws that exception. * Otherwise, this method returns the <code>Class</code> returned * by <code>findClass</code>, and if <code>resolve</code> is * <code>true</code>, {@link #resolveClass resolveClass} is * invoked with the <code>Class</code> before returning. * * <li>If <code>isPreferredResource</code> returns * <code>false</code>, then this method invokes the superclass * implementation of {@link ClassLoader#loadClass(String,boolean) * loadClass} with <code>name</code> and <code>resolve</code> and * returns the result. If the superclass's <code>loadClass</code> * throws an exception, then this method throws that exception. * * </ul> * * @param name the binary name of the class to load * * @param resolve if <code>true</code>, then {@link #resolveClass * resolveClass} will be invoked with the loaded class before * returning * * @return the loaded class * * @throws ClassNotFoundException if the class could not be found **/ protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { boolean preferred; try { preferred = isPreferredResource(name, true); } catch (IOException e) { throw new ClassNotFoundException(name + " (could not determine preferred setting; " + (firstURL != null ? "first URL: \"" + firstURL + "\"" : "no URLs") + ")", e); } if (preferred) { c = findClass(name); if (resolve) { resolveClass(c); } return c; } else { return super.loadClass(name, resolve); } } return c; } /** * Gets a resource with the specified name. * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>This method invokes {@link #isPreferredResource * isPreferredResource} with <code>name</code> as the first * argument and <code>false</code> as the second argument: * * <ul> * * <li>If <code>isPreferredResource</code> throws an * <code>IOException</code>, then this method returns * <code>null</code>. * * <li>If <code>isPreferredResource</code> returns * <code>true</code>, then this method invokes {@link * #findResource findResource} with <code>name</code> and returns * the result. * * <li>If <code>isPreferredResource</code> returns * <code>false</code>, then this method invokes the superclass * implementation of {@link ClassLoader#getResource getResource} * with <code>name</code> and returns the result. * * </ul> * * @param name the name of the resource to get * * @return a <code>URL</code> for the resource, or * <code>null</code> if the resource could not be found **/ public URL getResource(String name) { try { return (isPreferredResource(name, false) ? findResource(name) : super.getResource(name)); } catch (IOException e) { } return null; } /* * Work around 4841786: wrap ClassLoader.definePackage so that if * it throws an IllegalArgumentException because an ancestor * loader "defined" the named package since the last time that * ClassLoader.getPackage was invoked, then just return the * result of invoking ClassLoader.getPackage again here. * Fortunately, URLClassLoader.defineClass ignores the value * returned by this method. */ protected Package definePackage(String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase) { try { return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); } catch (IllegalArgumentException e) { return getPackage(name); } } protected Class<?> findClass(final String name) throws ClassNotFoundException { /* TODO: Override and create our own CodeSource * implementation that contains permissions.perm * After we retrieve the manifest, class bytes and * certificates, create the CodeSource we call * defineClass(String name, byte[]b, int off, int len, CodeSource cs) * * This will be utilised by a class that overrides * BasicProxyPreparer.getPermissions() * to retrieve the advisory permissions. */ return super.findClass(name); } /** * {@inheritDoc} * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>If this <code>PreferredClassLoader</code> was constructed * with a non-<code>null</code> export class annotation string, * then this method returns that string. Otherwise, this method * returns a space-separated list of this loader's path of URLs. **/ public String getClassAnnotation() { return exportAnnotation; } /** * Check that the current access control context has all of the * permissions necessary to load classes from this loader. */ void checkPermissions() { checkPermissions(permissions); } /** * Check that the current access control context has all of the * given permissions. */ private static void checkPermissions(PermissionCollection perms) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // should never be null? Enumeration en = perms.elements(); while (en.hasMoreElements()) { sm.checkPermission((Permission) en.nextElement()); } } } /** * Returns the static permissions to be automatically granted to * classes loaded from the specified {@link CodeSource} and * defined by this class loader. * * <p><code>PreferredClassLoader</code> implements this method as * follows: * * <p>If there is a security manager and this * <code>PreferredClassLoader</code> was constructed to enforce * {@link DownloadPermission}, then this method checks that the * current security policy grants the specified * <code>CodeSource</code> the permission * <code>DownloadPermission("permit")</code>; if that check fails, * then this method throws a <code>SecurityException</code>. * * <p>Then this method invokes the superclass implementation of * {@link #getPermissions getPermissions} and returns the result. * * @param codeSource the <code>CodeSource</code> to return the * permissions to be granted to * * @return the permissions to be granted to the * <code>CodeSource</code> * * @throws SecurityException if there is a security manager, this * <code>PreferredClassLoader</code> was constructed to enforce * <code>DownloadPermission</code>, and the current security * policy does not grant the specified <code>CodeSource</code> the * permission <code>DownloadPermission("permit")</code> **/ protected PermissionCollection getPermissions(CodeSource codeSource) { if (requireDlPerm) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { ProtectionDomain pd = new ProtectionDomain(codeSource, null, this, null); if (!pd.implies(downloadPermission)) { throw new SecurityException( "CodeSource not permitted to define class: " + codeSource); } } } return super.getPermissions(codeSource); } /** * Returns a string representation of this class loader. **/ public String toString() { return super.toString() + "[\"" + exportAnnotation + "\"]"; } /** * Return the access control context that a loader for the given * codebase URL path should execute with. */ static AccessControlContext getLoaderAccessControlContext(URL[] urls) { /* * The approach used here is taken from the similar method * getAccessControlContext() in the sun.applet.AppletPanel class. */ // begin with permissions granted to all code in current policy PermissionCollection perms = (PermissionCollection) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { CodeSource codesource = new CodeSource(null, (Certificate[]) null); Policy p = java.security.Policy.getPolicy(); if (p != null) { return p.getPermissions(codesource); } else { return new Permissions(); } } }); // createClassLoader permission needed to create loader in context perms.add(new RuntimePermission("createClassLoader")); // add permissions to read any "java.*" property perms.add(new java.util.PropertyPermission("java.*","read")); // add permissions required to load from codebase URL path addPermissionsForURLs(urls, perms, true); /* * Create an AccessControlContext that consists of a single * protection domain with only the permissions calculated above. * Comment added 7th May 2010 by Peter Firmstone: * This did call the pre java 1.4 constructor which causes the * ProtectionDomain to not consult the Policy, this * had the effect of not allowing Dynamic Permission changes to be * effected by the Policy. It doesn't affect the existing * DynamicPolicy implementation as it returns the Permissions * allowing the ProtectionDomain domain combiner to combine * cached permissions with those from the Policy. * ProtectionDomain(CodeSource, PermissionCollection) * By utilising this earlier constructor it also prevents * RevokeableDynamicPolicy, hence the constructor change. */ ProtectionDomain pd = new ProtectionDomain( new CodeSource((urls.length > 0 ? urls[0] : null), (Certificate[]) null), perms, null, null); return new AccessControlContext(new ProtectionDomain[] { pd }); } /** * Adds to the specified permission collection the permissions * necessary to load classes from a loader with the specified URL * path; if "forLoader" is true, also adds URL-specific * permissions necessary for the security context that such a * loader operates within, such as permissions necessary for * granting automatic permissions to classes defined by the * loader. A given permission is only added to the collection if * it is not already implied by the collection. **/ static void addPermissionsForURLs(URL[] urls, PermissionCollection perms, boolean forLoader) { for (int i = 0; i < urls.length; i++) { URL url = urls[i]; try { URLConnection urlConnection = url.openConnection(); Permission p = urlConnection.getPermission(); if (p != null) { if (p instanceof FilePermission) { /* * If the codebase is a file, the permission required * to actually read classes from the codebase URL is * the permission to read all files beneath the last * directory in the file path, either because JAR * files can refer to other JAR files in the same * directory, or because permission to read a * directory is not implied by permission to read the * contents of a directory, which all that might be * granted. */ String path = p.getName(); int endIndex = path.lastIndexOf(File.separatorChar); if (endIndex != -1) { path = path.substring(0, endIndex+1); if (path.endsWith(File.separator)) { path += "-"; } Permission p2 = new FilePermission(path, "read"); if (!perms.implies(p2)) { perms.add(p2); } } else { /* * No directory separator: use permission to * read the file. */ if (!perms.implies(p)) { perms.add(p); } } } else { if (!perms.implies(p)) { perms.add(p); } /* * If the purpose of these permissions is to grant * them to an instance of a URLClassLoader subclass, * we must add permission to connect to and accept * from the host of non-"file:" URLs, otherwise the * getPermissions() method of URLClassLoader will * throw a security exception. */ if (forLoader) { // get URL with meaningful host component URL hostURL = url; for (URLConnection conn = urlConnection; conn instanceof JarURLConnection;) { hostURL = ((JarURLConnection) conn).getJarFileURL(); conn = hostURL.openConnection(); } String host = hostURL.getHost(); if (host != null && p.implies(new SocketPermission(host, "resolve"))) { Permission p2 = new SocketPermission(host, "connect,accept"); if (!perms.implies(p2)) { perms.add(p2); } } } } } } catch (IOException e) { /* * This shouldn't happen, although it is declared to be * thrown by openConnection() and getPermission(). If it * does, don't bother granting or requiring any permissions * for this URL. */ } } } }
Work around sun bug ID6536522 NPE thrown instead of MalformedURLException git-svn-id: c7bbe51404944d9b279db17c7a6e06b416cefbc7@1369539 13f79535-47bb-0310-9956-ffa450edef68
src/net/jini/loader/pref/PreferredClassLoader.java
Work around sun bug ID6536522 NPE thrown instead of MalformedURLException
<ide><path>rc/net/jini/loader/pref/PreferredClassLoader.java <ide> * does, don't bother granting or requiring any permissions <ide> * for this URL. <ide> */ <del> } <add> } catch (NullPointerException e){ <add> // Sun Bug ID: 6536522 <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
6de89987389bdb2f338da47eb414bb67c739ca40
0
sequenceiq/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.cloudbreak.service.stack.connector.aws; import static com.amazonaws.services.cloudformation.model.StackStatus.CREATE_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.CREATE_FAILED; import static com.amazonaws.services.cloudformation.model.StackStatus.DELETE_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.DELETE_FAILED; import static com.amazonaws.services.cloudformation.model.StackStatus.ROLLBACK_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.ROLLBACK_FAILED; import static com.amazonaws.services.cloudformation.model.StackStatus.ROLLBACK_IN_PROGRESS; import static com.amazonaws.services.cloudformation.model.StackStatus.UPDATE_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.UPDATE_ROLLBACK_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.UPDATE_ROLLBACK_FAILED; import static com.sequenceiq.cloudbreak.service.PollingResult.isExited; import static com.sequenceiq.cloudbreak.service.PollingResult.isSuccess; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Regions; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import com.amazonaws.services.autoscaling.model.DetachInstancesRequest; import com.amazonaws.services.autoscaling.model.ResumeProcessesRequest; import com.amazonaws.services.autoscaling.model.SuspendProcessesRequest; import com.amazonaws.services.autoscaling.model.UpdateAutoScalingGroupRequest; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.CreateStackRequest; import com.amazonaws.services.cloudformation.model.DeleteStackRequest; import com.amazonaws.services.cloudformation.model.DescribeStacksRequest; import com.amazonaws.services.cloudformation.model.OnFailure; import com.amazonaws.services.cloudformation.model.Parameter; import com.amazonaws.services.cloudformation.model.StackStatus; import com.amazonaws.services.cloudformation.model.UpdateStackRequest; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeImagesRequest; import com.amazonaws.services.ec2.model.DescribeImagesResult; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Image; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.StartInstancesRequest; import com.amazonaws.services.ec2.model.StopInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.google.common.collect.Sets; import com.sequenceiq.cloudbreak.conf.ReactorConfig; import com.sequenceiq.cloudbreak.controller.BuildStackFailureException; import com.sequenceiq.cloudbreak.controller.StackCreationFailureException; import com.sequenceiq.cloudbreak.domain.AwsCredential; import com.sequenceiq.cloudbreak.domain.CloudPlatform; import com.sequenceiq.cloudbreak.domain.Cluster; import com.sequenceiq.cloudbreak.domain.Credential; import com.sequenceiq.cloudbreak.domain.InstanceGroup; import com.sequenceiq.cloudbreak.domain.InstanceMetaData; import com.sequenceiq.cloudbreak.domain.Resource; import com.sequenceiq.cloudbreak.domain.ResourceType; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.domain.Status; import com.sequenceiq.cloudbreak.logger.MDCBuilder; import com.sequenceiq.cloudbreak.repository.ClusterRepository; import com.sequenceiq.cloudbreak.repository.InstanceMetaDataRepository; import com.sequenceiq.cloudbreak.repository.RetryingStackUpdater; import com.sequenceiq.cloudbreak.repository.StackRepository; import com.sequenceiq.cloudbreak.service.PollingResult; import com.sequenceiq.cloudbreak.service.PollingService; import com.sequenceiq.cloudbreak.service.cluster.flow.AmbariClusterConnector; import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector; import com.sequenceiq.cloudbreak.service.stack.connector.UpdateFailedException; import com.sequenceiq.cloudbreak.service.stack.connector.UserDataBuilder; import com.sequenceiq.cloudbreak.service.stack.event.AddInstancesComplete; import com.sequenceiq.cloudbreak.service.stack.event.ProvisionComplete; import com.sequenceiq.cloudbreak.service.stack.event.StackDeleteComplete; import com.sequenceiq.cloudbreak.service.stack.event.StackUpdateSuccess; import com.sequenceiq.cloudbreak.service.stack.flow.AwsInstanceStatusCheckerTask; import com.sequenceiq.cloudbreak.service.stack.flow.AwsInstances; import reactor.core.Reactor; import reactor.event.Event; @Service public class AwsConnector implements CloudPlatformConnector { private static final int MAX_POLLING_ATTEMPTS = 60; private static final int POLLING_INTERVAL = 5000; private static final int INFINITE_ATTEMPTS = -1; private static final Logger LOGGER = LoggerFactory.getLogger(AwsConnector.class); @Autowired private AwsStackUtil awsStackUtil; @Autowired private Reactor reactor; @Autowired private ASGroupStatusCheckerTask asGroupStatusCheckerTask; @Autowired private CloudFormationTemplateBuilder cfTemplateBuilder; @Autowired private RetryingStackUpdater stackUpdater; @Autowired private CloudFormationStackUtil cfStackUtil; @Autowired private InstanceMetaDataRepository instanceMetaDataRepository; @Autowired private PollingService<AwsInstances> awsPollingService; @Autowired private PollingService<AutoScalingGroupReady> pollingService; @Autowired private PollingService<CloudFormationStackPollerContext> stackPollingService; @Autowired private ClusterRepository clusterRepository; @Autowired private UserDataBuilder userDataBuilder; @Autowired private StackRepository stackRepository; @Autowired private AwsInstanceStatusCheckerTask awsInstanceStatusCheckerTask; @Autowired private CloudFormationStackStatusChecker cloudFormationStackStatusChecker; @Override public void buildStack(Stack stack, String userData, Map<String, Object> setupProperties) { MDCBuilder.buildMdcContext(stack); Long stackId = stack.getId(); AwsCredential awsCredential = (AwsCredential) stack.getCredential(); AmazonCloudFormationClient client = awsStackUtil.createCloudFormationClient(Regions.valueOf(stack.getRegion()), awsCredential); String cFStackName = cfStackUtil.getCfStackName(stack); boolean existingVPC = isExistingVPC(stack); CreateStackRequest createStackRequest = new CreateStackRequest() .withStackName(cFStackName) .withOnFailure(OnFailure.valueOf(stack.getOnFailureActionAction().name())) .withTemplateBody(cfTemplateBuilder.build(stack, existingVPC, "templates/aws-cf-stack.ftl")) .withParameters(getStackParameters(stack, userData, awsCredential, cFStackName, existingVPC)); client.createStack(createStackRequest); Resource resource = new Resource(ResourceType.CLOUDFORMATION_STACK, cFStackName, stack, null); Set<Resource> resources = Sets.newHashSet(resource); stack = stackUpdater.updateStackResources(stackId, resources); LOGGER.info("CloudFormation stack creation request sent with stack name: '{}' for stack: '{}'", cFStackName, stackId); List<StackStatus> errorStatuses = Arrays.asList(CREATE_FAILED, ROLLBACK_IN_PROGRESS, ROLLBACK_FAILED, ROLLBACK_COMPLETE); CloudFormationStackPollerContext stackPollerContext = new CloudFormationStackPollerContext(client, CREATE_COMPLETE, errorStatuses, stack); try { PollingResult pollingResult = stackPollingService .pollWithTimeout(cloudFormationStackStatusChecker, stackPollerContext, POLLING_INTERVAL, INFINITE_ATTEMPTS); if (isSuccess(pollingResult)) { sendUpdatedStackCreateComplete(stackId, cFStackName, resources); } } catch (CloudFormationStackException e) { LOGGER.error(String.format("Failed to create CloudFormation stack: %s", stackId), e); stackUpdater.updateStackStatus(stackId, Status.CREATE_FAILED, "Creation of cluster infrastructure failed: " + e.getMessage()); throw new BuildStackFailureException(e); } } @Override public boolean addInstances(Stack stack, String userData, Integer instanceCount, String hostGroup) { MDCBuilder.buildMdcContext(stack); InstanceGroup instanceGroupByInstanceGroupName = stack.getInstanceGroupByInstanceGroupName(hostGroup); Integer requiredInstances = instanceGroupByInstanceGroupName.getNodeCount() + instanceCount; Regions region = Regions.valueOf(stack.getRegion()); AwsCredential credential = (AwsCredential) stack.getCredential(); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(region, credential); AmazonEC2Client amazonEC2Client = awsStackUtil.createEC2Client(region, credential); String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, hostGroup); amazonASClient.updateAutoScalingGroup(new UpdateAutoScalingGroupRequest() .withAutoScalingGroupName(asGroupName) .withMaxSize(requiredInstances) .withDesiredCapacity(requiredInstances)); LOGGER.info("Updated AutoScaling group's desiredCapacity: [stack: '{}', from: '{}', to: '{}']", stack.getId(), instanceGroupByInstanceGroupName.getNodeCount(), instanceGroupByInstanceGroupName.getNodeCount() + instanceCount); AutoScalingGroupReady asGroupReady = new AutoScalingGroupReady(stack, amazonEC2Client, amazonASClient, asGroupName, requiredInstances); LOGGER.info("Polling autoscaling group until new instances are ready. [stack: {}, asGroup: {}]", stack.getId(), asGroupName); PollingResult pollingResult = pollingService.pollWithTimeout(asGroupStatusCheckerTask, asGroupReady, POLLING_INTERVAL, MAX_POLLING_ATTEMPTS); if (isSuccess(pollingResult)) { LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.ADD_INSTANCES_COMPLETE_EVENT, stack.getId()); reactor.notify(ReactorConfig.ADD_INSTANCES_COMPLETE_EVENT, Event.wrap(new AddInstancesComplete(CloudPlatform.AWS, stack.getId(), null, hostGroup))); } return true; } /** * If the AutoScaling group has some suspended scaling policies it causes that the CloudFormation stack delete won't be able to remove the ASG. * In this case the ASG size is reduced to zero and the processes are resumed first. */ @Override public boolean removeInstances(Stack stack, Set<String> instanceIds, String hostGroup) { MDCBuilder.buildMdcContext(stack); Regions region = Regions.valueOf(stack.getRegion()); AwsCredential credential = (AwsCredential) stack.getCredential(); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(region, credential); AmazonEC2Client amazonEC2Client = awsStackUtil.createEC2Client(region, credential); String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, hostGroup); DetachInstancesRequest detachInstancesRequest = new DetachInstancesRequest().withAutoScalingGroupName(asGroupName).withInstanceIds(instanceIds) .withShouldDecrementDesiredCapacity(true); amazonASClient.detachInstances(detachInstancesRequest); amazonEC2Client.terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceIds)); LOGGER.info("Terminated instances in stack '{}': '{}'", stack.getId(), instanceIds); LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.STACK_UPDATE_SUCCESS_EVENT, stack.getId()); reactor.notify(ReactorConfig.STACK_UPDATE_SUCCESS_EVENT, Event.wrap(new StackUpdateSuccess(stack.getId(), true, instanceIds, hostGroup))); return true; } @Override public void updateAllowedSubnets(Stack stack, String userData) throws UpdateFailedException { String cFStackName = cfStackUtil.getCfStackName(stack); boolean existingVPC = isExistingVPC(stack); UpdateStackRequest updateStackRequest = new UpdateStackRequest() .withStackName(cFStackName) .withTemplateBody(cfTemplateBuilder.build(stack, existingVPC, "templates/aws-cf-stack.ftl")) .withParameters(getStackParameters(stack, userData, (AwsCredential) stack.getCredential(), stack.getName(), existingVPC)); AmazonCloudFormationClient cloudFormationClient = awsStackUtil.createCloudFormationClient(stack); cloudFormationClient.updateStack(updateStackRequest); List<StackStatus> errorStatuses = Arrays.asList(UPDATE_ROLLBACK_COMPLETE, UPDATE_ROLLBACK_FAILED); CloudFormationStackPollerContext stackPollerContext = new CloudFormationStackPollerContext(cloudFormationClient, UPDATE_COMPLETE, errorStatuses, stack); try { PollingResult pollingResult = stackPollingService.pollWithTimeout(cloudFormationStackStatusChecker, stackPollerContext, POLLING_INTERVAL, INFINITE_ATTEMPTS); if (isExited(pollingResult)) { throw new UpdateFailedException(new IllegalStateException()); } } catch (CloudFormationStackException e) { throw new UpdateFailedException(e); } } @Override public boolean startAll(Stack stack) { return setStackState(stack, false); } @Override public boolean stopAll(Stack stack) { return setStackState(stack, true); } /** * If the AutoScaling group has some suspended scaling policies it causes that the CloudFormation stack delete won't be able to remove the ASG. * In this case the ASG size is reduced to zero and the processes are resumed first. */ @Override public void deleteStack(Stack stack, Credential credential) { MDCBuilder.buildMdcContext(stack); LOGGER.info("Deleting stack: {}", stack.getId()); AwsCredential awsCredential = (AwsCredential) credential; Resource resource = stack.getResourceByType(ResourceType.CLOUDFORMATION_STACK); if (resource != null) { AmazonCloudFormationClient client = awsStackUtil.createCloudFormationClient(Regions.valueOf(stack.getRegion()), awsCredential); String cFStackName = resource.getResourceName(); LOGGER.info("Deleting CloudFormation stack for stack: {} [cf stack id: {}]", stack.getId(), cFStackName); DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(cFStackName); try { client.describeStacks(describeStacksRequest); } catch (AmazonServiceException e) { if (e.getErrorMessage().equals("Stack:" + cFStackName + " does not exist")) { LOGGER.info("AWS CloudFormation stack not found, publishing {} event.", ReactorConfig.DELETE_COMPLETE_EVENT); reactor.notify(ReactorConfig.DELETE_COMPLETE_EVENT, Event.wrap(new StackDeleteComplete(stack.getId()))); return; } else { throw e; } } resumeAutoScalingPolicies(stack, awsCredential); DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName(cFStackName); client.deleteStack(deleteStackRequest); List<StackStatus> errorStatuses = Arrays.asList(DELETE_FAILED); CloudFormationStackPollerContext stackPollerContext = new CloudFormationStackPollerContext(client, DELETE_COMPLETE, errorStatuses, stack); try { PollingResult pollingResult = stackPollingService .pollWithTimeout(cloudFormationStackStatusChecker, stackPollerContext, POLLING_INTERVAL, INFINITE_ATTEMPTS); if (isSuccess(pollingResult)) { LOGGER.info("CloudFormation stack({}) delete completed. Publishing {} event.", cFStackName, ReactorConfig.DELETE_COMPLETE_EVENT); reactor.notify(ReactorConfig.DELETE_COMPLETE_EVENT, Event.wrap(new StackDeleteComplete(stack.getId()))); } } catch (CloudFormationStackException e) { LOGGER.error(String.format("Failed to delete CloudFormation stack: %s, id:%s", cFStackName, stack.getId()), e); stackUpdater.updateStackStatus(stack.getId(), Status.DELETE_FAILED, "Failed to delete stack: " + e.getMessage()); throw new BuildStackFailureException(e); } } else { LOGGER.info("No resource saved for stack, publishing {} event.", ReactorConfig.DELETE_COMPLETE_EVENT); reactor.notify(ReactorConfig.DELETE_COMPLETE_EVENT, Event.wrap(new StackDeleteComplete(stack.getId()))); } } private boolean isExistingVPC(Stack stack) { return stack.getParameters().get("vpcId") != null && stack.getParameters().get("subnetCIDR") != null && stack.getParameters().get("internetGatewayId") != null; } private List<Parameter> getStackParameters(Stack stack, String userData, AwsCredential awsCredential, String stackName, boolean existingVPC) { List<Parameter> parameters = new ArrayList<>(Arrays.asList( new Parameter().withParameterKey("CBUserData").withParameterValue(userData), new Parameter().withParameterKey("StackName").withParameterValue(stackName), new Parameter().withParameterKey("StackOwner").withParameterValue(awsCredential.getRoleArn()), new Parameter().withParameterKey("KeyName").withParameterValue(awsCredential.getKeyPairName()), new Parameter().withParameterKey("AMI").withParameterValue(stack.getImage()), new Parameter().withParameterKey("RootDeviceName").withParameterValue(getRootDeviceName(stack, awsCredential)) )); if (existingVPC) { parameters.add(new Parameter().withParameterKey("VPCId").withParameterValue(stack.getParameters().get("vpcId"))); parameters.add(new Parameter().withParameterKey("SubnetCIDR").withParameterValue(stack.getParameters().get("subnetCIDR"))); parameters.add(new Parameter().withParameterKey("InternetGatewayId").withParameterValue(stack.getParameters().get("internetGatewayId"))); } return parameters; } private void sendUpdatedStackCreateComplete(long stackId, String cFStackName, Set<Resource> resourceSet) { stackUpdater.updateStackCreateComplete(stackId); LOGGER.info("CloudFormation stack({}) creation completed.", cFStackName); LOGGER.info("Publishing {} event.", ReactorConfig.PROVISION_COMPLETE_EVENT); reactor.notify(ReactorConfig.PROVISION_COMPLETE_EVENT, Event.wrap(new ProvisionComplete(CloudPlatform.AWS, stackId, resourceSet))); } private String getRootDeviceName(Stack stack, AwsCredential awsCredential) { AmazonEC2Client ec2Client = awsStackUtil.createEC2Client(Regions.valueOf(stack.getRegion()), awsCredential); DescribeImagesResult images = ec2Client.describeImages(new DescribeImagesRequest().withImageIds(stack.getImage())); Image image = images.getImages().get(0); if (image != null) { return image.getRootDeviceName(); } else { throw new StackCreationFailureException(String.format("Couldn't describe AMI '%s'.", stack.getImage())); } } private boolean setStackState(Stack stack, boolean stopped) { MDCBuilder.buildMdcContext(stack); boolean result = true; Regions region = Regions.valueOf(stack.getRegion()); AwsCredential credential = (AwsCredential) stack.getCredential(); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(region, credential); AmazonEC2Client amazonEC2Client = awsStackUtil.createEC2Client(region, credential); for (InstanceGroup instanceGroup : stack.getInstanceGroups()) { String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, instanceGroup.getGroupName()); Collection<String> instances = new ArrayList<>(); for (InstanceMetaData instance : instanceGroup.getInstanceMetaData()) { if (instance.getInstanceGroup().getGroupName().equals(instanceGroup.getGroupName())) { instances.add(instance.getInstanceId()); } } try { if (stopped) { amazonASClient.suspendProcesses(new SuspendProcessesRequest().withAutoScalingGroupName(asGroupName)); amazonEC2Client.stopInstances(new StopInstancesRequest().withInstanceIds(instances)); awsPollingService.pollWithTimeout( new AwsInstanceStatusCheckerTask(), new AwsInstances(stack, amazonEC2Client, new ArrayList(instances), "Stopped"), AmbariClusterConnector.POLLING_INTERVAL, AmbariClusterConnector.MAX_ATTEMPTS_FOR_AMBARI_OPS); } else { amazonEC2Client.startInstances(new StartInstancesRequest().withInstanceIds(instances)); PollingResult pollingResult = awsPollingService.pollWithTimeout( awsInstanceStatusCheckerTask, new AwsInstances(stack, amazonEC2Client, new ArrayList(instances), "Running"), AmbariClusterConnector.POLLING_INTERVAL, AmbariClusterConnector.MAX_ATTEMPTS_FOR_AMBARI_OPS); if (isSuccess(pollingResult)) { amazonASClient.resumeProcesses(new ResumeProcessesRequest().withAutoScalingGroupName(asGroupName)); updateInstanceMetadata(stack, amazonEC2Client, stack.getRunningInstanceMetaData(), instances); } } } catch (Exception e) { LOGGER.error(String.format("Failed to %s AWS instances on stack: %s", stopped ? "stop" : "start", stack.getId()), e); result = false; } } return result; } private void updateInstanceMetadata(Stack stack, AmazonEC2Client amazonEC2Client, Set<InstanceMetaData> instanceMetaData, Collection<String> instances) { MDCBuilder.buildMdcContext(stack); DescribeInstancesResult describeResult = amazonEC2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instances)); for (Reservation reservation : describeResult.getReservations()) { for (Instance instance : reservation.getInstances()) { for (InstanceMetaData metaData : instanceMetaData) { if (metaData.getInstanceId().equals(instance.getInstanceId())) { String publicIp = instance.getPublicIpAddress(); if (metaData.getAmbariServer()) { stack.setAmbariIp(publicIp); Cluster cluster = clusterRepository.findOneWithLists(stack.getCluster().getId()); stack.setCluster(cluster); stackRepository.save(stack); } metaData.setPublicIp(publicIp); instanceMetaDataRepository.save(metaData); break; } } } } } private void resumeAutoScalingPolicies(Stack stack, AwsCredential awsCredential) { for (InstanceGroup instanceGroup : stack.getInstanceGroups()) { try { String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, instanceGroup.getGroupName()); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(Regions.valueOf(stack.getRegion()), awsCredential); List<AutoScalingGroup> asGroups = amazonASClient.describeAutoScalingGroups(new DescribeAutoScalingGroupsRequest() .withAutoScalingGroupNames(asGroupName)).getAutoScalingGroups(); if (!asGroups.isEmpty()) { if (!asGroups.get(0).getSuspendedProcesses().isEmpty()) { amazonASClient.updateAutoScalingGroup(new UpdateAutoScalingGroupRequest() .withAutoScalingGroupName(asGroupName) .withMinSize(0) .withDesiredCapacity(0)); amazonASClient.resumeProcesses(new ResumeProcessesRequest().withAutoScalingGroupName(asGroupName)); } } } catch (AmazonServiceException e) { if (e.getErrorMessage().matches("Resource.*does not exist for stack.*")) { MDCBuilder.buildMdcContext(stack); LOGGER.info(e.getErrorMessage()); } else { throw e; } } } } @Override public void rollback(Stack stack, Set<Resource> resourceSet) { return; } @Override public CloudPlatform getCloudPlatform() { return CloudPlatform.AWS; } protected CreateStackRequest createStackRequest() { return new CreateStackRequest(); } }
src/main/java/com/sequenceiq/cloudbreak/service/stack/connector/aws/AwsConnector.java
package com.sequenceiq.cloudbreak.service.stack.connector.aws; import static com.amazonaws.services.cloudformation.model.StackStatus.CREATE_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.CREATE_FAILED; import static com.amazonaws.services.cloudformation.model.StackStatus.DELETE_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.DELETE_FAILED; import static com.amazonaws.services.cloudformation.model.StackStatus.ROLLBACK_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.ROLLBACK_FAILED; import static com.amazonaws.services.cloudformation.model.StackStatus.ROLLBACK_IN_PROGRESS; import static com.amazonaws.services.cloudformation.model.StackStatus.UPDATE_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.UPDATE_ROLLBACK_COMPLETE; import static com.amazonaws.services.cloudformation.model.StackStatus.UPDATE_ROLLBACK_FAILED; import static com.sequenceiq.cloudbreak.service.PollingResult.isExited; import static com.sequenceiq.cloudbreak.service.PollingResult.isSuccess; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Regions; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import com.amazonaws.services.autoscaling.model.DetachInstancesRequest; import com.amazonaws.services.autoscaling.model.ResumeProcessesRequest; import com.amazonaws.services.autoscaling.model.SuspendProcessesRequest; import com.amazonaws.services.autoscaling.model.UpdateAutoScalingGroupRequest; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.CreateStackRequest; import com.amazonaws.services.cloudformation.model.DeleteStackRequest; import com.amazonaws.services.cloudformation.model.DescribeStacksRequest; import com.amazonaws.services.cloudformation.model.OnFailure; import com.amazonaws.services.cloudformation.model.Parameter; import com.amazonaws.services.cloudformation.model.StackStatus; import com.amazonaws.services.cloudformation.model.UpdateStackRequest; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeImagesRequest; import com.amazonaws.services.ec2.model.DescribeImagesResult; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Image; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.StartInstancesRequest; import com.amazonaws.services.ec2.model.StopInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.google.common.collect.Sets; import com.sequenceiq.cloudbreak.conf.ReactorConfig; import com.sequenceiq.cloudbreak.controller.BuildStackFailureException; import com.sequenceiq.cloudbreak.controller.StackCreationFailureException; import com.sequenceiq.cloudbreak.domain.AwsCredential; import com.sequenceiq.cloudbreak.domain.CloudPlatform; import com.sequenceiq.cloudbreak.domain.Cluster; import com.sequenceiq.cloudbreak.domain.Credential; import com.sequenceiq.cloudbreak.domain.InstanceGroup; import com.sequenceiq.cloudbreak.domain.InstanceMetaData; import com.sequenceiq.cloudbreak.domain.Resource; import com.sequenceiq.cloudbreak.domain.ResourceType; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.domain.Status; import com.sequenceiq.cloudbreak.logger.MDCBuilder; import com.sequenceiq.cloudbreak.repository.ClusterRepository; import com.sequenceiq.cloudbreak.repository.InstanceMetaDataRepository; import com.sequenceiq.cloudbreak.repository.RetryingStackUpdater; import com.sequenceiq.cloudbreak.repository.StackRepository; import com.sequenceiq.cloudbreak.service.PollingResult; import com.sequenceiq.cloudbreak.service.PollingService; import com.sequenceiq.cloudbreak.service.cluster.flow.AmbariClusterConnector; import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector; import com.sequenceiq.cloudbreak.service.stack.connector.UpdateFailedException; import com.sequenceiq.cloudbreak.service.stack.connector.UserDataBuilder; import com.sequenceiq.cloudbreak.service.stack.event.AddInstancesComplete; import com.sequenceiq.cloudbreak.service.stack.event.ProvisionComplete; import com.sequenceiq.cloudbreak.service.stack.event.StackDeleteComplete; import com.sequenceiq.cloudbreak.service.stack.event.StackUpdateSuccess; import com.sequenceiq.cloudbreak.service.stack.flow.AwsInstanceStatusCheckerTask; import com.sequenceiq.cloudbreak.service.stack.flow.AwsInstances; import reactor.core.Reactor; import reactor.event.Event; @Service public class AwsConnector implements CloudPlatformConnector { private static final int MAX_POLLING_ATTEMPTS = 60; private static final int POLLING_INTERVAL = 5000; private static final int INFINITE_ATTEMPTS = -1; private static final Logger LOGGER = LoggerFactory.getLogger(AwsConnector.class); @Autowired private AwsStackUtil awsStackUtil; @Autowired private Reactor reactor; @Autowired private ASGroupStatusCheckerTask asGroupStatusCheckerTask; @Autowired private CloudFormationTemplateBuilder cfTemplateBuilder; @Autowired private RetryingStackUpdater stackUpdater; @Autowired private CloudFormationStackUtil cfStackUtil; @Autowired private InstanceMetaDataRepository instanceMetaDataRepository; @Autowired private PollingService<AwsInstances> awsPollingService; @Autowired private PollingService<AutoScalingGroupReady> pollingService; @Autowired private PollingService<CloudFormationStackPollerContext> stackPollingService; @Autowired private ClusterRepository clusterRepository; @Autowired private UserDataBuilder userDataBuilder; @Autowired private StackRepository stackRepository; @Autowired private AwsInstanceStatusCheckerTask awsInstanceStatusCheckerTask; @Autowired private CloudFormationStackStatusChecker cloudFormationStackStatusChecker; @Override public void buildStack(Stack stack, String userData, Map<String, Object> setupProperties) { MDCBuilder.buildMdcContext(stack); Long stackId = stack.getId(); AwsCredential awsCredential = (AwsCredential) stack.getCredential(); AmazonCloudFormationClient client = awsStackUtil.createCloudFormationClient(Regions.valueOf(stack.getRegion()), awsCredential); String cFStackName = cfStackUtil.getCfStackName(stack); boolean existingVPC = isExistingVPC(stack); CreateStackRequest createStackRequest = new CreateStackRequest() .withStackName(cFStackName) .withOnFailure(OnFailure.valueOf(stack.getOnFailureActionAction().name())) .withTemplateBody(cfTemplateBuilder.build(stack, existingVPC, "templates/aws-cf-stack.ftl")) .withParameters(getStackParameters(stack, userData, awsCredential, cFStackName, existingVPC)); client.createStack(createStackRequest); Resource resource = new Resource(ResourceType.CLOUDFORMATION_STACK, cFStackName, stack, null); Set<Resource> resources = Sets.newHashSet(resource); stack = stackUpdater.updateStackResources(stackId, resources); LOGGER.info("CloudFormation stack creation request sent with stack name: '{}' for stack: '{}'", cFStackName, stackId); List<StackStatus> errorStatuses = Arrays.asList(CREATE_FAILED, ROLLBACK_IN_PROGRESS, ROLLBACK_FAILED, ROLLBACK_COMPLETE); CloudFormationStackPollerContext stackPollerContext = new CloudFormationStackPollerContext(client, CREATE_COMPLETE, errorStatuses, stack); try { PollingResult pollingResult = stackPollingService .pollWithTimeout(cloudFormationStackStatusChecker, stackPollerContext, POLLING_INTERVAL, INFINITE_ATTEMPTS); if (isSuccess(pollingResult)) { sendUpdatedStackCreateComplete(stackId, cFStackName, resources); } } catch (CloudFormationStackException e) { LOGGER.error(String.format("Failed to create CloudFormation stack: %s", stackId), e); stackUpdater.updateStackStatus(stackId, Status.CREATE_FAILED, "Creation of cluster infrastructure failed: " + e.getMessage()); throw new BuildStackFailureException(e); } } @Override public boolean addInstances(Stack stack, String userData, Integer instanceCount, String hostGroup) { MDCBuilder.buildMdcContext(stack); InstanceGroup instanceGroupByInstanceGroupName = stack.getInstanceGroupByInstanceGroupName(hostGroup); Integer requiredInstances = instanceGroupByInstanceGroupName.getNodeCount() + instanceCount; Regions region = Regions.valueOf(stack.getRegion()); AwsCredential credential = (AwsCredential) stack.getCredential(); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(region, credential); AmazonEC2Client amazonEC2Client = awsStackUtil.createEC2Client(region, credential); String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, hostGroup); amazonASClient.updateAutoScalingGroup(new UpdateAutoScalingGroupRequest() .withAutoScalingGroupName(asGroupName) .withMaxSize(requiredInstances) .withDesiredCapacity(requiredInstances)); LOGGER.info("Updated AutoScaling group's desiredCapacity: [stack: '{}', from: '{}', to: '{}']", stack.getId(), instanceGroupByInstanceGroupName.getNodeCount(), instanceGroupByInstanceGroupName.getNodeCount() + instanceCount); AutoScalingGroupReady asGroupReady = new AutoScalingGroupReady(stack, amazonEC2Client, amazonASClient, asGroupName, requiredInstances); LOGGER.info("Polling autoscaling group until new instances are ready. [stack: {}, asGroup: {}]", stack.getId(), asGroupName); PollingResult pollingResult = pollingService.pollWithTimeout(asGroupStatusCheckerTask, asGroupReady, POLLING_INTERVAL, MAX_POLLING_ATTEMPTS); if (isSuccess(pollingResult)) { LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.ADD_INSTANCES_COMPLETE_EVENT, stack.getId()); reactor.notify(ReactorConfig.ADD_INSTANCES_COMPLETE_EVENT, Event.wrap(new AddInstancesComplete(CloudPlatform.AWS, stack.getId(), null, hostGroup))); } return true; } /** * If the AutoScaling group has some suspended scaling policies it causes that the CloudFormation stack delete won't be able to remove the ASG. * In this case the ASG size is reduced to zero and the processes are resumed first. */ @Override public boolean removeInstances(Stack stack, Set<String> instanceIds, String hostGroup) { MDCBuilder.buildMdcContext(stack); Regions region = Regions.valueOf(stack.getRegion()); AwsCredential credential = (AwsCredential) stack.getCredential(); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(region, credential); AmazonEC2Client amazonEC2Client = awsStackUtil.createEC2Client(region, credential); String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, hostGroup); DetachInstancesRequest detachInstancesRequest = new DetachInstancesRequest().withAutoScalingGroupName(asGroupName).withInstanceIds(instanceIds) .withShouldDecrementDesiredCapacity(true); amazonASClient.detachInstances(detachInstancesRequest); amazonEC2Client.terminateInstances(new TerminateInstancesRequest().withInstanceIds(instanceIds)); LOGGER.info("Terminated instances in stack '{}': '{}'", stack.getId(), instanceIds); LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.STACK_UPDATE_SUCCESS_EVENT, stack.getId()); reactor.notify(ReactorConfig.STACK_UPDATE_SUCCESS_EVENT, Event.wrap(new StackUpdateSuccess(stack.getId(), true, instanceIds, hostGroup))); return true; } @Override public void updateAllowedSubnets(Stack stack, String userData) throws UpdateFailedException { String cFStackName = cfStackUtil.getCfStackName(stack); boolean existingVPC = isExistingVPC(stack); UpdateStackRequest updateStackRequest = new UpdateStackRequest() .withStackName(cFStackName) .withTemplateBody(cfTemplateBuilder.build(stack, existingVPC, "templates/aws-cf-stack.ftl")) .withParameters(getStackParameters(stack, userData, (AwsCredential) stack.getCredential(), stack.getName(), existingVPC)); AmazonCloudFormationClient cloudFormationClient = awsStackUtil.createCloudFormationClient(stack); cloudFormationClient.updateStack(updateStackRequest); List<StackStatus> errorStatuses = Arrays.asList(UPDATE_ROLLBACK_COMPLETE, UPDATE_ROLLBACK_FAILED); CloudFormationStackPollerContext stackPollerContext = new CloudFormationStackPollerContext(cloudFormationClient, UPDATE_COMPLETE, errorStatuses, stack); try { PollingResult pollingResult = stackPollingService.pollWithTimeout(cloudFormationStackStatusChecker, stackPollerContext, POLLING_INTERVAL, INFINITE_ATTEMPTS); if (isExited(pollingResult)) { throw new UpdateFailedException(new IllegalStateException()); } } catch (CloudFormationStackException e) { throw new UpdateFailedException(e); } } @Override public boolean startAll(Stack stack) { return setStackState(stack, false); } @Override public boolean stopAll(Stack stack) { return setStackState(stack, true); } /** * If the AutoScaling group has some suspended scaling policies it causes that the CloudFormation stack delete won't be able to remove the ASG. * In this case the ASG size is reduced to zero and the processes are resumed first. */ @Override public void deleteStack(Stack stack, Credential credential) { MDCBuilder.buildMdcContext(stack); LOGGER.info("Deleting stack: {}", stack.getId()); AwsCredential awsCredential = (AwsCredential) credential; Resource resource = stack.getResourceByType(ResourceType.CLOUDFORMATION_STACK); if (resource != null) { AmazonCloudFormationClient client = awsStackUtil.createCloudFormationClient(Regions.valueOf(stack.getRegion()), awsCredential); String cFStackName = resource.getResourceName(); LOGGER.info("Deleting CloudFormation stack for stack: {} [cf stack id: {}]", stack.getId(), cFStackName); DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(cFStackName); try { client.describeStacks(describeStacksRequest); } catch (AmazonServiceException e) { if (e.getErrorMessage().equals("Stack:" + cFStackName + " does not exist")) { LOGGER.info("AWS CloudFormation stack not found, publishing {} event.", ReactorConfig.DELETE_COMPLETE_EVENT); reactor.notify(ReactorConfig.DELETE_COMPLETE_EVENT, Event.wrap(new StackDeleteComplete(stack.getId()))); return; } else { throw e; } } resumeAutoScalingPolicies(stack, awsCredential); DeleteStackRequest deleteStackRequest = new DeleteStackRequest().withStackName(cFStackName); client.deleteStack(deleteStackRequest); List<StackStatus> errorStatuses = Arrays.asList(DELETE_FAILED); CloudFormationStackPollerContext stackPollerContext = new CloudFormationStackPollerContext(client, DELETE_COMPLETE, errorStatuses, stack); try { PollingResult pollingResult = stackPollingService .pollWithTimeout(cloudFormationStackStatusChecker, stackPollerContext, POLLING_INTERVAL, INFINITE_ATTEMPTS); if (isSuccess(pollingResult)) { LOGGER.info("CloudFormation stack({}) delete completed. Publishing {} event.", cFStackName, ReactorConfig.DELETE_COMPLETE_EVENT); reactor.notify(ReactorConfig.DELETE_COMPLETE_EVENT, Event.wrap(new StackDeleteComplete(stack.getId()))); } } catch (CloudFormationStackException e) { LOGGER.error(String.format("Failed to delete CloudFormation stack: %s, id:%s", cFStackName, stack.getId()), e); stackUpdater.updateStackStatus(stack.getId(), Status.DELETE_FAILED, "Failed to delete stack: " + e.getMessage()); throw new BuildStackFailureException(e); } } else { LOGGER.info("No resource saved for stack, publishing {} event.", ReactorConfig.DELETE_COMPLETE_EVENT); reactor.notify(ReactorConfig.DELETE_COMPLETE_EVENT, Event.wrap(new StackDeleteComplete(stack.getId()))); } } private boolean isExistingVPC(Stack stack) { return stack.getParameters().get("vpcId") != null && stack.getParameters().get("subnetCIDR") != null && stack.getParameters().get("internetGatewayId") != null; } private List<Parameter> getStackParameters(Stack stack, String userData, AwsCredential awsCredential, String stackName, boolean existingVPC) { List<Parameter> parameters = new ArrayList<>(Arrays.asList( new Parameter().withParameterKey("CBUserData").withParameterValue(userData), new Parameter().withParameterKey("StackName").withParameterValue(stackName), new Parameter().withParameterKey("StackOwner").withParameterValue(awsCredential.getRoleArn()), new Parameter().withParameterKey("KeyName").withParameterValue(awsCredential.getKeyPairName()), new Parameter().withParameterKey("AMI").withParameterValue(stack.getImage()), new Parameter().withParameterKey("RootDeviceName").withParameterValue(getRootDeviceName(stack, awsCredential)) )); if (existingVPC) { parameters.add(new Parameter().withParameterKey("VPCId").withParameterValue(stack.getParameters().get("vpcId"))); parameters.add(new Parameter().withParameterKey("SubnetCIDR").withParameterValue(stack.getParameters().get("subnetCIDR"))); parameters.add(new Parameter().withParameterKey("InternetGatewayId").withParameterValue(stack.getParameters().get("internetGatewayId"))); } return parameters; } private void sendUpdatedStackCreateComplete(long stackId, String cFStackName, Set<Resource> resourceSet) { stackUpdater.updateStackCreateComplete(stackId); LOGGER.info("CloudFormation stack({}) creation completed.", cFStackName); LOGGER.info("Publishing {} event.", ReactorConfig.PROVISION_COMPLETE_EVENT); reactor.notify(ReactorConfig.PROVISION_COMPLETE_EVENT, Event.wrap(new ProvisionComplete(CloudPlatform.AWS, stackId, resourceSet))); } private String getRootDeviceName(Stack stack, AwsCredential awsCredential) { AmazonEC2Client ec2Client = awsStackUtil.createEC2Client(Regions.valueOf(stack.getRegion()), awsCredential); DescribeImagesResult images = ec2Client.describeImages(new DescribeImagesRequest().withImageIds(stack.getImage())); Image image = images.getImages().get(0); if (image != null) { return image.getRootDeviceName(); } else { throw new StackCreationFailureException(String.format("Couldn't describe AMI '%s'.", stack.getImage())); } } private boolean setStackState(Stack stack, boolean stopped) { MDCBuilder.buildMdcContext(stack); boolean result = true; Regions region = Regions.valueOf(stack.getRegion()); AwsCredential credential = (AwsCredential) stack.getCredential(); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(region, credential); AmazonEC2Client amazonEC2Client = awsStackUtil.createEC2Client(region, credential); for (InstanceGroup instanceGroup : stack.getInstanceGroups()) { String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, instanceGroup.getGroupName()); Collection<String> instances = new ArrayList<>(); for (InstanceMetaData instance : instanceGroup.getInstanceMetaData()) { if (instance.getInstanceGroup().getGroupName().equals(instanceGroup.getGroupName())) { instances.add(instance.getInstanceId()); } } try { if (stopped) { amazonASClient.suspendProcesses(new SuspendProcessesRequest().withAutoScalingGroupName(asGroupName)); amazonEC2Client.stopInstances(new StopInstancesRequest().withInstanceIds(instances)); awsPollingService.pollWithTimeout( new AwsInstanceStatusCheckerTask(), new AwsInstances(stack, amazonEC2Client, new ArrayList(instances), "Stopped"), AmbariClusterConnector.POLLING_INTERVAL, AmbariClusterConnector.MAX_ATTEMPTS_FOR_AMBARI_OPS); } else { amazonEC2Client.startInstances(new StartInstancesRequest().withInstanceIds(instances)); PollingResult pollingResult = awsPollingService.pollWithTimeout( awsInstanceStatusCheckerTask, new AwsInstances(stack, amazonEC2Client, new ArrayList(instances), "Running"), AmbariClusterConnector.POLLING_INTERVAL, AmbariClusterConnector.MAX_ATTEMPTS_FOR_AMBARI_OPS); if (isSuccess(pollingResult)) { amazonASClient.resumeProcesses(new ResumeProcessesRequest().withAutoScalingGroupName(asGroupName)); updateInstanceMetadata(stack, amazonEC2Client, stack.getRunningInstanceMetaData(), instances); } } } catch (Exception e) { LOGGER.error(String.format("Failed to %s AWS instances on stack: %s", stopped ? "stop" : "start", stack.getId()), e); result = false; } } return result; } private void updateInstanceMetadata(Stack stack, AmazonEC2Client amazonEC2Client, Set<InstanceMetaData> instanceMetaData, Collection<String> instances) { MDCBuilder.buildMdcContext(stack); DescribeInstancesResult describeResult = amazonEC2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(instances)); for (Reservation reservation : describeResult.getReservations()) { for (Instance instance : reservation.getInstances()) { for (InstanceMetaData metaData : instanceMetaData) { if (metaData.getInstanceId().equals(instance.getInstanceId())) { String publicDnsName = instance.getPublicDnsName(); if (metaData.getAmbariServer()) { stack.setAmbariIp(publicDnsName); Cluster cluster = clusterRepository.findOneWithLists(stack.getCluster().getId()); stack.setCluster(cluster); stackRepository.save(stack); } metaData.setPublicIp(publicDnsName); instanceMetaDataRepository.save(metaData); break; } } } } } private void resumeAutoScalingPolicies(Stack stack, AwsCredential awsCredential) { for (InstanceGroup instanceGroup : stack.getInstanceGroups()) { try { String asGroupName = cfStackUtil.getAutoscalingGroupName(stack, instanceGroup.getGroupName()); AmazonAutoScalingClient amazonASClient = awsStackUtil.createAutoScalingClient(Regions.valueOf(stack.getRegion()), awsCredential); List<AutoScalingGroup> asGroups = amazonASClient.describeAutoScalingGroups(new DescribeAutoScalingGroupsRequest() .withAutoScalingGroupNames(asGroupName)).getAutoScalingGroups(); if (!asGroups.isEmpty()) { if (!asGroups.get(0).getSuspendedProcesses().isEmpty()) { amazonASClient.updateAutoScalingGroup(new UpdateAutoScalingGroupRequest() .withAutoScalingGroupName(asGroupName) .withMinSize(0) .withDesiredCapacity(0)); amazonASClient.resumeProcesses(new ResumeProcessesRequest().withAutoScalingGroupName(asGroupName)); } } } catch (AmazonServiceException e) { if (e.getErrorMessage().matches("Resource.*does not exist for stack.*")) { MDCBuilder.buildMdcContext(stack); LOGGER.info(e.getErrorMessage()); } else { throw e; } } } } @Override public void rollback(Stack stack, Set<Resource> resourceSet) { return; } @Override public CloudPlatform getCloudPlatform() { return CloudPlatform.AWS; } protected CreateStackRequest createStackRequest() { return new CreateStackRequest(); } }
CLOUD-470 use ip address instead of dns name when restarting instances
src/main/java/com/sequenceiq/cloudbreak/service/stack/connector/aws/AwsConnector.java
CLOUD-470 use ip address instead of dns name when restarting instances
<ide><path>rc/main/java/com/sequenceiq/cloudbreak/service/stack/connector/aws/AwsConnector.java <ide> for (Instance instance : reservation.getInstances()) { <ide> for (InstanceMetaData metaData : instanceMetaData) { <ide> if (metaData.getInstanceId().equals(instance.getInstanceId())) { <del> String publicDnsName = instance.getPublicDnsName(); <add> String publicIp = instance.getPublicIpAddress(); <ide> if (metaData.getAmbariServer()) { <del> stack.setAmbariIp(publicDnsName); <add> stack.setAmbariIp(publicIp); <ide> Cluster cluster = clusterRepository.findOneWithLists(stack.getCluster().getId()); <ide> stack.setCluster(cluster); <ide> stackRepository.save(stack); <ide> } <del> metaData.setPublicIp(publicDnsName); <add> metaData.setPublicIp(publicIp); <ide> instanceMetaDataRepository.save(metaData); <ide> break; <ide> }
Java
apache-2.0
e2a6de00f1f8c3d116150e01b56fb0eee8c27955
0
whumph/sakai,pushyamig/sakai,zqian/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,whumph/sakai,hackbuteer59/sakai,joserabal/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,noondaysun/sakai,frasese/sakai,kwedoff1/sakai,wfuedu/sakai,udayg/sakai,lorenamgUMU/sakai,joserabal/sakai,kingmook/sakai,surya-janani/sakai,colczr/sakai,clhedrick/sakai,buckett/sakai-gitflow,puramshetty/sakai,clhedrick/sakai,colczr/sakai,liubo404/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,colczr/sakai,bzhouduke123/sakai,kingmook/sakai,Fudan-University/sakai,zqian/sakai,udayg/sakai,udayg/sakai,hackbuteer59/sakai,ktakacs/sakai,rodriguezdevera/sakai,frasese/sakai,noondaysun/sakai,noondaysun/sakai,udayg/sakai,joserabal/sakai,liubo404/sakai,joserabal/sakai,ktakacs/sakai,buckett/sakai-gitflow,clhedrick/sakai,rodriguezdevera/sakai,liubo404/sakai,tl-its-umich-edu/sakai,conder/sakai,willkara/sakai,bkirschn/sakai,bkirschn/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,OpenCollabZA/sakai,kwedoff1/sakai,bzhouduke123/sakai,introp-software/sakai,ouit0408/sakai,frasese/sakai,puramshetty/sakai,ouit0408/sakai,conder/sakai,whumph/sakai,joserabal/sakai,liubo404/sakai,clhedrick/sakai,bzhouduke123/sakai,conder/sakai,OpenCollabZA/sakai,surya-janani/sakai,zqian/sakai,colczr/sakai,kingmook/sakai,joserabal/sakai,Fudan-University/sakai,buckett/sakai-gitflow,willkara/sakai,willkara/sakai,puramshetty/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,tl-its-umich-edu/sakai,udayg/sakai,conder/sakai,Fudan-University/sakai,puramshetty/sakai,surya-janani/sakai,conder/sakai,liubo404/sakai,kwedoff1/sakai,introp-software/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,ktakacs/sakai,frasese/sakai,buckett/sakai-gitflow,noondaysun/sakai,Fudan-University/sakai,ouit0408/sakai,rodriguezdevera/sakai,zqian/sakai,bkirschn/sakai,lorenamgUMU/sakai,wfuedu/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,kwedoff1/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,introp-software/sakai,lorenamgUMU/sakai,willkara/sakai,frasese/sakai,udayg/sakai,kingmook/sakai,willkara/sakai,introp-software/sakai,bkirschn/sakai,hackbuteer59/sakai,kwedoff1/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,conder/sakai,zqian/sakai,kwedoff1/sakai,noondaysun/sakai,ouit0408/sakai,ouit0408/sakai,surya-janani/sakai,OpenCollabZA/sakai,kwedoff1/sakai,liubo404/sakai,frasese/sakai,surya-janani/sakai,ktakacs/sakai,noondaysun/sakai,udayg/sakai,willkara/sakai,kingmook/sakai,whumph/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,whumph/sakai,pushyamig/sakai,rodriguezdevera/sakai,joserabal/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,introp-software/sakai,lorenamgUMU/sakai,wfuedu/sakai,bzhouduke123/sakai,colczr/sakai,pushyamig/sakai,wfuedu/sakai,hackbuteer59/sakai,colczr/sakai,introp-software/sakai,hackbuteer59/sakai,wfuedu/sakai,hackbuteer59/sakai,bzhouduke123/sakai,puramshetty/sakai,colczr/sakai,pushyamig/sakai,buckett/sakai-gitflow,bkirschn/sakai,bzhouduke123/sakai,Fudan-University/sakai,ktakacs/sakai,OpenCollabZA/sakai,whumph/sakai,bkirschn/sakai,ouit0408/sakai,liubo404/sakai,willkara/sakai,zqian/sakai,surya-janani/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,introp-software/sakai,introp-software/sakai,Fudan-University/sakai,joserabal/sakai,wfuedu/sakai,pushyamig/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,kingmook/sakai,zqian/sakai,buckett/sakai-gitflow,zqian/sakai,colczr/sakai,whumph/sakai,pushyamig/sakai,ktakacs/sakai,ktakacs/sakai,frasese/sakai,OpenCollabZA/sakai,pushyamig/sakai,frasese/sakai,liubo404/sakai,puramshetty/sakai,noondaysun/sakai,udayg/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,kwedoff1/sakai,buckett/sakai-gitflow,conder/sakai,bkirschn/sakai,puramshetty/sakai,kingmook/sakai,conder/sakai,surya-janani/sakai,bkirschn/sakai,hackbuteer59/sakai,bzhouduke123/sakai,clhedrick/sakai,surya-janani/sakai
user/user-impl/integration-test/src/test/java/org/sakaiproject/user/impl/UserDirectoryServiceIntegrationTest.java
/********************************************************************************** * * $Id$ * *********************************************************************************** * * Copyright (c) 2007 The Regents of the University of California * * 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.user.impl; import java.util.Collection; import junit.extensions.TestSetup; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.test.SakaiTestBase; import org.sakaiproject.user.api.AuthenticatedUserProvider; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserDirectoryProvider; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserFactory; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.util.StringUtil; /** * */ public class UserDirectoryServiceIntegrationTest extends SakaiTestBase { private static Log log = LogFactory.getLog(UserDirectoryServiceIntegrationTest.class); private static String[] USER_DATA_IN_LOCAL_STORAGE = {"LocalOnlyUser", null, "First", "Last", "local@edu", "localpassword"}; private static String[] USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT = {"LocalOnlyButHopefulUser", null, "First", "Last", "localhopeful@edu", "localpassword"}; private static String[] USER_DATA_IN_PROVIDER = {"ProviderOnlyUser", null, "First", "Last", "provider@edu", "providerpassword"}; private static String[] USER_DATA_FROM_PROVIDER_AUTHN = {"ProviderAuthnUser", null, "First", "Last", "providerauthn@edu", "providerauthnpassword"}; private static String[] USER_DATA_UPDATED_BY_PROVIDER = {"LocalFirstUser", null, "First", "Last", "localfirst@edu", "localfirstpassword"}; private static String AUTHN_ID_NOT_PROVIDER_EID = "ProviderAuthnUserIsNotEid"; private static String AUTHN_ID_NOT_LOCAL_EID = "LocalAuthnUserIsNotEid"; private static String EMAIL_FOR_UPDATED_USER_EQUAL_IDS = "localsecond@edu"; private static String EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS = "localthird@edu"; private UserDirectoryService userDirectoryService; public static Test suite() { TestSetup setup = new TestSetup(new TestSuite(UserDirectoryServiceIntegrationTest.class)) { protected void setUp() throws Exception { log.debug("starting setup"); oneTimeSetup(); log.debug("finished setup"); } protected void tearDown() throws Exception { oneTimeTearDown(); } }; return setup; } public void setUp() throws Exception { log.debug("Setting up UserDirectoryServiceIntegrationTest"); userDirectoryService = (UserDirectoryService)getService(UserDirectoryService.class.getName()); log.debug("userDirectoryService=" + userDirectoryService + " for name=" + UserDirectoryService.class.getName()); TestProvider userDirectoryProvider = new TestProvider(); // Now for the tricky part.... This is just a workaround until we can make it // easier to load sakai.properties for specific integration tests. DbUserService dbUserService = (DbUserService)userDirectoryService; dbUserService.setProvider(userDirectoryProvider); dbUserService.setCacheMinutes("15"); dbUserService.setCacheCleanerMinutes("15"); userDirectoryProvider.setUserFactory(dbUserService); User localUser = userDirectoryService.addUser(USER_DATA_IN_LOCAL_STORAGE[1], USER_DATA_IN_LOCAL_STORAGE[0], USER_DATA_IN_LOCAL_STORAGE[2], USER_DATA_IN_LOCAL_STORAGE[3], USER_DATA_IN_LOCAL_STORAGE[4], USER_DATA_IN_LOCAL_STORAGE[5], null, null); log.debug("Created local user eid=" + localUser.getEid() + ", id=" + localUser.getId()); USER_DATA_IN_LOCAL_STORAGE[1] = localUser.getId(); localUser = userDirectoryService.addUser(USER_DATA_UPDATED_BY_PROVIDER[1], USER_DATA_UPDATED_BY_PROVIDER[0], USER_DATA_UPDATED_BY_PROVIDER[2], USER_DATA_UPDATED_BY_PROVIDER[3], USER_DATA_UPDATED_BY_PROVIDER[4], USER_DATA_UPDATED_BY_PROVIDER[5], null, null); log.debug("Created local user eid=" + localUser.getEid() + ", id=" + localUser.getId()); USER_DATA_UPDATED_BY_PROVIDER[1] = localUser.getId(); localUser = userDirectoryService.addUser(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[1], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[0], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[2], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[3], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[4], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[5], null, null); log.debug("Created local user eid=" + localUser.getEid() + ", id=" + localUser.getId()); USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[1] = localUser.getId(); } /** * Because a lot of what we have to test in the legacy user provider service involves * irreversible side-effects (such as use of in-memory cache), we can't put much * trust in the "tearDown" approach. Instead, we rely on the "one long * complex test method" approach. */ public void tearDown() throws Exception { } public void testGetAndAuthUser() throws Exception { User user = userDirectoryService.getUserByEid(USER_DATA_IN_LOCAL_STORAGE[0]); if (log.isDebugEnabled()) log.debug("Got local user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_LOCAL_STORAGE[4])); user = userDirectoryService.getUserByEid(USER_DATA_IN_PROVIDER[0]); if (log.isDebugEnabled()) log.debug("Got provided user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_PROVIDER[4])); // Test legacy getUser(id) path; user = userDirectoryService.getUser(USER_DATA_UPDATED_BY_PROVIDER[1]); if (log.isDebugEnabled()) log.debug("Got provided user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_UPDATED_BY_PROVIDER[4])); // Default Base authentication of a locally stored user. user = userDirectoryService.authenticate(USER_DATA_IN_LOCAL_STORAGE[0], USER_DATA_IN_LOCAL_STORAGE[5]); if (log.isDebugEnabled()) log.debug("Locally authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_LOCAL_STORAGE[4])); // Try (but fall through) provided authentication of a locally stored user. user = userDirectoryService.authenticate(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[0], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[5]); if (log.isDebugEnabled()) log.debug("Locally authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[4])); // Authn-provided update of already loaded locally stored user, with // Authentication ID == EID. (In other words, test the current code // path for authenticate-first update-after.) user = userDirectoryService.authenticate(USER_DATA_UPDATED_BY_PROVIDER[0], USER_DATA_UPDATED_BY_PROVIDER[5]); if (log.isDebugEnabled()) log.debug("Provider authenticated local user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_EQUAL_IDS)); user = userDirectoryService.getUserByEid(USER_DATA_UPDATED_BY_PROVIDER[0]); if (log.isDebugEnabled()) log.debug("On re-get local user email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_EQUAL_IDS)); // Authn-provided user where Authentication ID != EID. user = userDirectoryService.authenticate(AUTHN_ID_NOT_PROVIDER_EID, USER_DATA_FROM_PROVIDER_AUTHN[5]); if (log.isDebugEnabled()) log.debug("Provider authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_FROM_PROVIDER_AUTHN[4])); // Remember the assigned ID for the next go round below. String authnProvidedId = StringUtil.trimToNull(user.getId()); Assert.assertTrue(authnProvidedId != null); // Authn-provided update of already loaded locally stored user, with // Authentication ID != EID. user = userDirectoryService.authenticate(AUTHN_ID_NOT_LOCAL_EID, USER_DATA_UPDATED_BY_PROVIDER[5]); if (log.isDebugEnabled()) log.debug("Provider non-EID authenticated local user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS)); user = userDirectoryService.getUserByEid(USER_DATA_UPDATED_BY_PROVIDER[0]); if (log.isDebugEnabled()) log.debug("On re-get local user email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS)); // Authn-provided user where Authentication ID != EID. user = userDirectoryService.authenticate(AUTHN_ID_NOT_PROVIDER_EID, USER_DATA_FROM_PROVIDER_AUTHN[5]); if (log.isDebugEnabled()) log.debug("Provider authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(user.getEmail().equals(USER_DATA_FROM_PROVIDER_AUTHN[4])); // Second go-round for authn-provided user where Authentication ID != EID, // to make sure the ID isn't lost. user = userDirectoryService.authenticate(AUTHN_ID_NOT_PROVIDER_EID, USER_DATA_FROM_PROVIDER_AUTHN[5]); if (log.isDebugEnabled()) log.debug("Provider authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); Assert.assertTrue(authnProvidedId.equals(user.getId())); // Make sure nothing horrible happens when there's no such user anywhere. user = userDirectoryService.authenticate("NoSuchUser", "NoSuchPassword"); Assert.assertTrue(user == null); } private static boolean loadProvidedUserData(String eid, UserEdit toUser) { String[] fromData = {}; if (eid.equalsIgnoreCase(USER_DATA_IN_PROVIDER[0])) { fromData = USER_DATA_IN_PROVIDER; } else if (eid.equalsIgnoreCase(USER_DATA_FROM_PROVIDER_AUTHN[0])) { fromData = USER_DATA_FROM_PROVIDER_AUTHN; } else { return false; } toUser.setEid(fromData[0]); toUser.setFirstName(fromData[2]); toUser.setLastName(fromData[3]); toUser.setEmail(fromData[4]); toUser.setPassword(fromData[5]); return true; } public class TestProvider implements UserDirectoryProvider, AuthenticatedUserProvider { private UserFactory userFactory; public boolean authenticateUser(String authenticationId, UserEdit user, String password) { if (log.isDebugEnabled()) { log.debug("provider authenticateUser authenticationId=" + authenticationId + ", user=" + user); if (user != null) log.debug("provider authenticateUser authenticationId=" + authenticationId + ", user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); } // This should never be called since we implement the new interface. throw new RuntimeException("authenticateUser unexpectedly called"); } public boolean authenticateWithProviderFirst(String eid) { return (!eid.equalsIgnoreCase(USER_DATA_IN_LOCAL_STORAGE[0])); } /* * AFAIK this is never used by anything and should be removed from the interface.... */ // public boolean createUserRecord(String eid) { // if (log.isWarnEnabled()) log.warn("provider createUserRecord called unexpectedly!"); // return false; // } /** * AFAIK this is never used by anything and should be removed from the interface.... */ public void destroyAuthentication() { } public boolean findUserByEmail(UserEdit edit, String email) { // TODO Auto-generated method stub return false; } public boolean getUser(UserEdit user) { if (log.isDebugEnabled()) log.debug("provider getUser eid=" + user.getEid()); return loadProvidedUserData(user.getEid(), user); } public void getUsers(Collection users) { // TODO Auto-generated method stub } public boolean updateUserAfterAuthentication() { return true; } /** * AFAIK this is never used by anything and should be removed from the interface.... */ public boolean userExists(String eid) { // TODO Auto-generated method stub return false; } public UserEdit getAuthenticatedUser(String authenticationId, String password) { String eid; String revisedEmail = null; if (log.isDebugEnabled()) log.debug("provider getAuthenticatedUser authenticationId=" + authenticationId); // Make sure the service obeyed our authenticateWithProviderFirst directive. Assert.assertFalse(authenticationId.equalsIgnoreCase(USER_DATA_IN_LOCAL_STORAGE[0])); // The "local user" case in which authentication should really be handled by the // base service rather than the provider, but the provider wasn't able to predict that. if (authenticationId.equalsIgnoreCase(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[0])) { return null; } // For testing purposes, we have a case where the authentication // ID equals the EID. if (authenticationId.equalsIgnoreCase(USER_DATA_UPDATED_BY_PROVIDER[0])) { eid = authenticationId; revisedEmail = EMAIL_FOR_UPDATED_USER_EQUAL_IDS; } else if (authenticationId.equalsIgnoreCase(AUTHN_ID_NOT_LOCAL_EID)) { eid = USER_DATA_UPDATED_BY_PROVIDER[0]; revisedEmail = EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS; } else if (authenticationId.equalsIgnoreCase(AUTHN_ID_NOT_PROVIDER_EID)) { eid = USER_DATA_FROM_PROVIDER_AUTHN[0]; } else { return null; } UserEdit user = null; if (eid.equalsIgnoreCase(USER_DATA_UPDATED_BY_PROVIDER[0])) { try { user = (UserEdit)userDirectoryService.getUserByEid(eid); } catch (UserNotDefinedException e) { if (log.isDebugEnabled()) log.debug("provider did not find user with eid=" + eid); return null; } } else if (eid.equalsIgnoreCase(USER_DATA_FROM_PROVIDER_AUTHN[0])) { // Mimic the case where we have user data at hand via something // like LDAP. user = userFactory.newUser(); loadProvidedUserData(eid, user); } if (user.getEid().equalsIgnoreCase(USER_DATA_UPDATED_BY_PROVIDER[0])) { user.setEmail(revisedEmail); } return user; } public void setUserFactory(UserFactory userFactory) { this.userFactory = userFactory; } } }
SAK-9983 Remove anticipatory integration test merged in by mistake at rev 31172 git-svn-id: 470921d30149416e94c2486af53d02cfc164742e@32094 66ffb92e-73f9-0310-93c1-f5514f145a0a
user/user-impl/integration-test/src/test/java/org/sakaiproject/user/impl/UserDirectoryServiceIntegrationTest.java
SAK-9983 Remove anticipatory integration test merged in by mistake at rev 31172
<ide><path>ser/user-impl/integration-test/src/test/java/org/sakaiproject/user/impl/UserDirectoryServiceIntegrationTest.java <del>/********************************************************************************** <del>* <del>* $Id$ <del>* <del>*********************************************************************************** <del>* <del>* Copyright (c) 2007 The Regents of the University of California <del>* <del>* Licensed under the Educational Community License, Version 1.0 (the "License"); <del>* you may not use this file except in compliance with the License. <del>* You may obtain a copy of the License at <del>* <del>* http://www.opensource.org/licenses/ecl1.php <del>* <del>* Unless required by applicable law or agreed to in writing, software <del>* distributed under the License is distributed on an "AS IS" BASIS, <del>* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del>* See the License for the specific language governing permissions and <del>* limitations under the License. <del>* <del>**********************************************************************************/ <del> <del>package org.sakaiproject.user.impl; <del> <del>import java.util.Collection; <del> <del>import junit.extensions.TestSetup; <del>import junit.framework.Assert; <del>import junit.framework.Test; <del>import junit.framework.TestSuite; <del> <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <del>import org.sakaiproject.test.SakaiTestBase; <del>import org.sakaiproject.user.api.AuthenticatedUserProvider; <del>import org.sakaiproject.user.api.User; <del>import org.sakaiproject.user.api.UserDirectoryProvider; <del>import org.sakaiproject.user.api.UserDirectoryService; <del>import org.sakaiproject.user.api.UserEdit; <del>import org.sakaiproject.user.api.UserFactory; <del>import org.sakaiproject.user.api.UserNotDefinedException; <del>import org.sakaiproject.util.StringUtil; <del> <del>/** <del> * <del> */ <del>public class UserDirectoryServiceIntegrationTest extends SakaiTestBase { <del> private static Log log = LogFactory.getLog(UserDirectoryServiceIntegrationTest.class); <del> private static String[] USER_DATA_IN_LOCAL_STORAGE = {"LocalOnlyUser", null, "First", "Last", "local@edu", "localpassword"}; <del> private static String[] USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT = {"LocalOnlyButHopefulUser", null, "First", "Last", "localhopeful@edu", "localpassword"}; <del> private static String[] USER_DATA_IN_PROVIDER = {"ProviderOnlyUser", null, "First", "Last", "provider@edu", "providerpassword"}; <del> private static String[] USER_DATA_FROM_PROVIDER_AUTHN = {"ProviderAuthnUser", null, "First", "Last", "providerauthn@edu", "providerauthnpassword"}; <del> private static String[] USER_DATA_UPDATED_BY_PROVIDER = {"LocalFirstUser", null, "First", "Last", "localfirst@edu", "localfirstpassword"}; <del> private static String AUTHN_ID_NOT_PROVIDER_EID = "ProviderAuthnUserIsNotEid"; <del> private static String AUTHN_ID_NOT_LOCAL_EID = "LocalAuthnUserIsNotEid"; <del> private static String EMAIL_FOR_UPDATED_USER_EQUAL_IDS = "localsecond@edu"; <del> private static String EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS = "localthird@edu"; <del> <del> private UserDirectoryService userDirectoryService; <del> <del> public static Test suite() { <del> TestSetup setup = new TestSetup(new TestSuite(UserDirectoryServiceIntegrationTest.class)) { <del> protected void setUp() throws Exception { <del> log.debug("starting setup"); <del> oneTimeSetup(); <del> log.debug("finished setup"); <del> } <del> protected void tearDown() throws Exception { <del> oneTimeTearDown(); <del> } <del> }; <del> return setup; <del> } <del> <del> public void setUp() throws Exception { <del> log.debug("Setting up UserDirectoryServiceIntegrationTest"); <del> <del> userDirectoryService = (UserDirectoryService)getService(UserDirectoryService.class.getName()); <del> log.debug("userDirectoryService=" + userDirectoryService + " for name=" + UserDirectoryService.class.getName()); <del> <del> TestProvider userDirectoryProvider = new TestProvider(); <del> <del> // Now for the tricky part.... This is just a workaround until we can make it <del> // easier to load sakai.properties for specific integration tests. <del> DbUserService dbUserService = (DbUserService)userDirectoryService; <del> dbUserService.setProvider(userDirectoryProvider); <del> dbUserService.setCacheMinutes("15"); <del> dbUserService.setCacheCleanerMinutes("15"); <del> userDirectoryProvider.setUserFactory(dbUserService); <del> <del> User localUser = userDirectoryService.addUser(USER_DATA_IN_LOCAL_STORAGE[1], USER_DATA_IN_LOCAL_STORAGE[0], <del> USER_DATA_IN_LOCAL_STORAGE[2], USER_DATA_IN_LOCAL_STORAGE[3], USER_DATA_IN_LOCAL_STORAGE[4], USER_DATA_IN_LOCAL_STORAGE[5], null, null); <del> log.debug("Created local user eid=" + localUser.getEid() + ", id=" + localUser.getId()); <del> USER_DATA_IN_LOCAL_STORAGE[1] = localUser.getId(); <del> localUser = userDirectoryService.addUser(USER_DATA_UPDATED_BY_PROVIDER[1], USER_DATA_UPDATED_BY_PROVIDER[0], <del> USER_DATA_UPDATED_BY_PROVIDER[2], USER_DATA_UPDATED_BY_PROVIDER[3], USER_DATA_UPDATED_BY_PROVIDER[4], USER_DATA_UPDATED_BY_PROVIDER[5], null, null); <del> log.debug("Created local user eid=" + localUser.getEid() + ", id=" + localUser.getId()); <del> USER_DATA_UPDATED_BY_PROVIDER[1] = localUser.getId(); <del> localUser = userDirectoryService.addUser(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[1], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[0], <del> USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[2], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[3], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[4], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[5], null, null); <del> log.debug("Created local user eid=" + localUser.getEid() + ", id=" + localUser.getId()); <del> USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[1] = localUser.getId(); <del> } <del> <del> /** <del> * Because a lot of what we have to test in the legacy user provider service involves <del> * irreversible side-effects (such as use of in-memory cache), we can't put much <del> * trust in the "tearDown" approach. Instead, we rely on the "one long <del> * complex test method" approach. <del> */ <del> public void tearDown() throws Exception { <del> } <del> <del> public void testGetAndAuthUser() throws Exception { <del> User user = userDirectoryService.getUserByEid(USER_DATA_IN_LOCAL_STORAGE[0]); <del> if (log.isDebugEnabled()) log.debug("Got local user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_LOCAL_STORAGE[4])); <del> <del> user = userDirectoryService.getUserByEid(USER_DATA_IN_PROVIDER[0]); <del> if (log.isDebugEnabled()) log.debug("Got provided user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_PROVIDER[4])); <del> <del> // Test legacy getUser(id) path; <del> user = userDirectoryService.getUser(USER_DATA_UPDATED_BY_PROVIDER[1]); <del> if (log.isDebugEnabled()) log.debug("Got provided user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_UPDATED_BY_PROVIDER[4])); <del> <del> // Default Base authentication of a locally stored user. <del> user = userDirectoryService.authenticate(USER_DATA_IN_LOCAL_STORAGE[0], USER_DATA_IN_LOCAL_STORAGE[5]); <del> if (log.isDebugEnabled()) log.debug("Locally authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_LOCAL_STORAGE[4])); <del> <del> // Try (but fall through) provided authentication of a locally stored user. <del> user = userDirectoryService.authenticate(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[0], USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[5]); <del> if (log.isDebugEnabled()) log.debug("Locally authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[4])); <del> <del> // Authn-provided update of already loaded locally stored user, with <del> // Authentication ID == EID. (In other words, test the current code <del> // path for authenticate-first update-after.) <del> user = userDirectoryService.authenticate(USER_DATA_UPDATED_BY_PROVIDER[0], USER_DATA_UPDATED_BY_PROVIDER[5]); <del> if (log.isDebugEnabled()) log.debug("Provider authenticated local user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_EQUAL_IDS)); <del> user = userDirectoryService.getUserByEid(USER_DATA_UPDATED_BY_PROVIDER[0]); <del> if (log.isDebugEnabled()) log.debug("On re-get local user email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_EQUAL_IDS)); <del> <del> // Authn-provided user where Authentication ID != EID. <del> user = userDirectoryService.authenticate(AUTHN_ID_NOT_PROVIDER_EID, USER_DATA_FROM_PROVIDER_AUTHN[5]); <del> if (log.isDebugEnabled()) log.debug("Provider authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_FROM_PROVIDER_AUTHN[4])); <del> <del> // Remember the assigned ID for the next go round below. <del> String authnProvidedId = StringUtil.trimToNull(user.getId()); <del> Assert.assertTrue(authnProvidedId != null); <del> <del> // Authn-provided update of already loaded locally stored user, with <del> // Authentication ID != EID. <del> user = userDirectoryService.authenticate(AUTHN_ID_NOT_LOCAL_EID, USER_DATA_UPDATED_BY_PROVIDER[5]); <del> if (log.isDebugEnabled()) log.debug("Provider non-EID authenticated local user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS)); <del> user = userDirectoryService.getUserByEid(USER_DATA_UPDATED_BY_PROVIDER[0]); <del> if (log.isDebugEnabled()) log.debug("On re-get local user email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS)); <del> <del> // Authn-provided user where Authentication ID != EID. <del> user = userDirectoryService.authenticate(AUTHN_ID_NOT_PROVIDER_EID, USER_DATA_FROM_PROVIDER_AUTHN[5]); <del> if (log.isDebugEnabled()) log.debug("Provider authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(user.getEmail().equals(USER_DATA_FROM_PROVIDER_AUTHN[4])); <del> <del> // Second go-round for authn-provided user where Authentication ID != EID, <del> // to make sure the ID isn't lost. <del> user = userDirectoryService.authenticate(AUTHN_ID_NOT_PROVIDER_EID, USER_DATA_FROM_PROVIDER_AUTHN[5]); <del> if (log.isDebugEnabled()) log.debug("Provider authenticated user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> Assert.assertTrue(authnProvidedId.equals(user.getId())); <del> <del> // Make sure nothing horrible happens when there's no such user anywhere. <del> user = userDirectoryService.authenticate("NoSuchUser", "NoSuchPassword"); <del> Assert.assertTrue(user == null); <del> } <del> <del> private static boolean loadProvidedUserData(String eid, UserEdit toUser) { <del> String[] fromData = {}; <del> if (eid.equalsIgnoreCase(USER_DATA_IN_PROVIDER[0])) { <del> fromData = USER_DATA_IN_PROVIDER; <del> } else if (eid.equalsIgnoreCase(USER_DATA_FROM_PROVIDER_AUTHN[0])) { <del> fromData = USER_DATA_FROM_PROVIDER_AUTHN; <del> } else { <del> return false; <del> } <del> <del> toUser.setEid(fromData[0]); <del> toUser.setFirstName(fromData[2]); <del> toUser.setLastName(fromData[3]); <del> toUser.setEmail(fromData[4]); <del> toUser.setPassword(fromData[5]); <del> return true; <del> } <del> <del> public class TestProvider implements UserDirectoryProvider, AuthenticatedUserProvider { <del> private UserFactory userFactory; <del> <del> public boolean authenticateUser(String authenticationId, UserEdit user, String password) { <del> if (log.isDebugEnabled()) { <del> log.debug("provider authenticateUser authenticationId=" + authenticationId + ", user=" + user); <del> if (user != null) log.debug("provider authenticateUser authenticationId=" + authenticationId + ", user eid=" + user.getEid() + ", id=" + user.getId() + ", email=" + user.getEmail()); <del> } <del> <del> // This should never be called since we implement the new interface. <del> throw new RuntimeException("authenticateUser unexpectedly called"); <del> } <del> <del> public boolean authenticateWithProviderFirst(String eid) { <del> return (!eid.equalsIgnoreCase(USER_DATA_IN_LOCAL_STORAGE[0])); <del> } <del> <del> /* <del> * AFAIK this is never used by anything and should be removed from the interface.... <del> */ <del>// public boolean createUserRecord(String eid) { <del>// if (log.isWarnEnabled()) log.warn("provider createUserRecord called unexpectedly!"); <del>// return false; <del>// } <del> <del> /** <del> * AFAIK this is never used by anything and should be removed from the interface.... <del> */ <del> public void destroyAuthentication() { <del> } <del> <del> public boolean findUserByEmail(UserEdit edit, String email) { <del> // TODO Auto-generated method stub <del> return false; <del> } <del> <del> public boolean getUser(UserEdit user) { <del> if (log.isDebugEnabled()) log.debug("provider getUser eid=" + user.getEid()); <del> return loadProvidedUserData(user.getEid(), user); <del> } <del> <del> public void getUsers(Collection users) { <del> // TODO Auto-generated method stub <del> <del> } <del> <del> public boolean updateUserAfterAuthentication() { <del> return true; <del> } <del> <del> /** <del> * AFAIK this is never used by anything and should be removed from the interface.... <del> */ <del> public boolean userExists(String eid) { <del> // TODO Auto-generated method stub <del> return false; <del> } <del> <del> public UserEdit getAuthenticatedUser(String authenticationId, String password) { <del> String eid; <del> String revisedEmail = null; <del> <del> if (log.isDebugEnabled()) log.debug("provider getAuthenticatedUser authenticationId=" + authenticationId); <del> <del> // Make sure the service obeyed our authenticateWithProviderFirst directive. <del> Assert.assertFalse(authenticationId.equalsIgnoreCase(USER_DATA_IN_LOCAL_STORAGE[0])); <del> <del> // The "local user" case in which authentication should really be handled by the <del> // base service rather than the provider, but the provider wasn't able to predict that. <del> if (authenticationId.equalsIgnoreCase(USER_DATA_IN_LOCAL_STORAGE_WITH_AUTHN_ATTEMPT[0])) { <del> return null; <del> } <del> <del> // For testing purposes, we have a case where the authentication <del> // ID equals the EID. <del> if (authenticationId.equalsIgnoreCase(USER_DATA_UPDATED_BY_PROVIDER[0])) { <del> eid = authenticationId; <del> revisedEmail = EMAIL_FOR_UPDATED_USER_EQUAL_IDS; <del> } else if (authenticationId.equalsIgnoreCase(AUTHN_ID_NOT_LOCAL_EID)) { <del> eid = USER_DATA_UPDATED_BY_PROVIDER[0]; <del> revisedEmail = EMAIL_FOR_UPDATED_USER_UNEQUAL_IDS; <del> } else if (authenticationId.equalsIgnoreCase(AUTHN_ID_NOT_PROVIDER_EID)) { <del> eid = USER_DATA_FROM_PROVIDER_AUTHN[0]; <del> } else { <del> return null; <del> } <del> <del> UserEdit user = null; <del> if (eid.equalsIgnoreCase(USER_DATA_UPDATED_BY_PROVIDER[0])) { <del> try { <del> user = (UserEdit)userDirectoryService.getUserByEid(eid); <del> } catch (UserNotDefinedException e) { <del> if (log.isDebugEnabled()) log.debug("provider did not find user with eid=" + eid); <del> return null; <del> } <del> } else if (eid.equalsIgnoreCase(USER_DATA_FROM_PROVIDER_AUTHN[0])) { <del> // Mimic the case where we have user data at hand via something <del> // like LDAP. <del> user = userFactory.newUser(); <del> loadProvidedUserData(eid, user); <del> } <del> <del> if (user.getEid().equalsIgnoreCase(USER_DATA_UPDATED_BY_PROVIDER[0])) { <del> user.setEmail(revisedEmail); <del> } <del> <del> return user; <del> } <del> <del> public void setUserFactory(UserFactory userFactory) { <del> this.userFactory = userFactory; <del> } <del> } <del> <del>}
Java
agpl-3.0
7afa613b42d0cb5310d45b823cd48515874a908f
0
picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons,picoded/JavaCommons
package picoded.jSql.db; import java.lang.String; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Logger; import java.lang.RuntimeException; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.StringWriter; import java.util.logging.*; import java.io.PrintWriter; import java.util.concurrent.ExecutionException; import picoded.jSql.JSqlType; import picoded.jSql.JSqlResult; import picoded.jSql.JSqlException; import picoded.jSql.*; import picoded.jSql.db.BaseInterface; /// Pure SQL Server 2012 implentation of JSql /// Support only for SQL Server 2012 and above version for the pagination query, the OFFSET / FETCH keywords /// are used which are faster and better in performance in comparison of old ROW_NUMBER() public class JSql_Mssql extends JSql implements BaseInterface { /// Internal self used logger private static Logger logger = Logger.getLogger(JSql_Mssql.class.getName()); /// Runs JSql with the JDBC sqlite engine public JSql_Mssql(String dbUrl, String dbName, String dbUser, String dbPass) { sqlType = JSqlType.mssql; String connectionUrl = "jdbc:jtds:sqlserver://" + dbUrl; if (dbName != null && dbName.length() > 0) { connectionUrl = connectionUrl + ";DatabaseName=" + dbName + ";uselobs=false;"; //disable clobs } try { Class.forName("net.sourceforge.jtds.jdbcx.JtdsDataSource"); //connection pooling sqlConn = java.sql.DriverManager.getConnection(connectionUrl, dbUser, dbPass); } catch (Exception e) { throw new RuntimeException("Failed to load mssql connection: ", e); } } // Internal parser that converts some of the common sql statements to mssql public static String genericSqlParser(String inString) { String fixedQuotes = inString.trim().replaceAll("(\\s){1}", " ").replaceAll("'", "\"").replaceAll("`", "\""); String upperCaseStr = fixedQuotes.toUpperCase(); String qString = fixedQuotes; String qStringPrefix = ""; String qStringSuffix = ""; final String ifExists = "IF EXISTS"; final String ifNotExists = "IF NOT EXISTS"; final String create = "CREATE"; final String drop = "DROP"; final String table = "TABLE"; final String select = "SELECT"; final String update = "UPDATE"; final String insertInto = "INSERT INTO"; final String deleteFrom = "DELETE FROM"; final String[] indexTypeArr = { "UNIQUE", "FULLTEXT", "SPATIAL" }; final String index = "INDEX"; String indexType; String tmpStr; int tmpIndx; Pattern createIndexType = Pattern.compile("((UNIQUE|FULLTEXT|SPATIAL) ){0,1}INDEX.*"); int prefixOffset = 0; if (upperCaseStr.startsWith(drop)) { //DROP prefixOffset = drop.length() + 1; if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE prefixOffset += table.length() + 1; if (upperCaseStr.startsWith(ifExists, prefixOffset)) { //IF EXISTS prefixOffset += ifExists.length() + 1; qStringPrefix = "BEGIN TRY IF OBJECT_ID('" + fixedQuotes.substring(prefixOffset).toUpperCase() + "', 'U')" + " IS NOT NULL DROP TABLE " + fixedQuotes.substring(prefixOffset) + " END TRY BEGIN CATCH END CATCH"; } else { qStringPrefix = "DROP TABLE "; } qString = qStringPrefix; } else if (upperCaseStr.startsWith(index, prefixOffset)) { //INDEX } } else if (upperCaseStr.startsWith(create)) { //CREATE prefixOffset = create.length() + 1; if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE prefixOffset += table.length() + 1; if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) { //IF NOT EXISTS prefixOffset += ifNotExists.length() + 1; //get the table name from incoming query String tableName = getTableName(fixedQuotes.substring(prefixOffset)); qStringPrefix = "BEGIN TRY IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'" + tableName + "')" + " AND OBJECTPROPERTY(id, N'" + tableName + "')" + " = 1) CREATE TABLE "; qStringSuffix = " END TRY BEGIN CATCH END CATCH"; } else { qStringPrefix = "CREATE TABLE "; } qString = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset)); //qString = _simpleMysqlToOracle_collumnSubstitude(qString); } else { logger.finer("Trying to matched INDEX : " + upperCaseStr.substring(prefixOffset)); if (createIndexType.matcher(upperCaseStr.substring(prefixOffset)).matches()) { //UNIQUE|FULLTEXT|SPATIAL|_ INDEX logger.finer("Matched INDEX : " + inString); //Find the index type indexType = null; for (int a = 0; a < indexTypeArr.length; ++a) { if (upperCaseStr.startsWith(indexTypeArr[a], prefixOffset)) { prefixOffset += indexTypeArr[a].length() + 1; indexType = indexTypeArr[a]; break; } } //only bother if it matches (shd be right?) if (upperCaseStr.startsWith(index, prefixOffset)) { prefixOffset += index.length() + 1; //If not exists wrapper if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) { prefixOffset += ifNotExists.length() + 1; qStringPrefix = ""; qStringSuffix = ""; } tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset)); tmpIndx = tmpStr.indexOf(" ON "); if (tmpIndx > 0) { qString = "BEGIN TRY CREATE " + ((indexType != null) ? indexType + " " : "") + "INDEX " + tmpStr.substring(0, tmpIndx) + " ON " + _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx + 4)) + " END TRY BEGIN CATCH END CATCH"; } } } } } else if (upperCaseStr.startsWith(insertInto)) { //INSERT INTO prefixOffset = insertInto.length() + 1; tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset)); qString = "INSERT INTO " + tmpStr; } else if (upperCaseStr.startsWith(select)) { //SELECT prefixOffset = select.length() + 1; tmpStr = qString.substring(prefixOffset); tmpIndx = qString.toUpperCase().indexOf(" FROM "); if (tmpIndx > 0) { qString = "SELECT " + tmpStr.substring(0, tmpIndx - 7).replaceAll("\"", "'").replaceAll("`", "'") + " FROM " + _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx - 1)); } else { qString = _fixTableNameInMssqlSubQuery(fixedQuotes); } prefixOffset = 0; //Fix the "AS" quotation while ((tmpIndx = qString.indexOf(" AS ", prefixOffset)) > 0) { prefixOffset = qString.indexOf(" ", tmpIndx + 4); if (prefixOffset > 0) { qString = qString.substring(0, tmpIndx) + qString.substring(tmpIndx, prefixOffset).replaceAll("`", "\"").replaceAll("'", "\"") + qString.substring(prefixOffset); } else { break; } } // Fix the pagination query as per the SQL Server 2012 syntax by using the OFFSET/FETCH String prefixQuery = null; int offsetIndex = qString.indexOf("OFFSET"); String offsetQuery = ""; if (offsetIndex != -1) { prefixQuery = qString.substring(0, offsetIndex); offsetQuery = qString.substring(offsetIndex); offsetQuery += " ROWS "; } int limitIndex = qString.indexOf("LIMIT"); String limitQuery = ""; if (limitIndex != -1) { prefixQuery = qString.substring(0, limitIndex); if (offsetIndex != -1) { limitQuery = qString.substring(limitIndex, offsetIndex); } else { limitQuery = qString.substring(limitIndex); } limitQuery = limitQuery.replace("LIMIT", "FETCH NEXT"); limitQuery += " ROWS ONLY "; } if (prefixQuery != null) { qString = prefixQuery + offsetQuery + limitQuery; } } else if (upperCaseStr.startsWith(deleteFrom)) { prefixOffset = deleteFrom.length() + 1; tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset)); qString = deleteFrom + " " + tmpStr; } else if (upperCaseStr.startsWith(update)) { //UPDATE prefixOffset = update.length() + 1; tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset)); qString = update + " " + tmpStr; } //Drop table query modication if (qString.contains("DROP")) { qString = qStringPrefix; } else { qString = qStringPrefix + qString + qStringSuffix; } //Convert MY-Sql NUMBER data type to NUMERIC data type for Ms-sql if (qString.contains("CREATE TABLE") && qString.contains("NUMBER")) { qString = qString.replaceAll("NUMBER", "NUMERIC"); } //remove ON DELETE FOR CLIENTSTATUSHISTORY---> this block needs to be refined for future. if (qString.contains("ON DELETE")) { //qString.contains("CLIENTSTATUSHISTORY") && qString = qString.replaceAll("ON DELETE SET NULL", ""); } //logger.finer("Converting MySQL query to MsSql query"); logger.finer("MySql -> " + inString); logger.finer("MsSql -> " + qString); //logger.warning("MySql -> "+inString); //logger.warning("OracleSql -> "+qString); //System.out.println("[Query]: "+qString); return qString; //no change of data } //Method to return table name from incoming query string private static String getTableName(String qString) { qString = qString.trim(); int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt; String tableStr = qString.substring(0, indxPt).toUpperCase(); return tableStr; //retrun the table name } private static String _fixTableNameInMssqlSubQuery(String qString) { qString = qString.trim(); int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt; String tableStr = qString.substring(0, indxPt).toUpperCase(); qString = tableStr + qString.substring(indxPt); while (qString.endsWith(";")) { //Remove uneeded trailing ";" semi collons qString = qString.substring(0, qString.length() - 1); } return qString; } /// Executes the argumented query, and returns the result object *without* /// fetching the result data from the database. (not fetching may not apply to all implementations) /// /// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results public JSqlResult executeQuery(String qString, Object... values) throws JSqlException { return executeQuery_raw(genericSqlParser(qString), values); } /// Executes the argumented query, and immediately fetches the result from /// the database into the result set. /// /// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results public JSqlResult query(String qString, Object... values) throws JSqlException { return query_raw(genericSqlParser(qString), values); } /// Executes and dispose the sqliteResult object. /// /// Returns false if no result is given by the execution call, else true on success public boolean execute(String qString, Object... values) throws JSqlException { return execute_raw(genericSqlParser(qString), values); } /// /// Helps generate an SQL UPSERT request. This function was created to acommedate the various /// syntax differances of UPSERT across the various SQL vendors. /// /// Note that care should be taken to prevent SQL injection via the given statment strings. /// /// The syntax below, is an example of such an UPSERT statement for Oracle. /// /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.SQL} /// MERGE /// INTO destTable d /// USING ( /// SELECT * /// FROM sourceTable /// ) s /// ON (s.id = d.id) /// WHEN MATCHED THEN /// INSERT (id, destCol1, destCol2) /// VALUES (id, sourceCol1, sourceCol2) /// WHEN NOT MATCHED THEN /// UPDATE /// SET destCol1 = sourceCol1, /// destCol2 = sourceCol2 /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// public JSqlQuerySet upsertQuerySet( // String tableName, // Table name to upsert on // String[] uniqueColumns, // The unique column names Object[] uniqueValues, // The row unique identifier values // String[] insertColumns, // Columns names to update Object[] insertValues, // Values to update // String[] defaultColumns, // Columns names to apply default value, if not exists Object[] defaultValues, // Values to insert, that is not updated. Note that this is ignored if pre-existing values exists // // Various column names where its existing value needs to be maintained (if any), // this is important as some SQL implementation will fallback to default table values, if not properly handled String[] miscColumns // ) throws JSqlException { if (tableName.length() > 30) { logger.warning(JSqlException.oracleNameSpaceWarning + tableName); } /// Checks that unique collumn and values length to be aligned if (uniqueColumns == null || uniqueValues == null || uniqueColumns.length != uniqueValues.length) { throw new JSqlException("Upsert query requires unique column and values to be equal length"); } /// Preparing inner default select, this will be used repeatingly for COALESCE, DEFAULT and MISC values ArrayList<Object> innerSelectArgs = new ArrayList<Object>(); StringBuilder innerSelectSB = new StringBuilder(" FROM "); innerSelectSB.append("`" + tableName + "`"); innerSelectSB.append(" WHERE "); for (int a = 0; a < uniqueColumns.length; ++a) { if (a > 0) { innerSelectSB.append(" AND "); } innerSelectSB.append(uniqueColumns[a] + " = ?"); innerSelectArgs.add(uniqueValues[a]); } innerSelectSB.append(")"); String innerSelectPrefix = "(SELECT "; String innerSelectSuffix = innerSelectSB.toString(); /// Building the query for INSERT OR REPLACE StringBuilder queryBuilder = new StringBuilder("MERGE INTO `" + tableName + "` t USING ("); ArrayList<Object> queryArgs = new ArrayList<Object>(); ArrayList<Object> updateQueryArgs = new ArrayList<Object>(); /// Building the query for both sides of '(...columns...) VALUE (...vars...)' clauses in upsert /// Note that the final trailing ", " seperator will be removed prior to final query conversion StringBuilder dualColumnNames = new StringBuilder(); StringBuilder updateColumnNames = new StringBuilder(); StringBuilder updateUniqueColumnNames = new StringBuilder(); StringBuilder columnNames = new StringBuilder(); StringBuilder columnValues = new StringBuilder(); String columnSeperator = ", "; /// Setting up unique values for (int a = 0; a < uniqueColumns.length; ++a) { //updateColumnNames.append(uniqueColumns[a]+"=?"+columnSeperator); updateUniqueColumnNames.append(uniqueColumns[a] + "=?" + columnSeperator); queryArgs.add(uniqueValues[a]); dualColumnNames.append("? AS " + uniqueColumns[a] + columnSeperator); queryArgs.add(uniqueValues[a]); columnNames.append(uniqueColumns[a]); columnNames.append(columnSeperator); // columnValues.append("?"); columnValues.append(columnSeperator); // queryArgs.add(uniqueValues[a]); } /// Inserting updated values if (insertColumns != null) { for (int a = 0; a < insertColumns.length; ++a) { updateColumnNames.append(insertColumns[a] + "=?" + columnSeperator); queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); dualColumnNames.append("? AS " + insertColumns[a] + columnSeperator); queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); columnNames.append(insertColumns[a]); columnNames.append(columnSeperator); // columnValues.append("?"); columnValues.append(columnSeperator); // queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); } } /// Handling default values if (defaultColumns != null) { for (int a = 0; a < defaultColumns.length; ++a) { updateColumnNames.append(defaultColumns[a] + "="); columnNames.append(defaultColumns[a]); columnNames.append(columnSeperator); // columnValues.append("COALESCE("); updateColumnNames.append("COALESCE("); //- columnValues.append(innerSelectPrefix); columnValues.append(defaultColumns[a]); columnValues.append(innerSelectSuffix); updateColumnNames.append(innerSelectPrefix); updateColumnNames.append(defaultColumns[a]); updateColumnNames.append(innerSelectSuffix); queryArgs.addAll(innerSelectArgs); //- columnValues.append(", ?)"); columnValues.append(columnSeperator); queryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null); updateColumnNames.append(", ?)"); updateColumnNames.append(columnSeperator); queryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null); dualColumnNames.append("? AS " + defaultColumns[a] + columnSeperator); queryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null); } } /// Handling Misc values if (miscColumns != null) { for (int a = 0; a < miscColumns.length; ++a) { columnNames.append(miscColumns[a]); columnNames.append(columnSeperator); //- columnValues.append(innerSelectPrefix); columnValues.append(miscColumns[a]); columnValues.append(innerSelectSuffix); queryArgs.addAll(innerSelectArgs); //- columnValues.append(columnSeperator); updateColumnNames.append(miscColumns[a] + "="); updateColumnNames.append(innerSelectPrefix); updateColumnNames.append(miscColumns[a]); updateColumnNames.append(innerSelectSuffix); updateColumnNames.append(columnSeperator); queryArgs.addAll(innerSelectArgs); dualColumnNames.append("? AS " + miscColumns[a] + columnSeperator); queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); } } /// Setting up DUAL columns for (int a = 0; a < uniqueColumns.length; ++a) { dualColumnNames.append(uniqueColumns[a]); dualColumnNames.append("=?"); dualColumnNames.append(columnSeperator); queryArgs.add(uniqueValues[a]); } /// Building the final query queryBuilder.append(" SELECT "); queryBuilder.append(dualColumnNames.substring(0, dualColumnNames.length() - columnSeperator.length())); queryBuilder.append(") d "); queryBuilder.append(" ON ( t.key = d.key ) "); queryBuilder.append(" WHEN MATCHED "); queryBuilder.append(" THEN UPDATE SET "); queryBuilder.append(updateColumnNames.substring(0, updateColumnNames.length() - columnSeperator.length())); queryBuilder.append(" WHEN NOT MATCHED "); queryBuilder.append(" THEN INSERT ("); queryBuilder.append(columnNames.substring(0, columnNames.length() - columnSeperator.length())); queryBuilder.append(") VALUES ("); queryBuilder.append(columnValues.substring(0, columnValues.length() - columnSeperator.length())); queryBuilder.append(")"); System.out.println("JSql -> upsertQuerySet -> query : " + queryBuilder.toString()); System.out.println("JSql -> upsertQuerySet -> queryArgs : " + queryArgs); return new JSqlQuerySet(queryBuilder.toString(), queryArgs.toArray(), this); } // Helper varient, without default or misc fields public JSqlQuerySet upsertQuerySet( // String tableName, // Table name to upsert on // String[] uniqueColumns, // The unique column names Object[] uniqueValues, // The row unique identifier values // String[] insertColumns, // Columns names to update Object[] insertValues // Values to update ) throws JSqlException { return upsertQuerySet(tableName, uniqueColumns, uniqueValues, insertColumns, insertValues, null, null, null); } }
src/picoded/jSql/db/JSql_Mssql.java
package picoded.jSql.db; import java.lang.String; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Logger; import java.lang.RuntimeException; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.StringWriter; import java.util.logging.*; import java.io.PrintWriter; import java.util.concurrent.ExecutionException; import picoded.jSql.JSqlType; import picoded.jSql.JSqlResult; import picoded.jSql.JSqlException; import picoded.jSql.JSql; import picoded.jSql.db.BaseInterface; /// Pure SQL Server 2012 implentation of JSql /// Support only for SQL Server 2012 and above version for the pagination query, the OFFSET / FETCH keywords /// are used which are faster and better in performance in comparison of old ROW_NUMBER() public class JSql_Mssql extends JSql implements BaseInterface { /// Internal self used logger private static Logger logger = Logger.getLogger(JSql_Mssql.class.getName()); /// Runs JSql with the JDBC sqlite engine public JSql_Mssql(String dbUrl, String dbName, String dbUser, String dbPass) { sqlType = JSqlType.mssql; String connectionUrl = "jdbc:jtds:sqlserver://" + dbUrl; if (dbName != null && dbName.length() > 0) { connectionUrl = connectionUrl + ";DatabaseName=" + dbName + ";uselobs=false;"; //disable clobs } try { Class.forName("net.sourceforge.jtds.jdbcx.JtdsDataSource"); //connection pooling sqlConn = java.sql.DriverManager.getConnection(connectionUrl, dbUser, dbPass); } catch (Exception e) { throw new RuntimeException("Failed to load mssql connection: ", e); } } // Internal parser that converts some of the common sql statements to mssql public static String genericSqlParser(String inString) { String fixedQuotes = inString.trim().replaceAll("(\\s){1}", " ").replaceAll("'", "\"").replaceAll("`", "\""); String upperCaseStr = fixedQuotes.toUpperCase(); String qString = fixedQuotes; String qStringPrefix = ""; String qStringSuffix = ""; final String ifExists = "IF EXISTS"; final String ifNotExists = "IF NOT EXISTS"; final String create = "CREATE"; final String drop = "DROP"; final String table = "TABLE"; final String select = "SELECT"; final String update = "UPDATE"; final String insertInto = "INSERT INTO"; final String deleteFrom = "DELETE FROM"; final String[] indexTypeArr = { "UNIQUE", "FULLTEXT", "SPATIAL" }; final String index = "INDEX"; String indexType; String tmpStr; int tmpIndx; Pattern createIndexType = Pattern.compile("((UNIQUE|FULLTEXT|SPATIAL) ){0,1}INDEX.*"); int prefixOffset = 0; if (upperCaseStr.startsWith(drop)) { //DROP prefixOffset = drop.length() + 1; if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE prefixOffset += table.length() + 1; if (upperCaseStr.startsWith(ifExists, prefixOffset)) { //IF EXISTS prefixOffset += ifExists.length() + 1; qStringPrefix = "BEGIN TRY IF OBJECT_ID('" + fixedQuotes.substring(prefixOffset).toUpperCase() + "', 'U')" + " IS NOT NULL DROP TABLE " + fixedQuotes.substring(prefixOffset) + " END TRY BEGIN CATCH END CATCH"; } else { qStringPrefix = "DROP TABLE "; } qString = qStringPrefix; } else if (upperCaseStr.startsWith(index, prefixOffset)) { //INDEX } } else if (upperCaseStr.startsWith(create)) { //CREATE prefixOffset = create.length() + 1; if (upperCaseStr.startsWith(table, prefixOffset)) { //TABLE prefixOffset += table.length() + 1; if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) { //IF NOT EXISTS prefixOffset += ifNotExists.length() + 1; //get the table name from incoming query String tableName = getTableName(fixedQuotes.substring(prefixOffset)); qStringPrefix = "BEGIN TRY IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'" + tableName + "')" + " AND OBJECTPROPERTY(id, N'" + tableName + "')" + " = 1) CREATE TABLE "; qStringSuffix = " END TRY BEGIN CATCH END CATCH"; } else { qStringPrefix = "CREATE TABLE "; } qString = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset)); //qString = _simpleMysqlToOracle_collumnSubstitude(qString); } else { logger.finer("Trying to matched INDEX : " + upperCaseStr.substring(prefixOffset)); if (createIndexType.matcher(upperCaseStr.substring(prefixOffset)).matches()) { //UNIQUE|FULLTEXT|SPATIAL|_ INDEX logger.finer("Matched INDEX : " + inString); //Find the index type indexType = null; for (int a = 0; a < indexTypeArr.length; ++a) { if (upperCaseStr.startsWith(indexTypeArr[a], prefixOffset)) { prefixOffset += indexTypeArr[a].length() + 1; indexType = indexTypeArr[a]; break; } } //only bother if it matches (shd be right?) if (upperCaseStr.startsWith(index, prefixOffset)) { prefixOffset += index.length() + 1; //If not exists wrapper if (upperCaseStr.startsWith(ifNotExists, prefixOffset)) { prefixOffset += ifNotExists.length() + 1; qStringPrefix = ""; qStringSuffix = ""; } tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset)); tmpIndx = tmpStr.indexOf(" ON "); if (tmpIndx > 0) { qString = "BEGIN TRY CREATE " + ((indexType != null) ? indexType + " " : "") + "INDEX " + tmpStr.substring(0, tmpIndx) + " ON " + _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx + 4)) + " END TRY BEGIN CATCH END CATCH"; } } } } } else if (upperCaseStr.startsWith(insertInto)) { //INSERT INTO prefixOffset = insertInto.length() + 1; tmpStr = _fixTableNameInMssqlSubQuery(fixedQuotes.substring(prefixOffset)); qString = "INSERT INTO " + tmpStr; } else if (upperCaseStr.startsWith(select)) { //SELECT prefixOffset = select.length() + 1; tmpStr = qString.substring(prefixOffset); tmpIndx = qString.toUpperCase().indexOf(" FROM "); if (tmpIndx > 0) { qString = "SELECT " + tmpStr.substring(0, tmpIndx - 7).replaceAll("\"", "'").replaceAll("`", "'") + " FROM " + _fixTableNameInMssqlSubQuery(tmpStr.substring(tmpIndx - 1)); } else { qString = _fixTableNameInMssqlSubQuery(fixedQuotes); } prefixOffset = 0; //Fix the "AS" quotation while ((tmpIndx = qString.indexOf(" AS ", prefixOffset)) > 0) { prefixOffset = qString.indexOf(" ", tmpIndx + 4); if (prefixOffset > 0) { qString = qString.substring(0, tmpIndx) + qString.substring(tmpIndx, prefixOffset).replaceAll("`", "\"").replaceAll("'", "\"") + qString.substring(prefixOffset); } else { break; } } // Fix the pagination query as per the SQL Server 2012 syntax by using the OFFSET/FETCH String prefixQuery = null; int offsetIndex = qString.indexOf("OFFSET"); String offsetQuery = ""; if (offsetIndex != -1) { prefixQuery = qString.substring(0, offsetIndex); offsetQuery = qString.substring(offsetIndex); offsetQuery += " ROWS "; } int limitIndex = qString.indexOf("LIMIT"); String limitQuery = ""; if (limitIndex != -1) { prefixQuery = qString.substring(0, limitIndex); if (offsetIndex != -1) { limitQuery = qString.substring(limitIndex, offsetIndex); } else { limitQuery = qString.substring(limitIndex); } limitQuery = limitQuery.replace("LIMIT", "FETCH NEXT"); limitQuery += " ROWS ONLY "; } if (prefixQuery != null) { qString = prefixQuery + offsetQuery + limitQuery; } } else if (upperCaseStr.startsWith(deleteFrom)) { prefixOffset = deleteFrom.length() + 1; tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset)); qString = deleteFrom + " " + tmpStr; } else if (upperCaseStr.startsWith(update)) { //UPDATE prefixOffset = update.length() + 1; tmpStr = _fixTableNameInMssqlSubQuery(qString.substring(prefixOffset)); qString = update + " " + tmpStr; } //Drop table query modication if (qString.contains("DROP")) { qString = qStringPrefix; } else { qString = qStringPrefix + qString + qStringSuffix; } //Convert MY-Sql NUMBER data type to NUMERIC data type for Ms-sql if (qString.contains("CREATE TABLE") && qString.contains("NUMBER")) { qString = qString.replaceAll("NUMBER", "NUMERIC"); } //remove ON DELETE FOR CLIENTSTATUSHISTORY---> this block needs to be refined for future. if (qString.contains("ON DELETE")) { //qString.contains("CLIENTSTATUSHISTORY") && qString = qString.replaceAll("ON DELETE SET NULL", ""); } //logger.finer("Converting MySQL query to MsSql query"); logger.finer("MySql -> " + inString); logger.finer("MsSql -> " + qString); //logger.warning("MySql -> "+inString); //logger.warning("OracleSql -> "+qString); //System.out.println("[Query]: "+qString); return qString; //no change of data } //Method to return table name from incoming query string private static String getTableName(String qString) { qString = qString.trim(); int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt; String tableStr = qString.substring(0, indxPt).toUpperCase(); return tableStr; //retrun the table name } private static String _fixTableNameInMssqlSubQuery(String qString) { qString = qString.trim(); int indxPt = ((indxPt = qString.indexOf(' ')) <= -1) ? qString.length() : indxPt; String tableStr = qString.substring(0, indxPt).toUpperCase(); qString = tableStr + qString.substring(indxPt); while (qString.endsWith(";")) { //Remove uneeded trailing ";" semi collons qString = qString.substring(0, qString.length() - 1); } return qString; } /// Executes the argumented query, and returns the result object *without* /// fetching the result data from the database. (not fetching may not apply to all implementations) /// /// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results public JSqlResult executeQuery(String qString, Object... values) throws JSqlException { return executeQuery_raw(genericSqlParser(qString), values); } /// Executes the argumented query, and immediately fetches the result from /// the database into the result set. /// /// **Note:** Only queries starting with 'SELECT' will produce a JSqlResult object that has fetchable results public JSqlResult query(String qString, Object... values) throws JSqlException { return query_raw(genericSqlParser(qString), values); } /// Executes and dispose the sqliteResult object. /// /// Returns false if no result is given by the execution call, else true on success public boolean execute(String qString, Object... values) throws JSqlException { return execute_raw(genericSqlParser(qString), values); } }
upsert fix for mssql - uncomplete
src/picoded/jSql/db/JSql_Mssql.java
upsert fix for mssql - uncomplete
<ide><path>rc/picoded/jSql/db/JSql_Mssql.java <ide> import picoded.jSql.JSqlResult; <ide> import picoded.jSql.JSqlException; <ide> <del>import picoded.jSql.JSql; <add>import picoded.jSql.*; <ide> import picoded.jSql.db.BaseInterface; <ide> <ide> /// Pure SQL Server 2012 implentation of JSql <ide> return execute_raw(genericSqlParser(qString), values); <ide> } <ide> <add> /// <add> /// Helps generate an SQL UPSERT request. This function was created to acommedate the various <add> /// syntax differances of UPSERT across the various SQL vendors. <add> /// <add> /// Note that care should be taken to prevent SQL injection via the given statment strings. <add> /// <add> /// The syntax below, is an example of such an UPSERT statement for Oracle. <add> /// <add> /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.SQL} <add> /// MERGE <add> /// INTO destTable d <add> /// USING ( <add> /// SELECT * <add> /// FROM sourceTable <add> /// ) s <add> /// ON (s.id = d.id) <add> /// WHEN MATCHED THEN <add> /// INSERT (id, destCol1, destCol2) <add> /// VALUES (id, sourceCol1, sourceCol2) <add> /// WHEN NOT MATCHED THEN <add> /// UPDATE <add> /// SET destCol1 = sourceCol1, <add> /// destCol2 = sourceCol2 <add> /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <add> /// <add> public JSqlQuerySet upsertQuerySet( // <add> String tableName, // Table name to upsert on <add> // <add> String[] uniqueColumns, // The unique column names <add> Object[] uniqueValues, // The row unique identifier values <add> // <add> String[] insertColumns, // Columns names to update <add> Object[] insertValues, // Values to update <add> // <add> String[] defaultColumns, // Columns names to apply default value, if not exists <add> Object[] defaultValues, // Values to insert, that is not updated. Note that this is ignored if pre-existing values exists <add> // <add> // Various column names where its existing value needs to be maintained (if any), <add> // this is important as some SQL implementation will fallback to default table values, if not properly handled <add> String[] miscColumns // <add> ) throws JSqlException { <add> <add> if (tableName.length() > 30) { <add> logger.warning(JSqlException.oracleNameSpaceWarning + tableName); <add> } <add> <add> /// Checks that unique collumn and values length to be aligned <add> if (uniqueColumns == null || uniqueValues == null || uniqueColumns.length != uniqueValues.length) { <add> throw new JSqlException("Upsert query requires unique column and values to be equal length"); <add> } <add> <add> /// Preparing inner default select, this will be used repeatingly for COALESCE, DEFAULT and MISC values <add> ArrayList<Object> innerSelectArgs = new ArrayList<Object>(); <add> StringBuilder innerSelectSB = new StringBuilder(" FROM "); <add> innerSelectSB.append("`" + tableName + "`"); <add> innerSelectSB.append(" WHERE "); <add> for (int a = 0; a < uniqueColumns.length; ++a) { <add> if (a > 0) { <add> innerSelectSB.append(" AND "); <add> } <add> innerSelectSB.append(uniqueColumns[a] + " = ?"); <add> innerSelectArgs.add(uniqueValues[a]); <add> } <add> innerSelectSB.append(")"); <add> <add> String innerSelectPrefix = "(SELECT "; <add> String innerSelectSuffix = innerSelectSB.toString(); <add> <add> /// Building the query for INSERT OR REPLACE <add> StringBuilder queryBuilder = new StringBuilder("MERGE INTO `" + tableName + "` t USING ("); <add> ArrayList<Object> queryArgs = new ArrayList<Object>(); <add> ArrayList<Object> updateQueryArgs = new ArrayList<Object>(); <add> <add> /// Building the query for both sides of '(...columns...) VALUE (...vars...)' clauses in upsert <add> /// Note that the final trailing ", " seperator will be removed prior to final query conversion <add> StringBuilder dualColumnNames = new StringBuilder(); <add> StringBuilder updateColumnNames = new StringBuilder(); <add> StringBuilder updateUniqueColumnNames = new StringBuilder(); <add> StringBuilder columnNames = new StringBuilder(); <add> StringBuilder columnValues = new StringBuilder(); <add> String columnSeperator = ", "; <add> <add> /// Setting up unique values <add> for (int a = 0; a < uniqueColumns.length; ++a) { <add> //updateColumnNames.append(uniqueColumns[a]+"=?"+columnSeperator); <add> updateUniqueColumnNames.append(uniqueColumns[a] + "=?" + columnSeperator); <add> queryArgs.add(uniqueValues[a]); <add> <add> dualColumnNames.append("? AS " + uniqueColumns[a] + columnSeperator); <add> queryArgs.add(uniqueValues[a]); <add> <add> columnNames.append(uniqueColumns[a]); <add> columnNames.append(columnSeperator); <add> // <add> columnValues.append("?"); <add> columnValues.append(columnSeperator); <add> // <add> queryArgs.add(uniqueValues[a]); <add> } <add> <add> /// Inserting updated values <add> if (insertColumns != null) { <add> for (int a = 0; a < insertColumns.length; ++a) { <add> updateColumnNames.append(insertColumns[a] + "=?" + columnSeperator); <add> queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); <add> <add> dualColumnNames.append("? AS " + insertColumns[a] + columnSeperator); <add> queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); <add> <add> columnNames.append(insertColumns[a]); <add> columnNames.append(columnSeperator); <add> // <add> columnValues.append("?"); <add> columnValues.append(columnSeperator); <add> // <add> queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); <add> } <add> } <add> <add> /// Handling default values <add> if (defaultColumns != null) { <add> for (int a = 0; a < defaultColumns.length; ++a) { <add> updateColumnNames.append(defaultColumns[a] + "="); <add> <add> columnNames.append(defaultColumns[a]); <add> columnNames.append(columnSeperator); <add> // <add> columnValues.append("COALESCE("); <add> updateColumnNames.append("COALESCE("); <add> //- <add> columnValues.append(innerSelectPrefix); <add> columnValues.append(defaultColumns[a]); <add> columnValues.append(innerSelectSuffix); <add> <add> updateColumnNames.append(innerSelectPrefix); <add> updateColumnNames.append(defaultColumns[a]); <add> updateColumnNames.append(innerSelectSuffix); <add> <add> queryArgs.addAll(innerSelectArgs); <add> //- <add> columnValues.append(", ?)"); <add> columnValues.append(columnSeperator); <add> <add> queryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null); <add> <add> updateColumnNames.append(", ?)"); <add> updateColumnNames.append(columnSeperator); <add> queryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null); <add> <add> dualColumnNames.append("? AS " + defaultColumns[a] + columnSeperator); <add> queryArgs.add((defaultValues != null && defaultValues.length > a) ? defaultValues[a] : null); <add> } <add> } <add> <add> /// Handling Misc values <add> if (miscColumns != null) { <add> for (int a = 0; a < miscColumns.length; ++a) { <add> <add> columnNames.append(miscColumns[a]); <add> columnNames.append(columnSeperator); <add> //- <add> columnValues.append(innerSelectPrefix); <add> columnValues.append(miscColumns[a]); <add> columnValues.append(innerSelectSuffix); <add> queryArgs.addAll(innerSelectArgs); <add> //- <add> columnValues.append(columnSeperator); <add> <add> updateColumnNames.append(miscColumns[a] + "="); <add> updateColumnNames.append(innerSelectPrefix); <add> updateColumnNames.append(miscColumns[a]); <add> updateColumnNames.append(innerSelectSuffix); <add> updateColumnNames.append(columnSeperator); <add> <add> queryArgs.addAll(innerSelectArgs); <add> <add> dualColumnNames.append("? AS " + miscColumns[a] + columnSeperator); <add> queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); <add> <add> queryArgs.add((insertValues != null && insertValues.length > a) ? insertValues[a] : null); <add> <add> } <add> } <add> <add> /// Setting up DUAL columns <add> <add> for (int a = 0; a < uniqueColumns.length; ++a) { <add> dualColumnNames.append(uniqueColumns[a]); <add> dualColumnNames.append("=?"); <add> dualColumnNames.append(columnSeperator); <add> <add> queryArgs.add(uniqueValues[a]); <add> } <add> <add> /// Building the final query <add> <add> queryBuilder.append(" SELECT "); <add> queryBuilder.append(dualColumnNames.substring(0, dualColumnNames.length() - columnSeperator.length())); <add> queryBuilder.append(") d "); <add> queryBuilder.append(" ON ( t.key = d.key ) "); <add> queryBuilder.append(" WHEN MATCHED "); <add> queryBuilder.append(" THEN UPDATE SET "); <add> queryBuilder.append(updateColumnNames.substring(0, updateColumnNames.length() - columnSeperator.length())); <add> queryBuilder.append(" WHEN NOT MATCHED "); <add> queryBuilder.append(" THEN INSERT ("); <add> queryBuilder.append(columnNames.substring(0, columnNames.length() - columnSeperator.length())); <add> queryBuilder.append(") VALUES ("); <add> queryBuilder.append(columnValues.substring(0, columnValues.length() - columnSeperator.length())); <add> queryBuilder.append(")"); <add> <add> System.out.println("JSql -> upsertQuerySet -> query : " + queryBuilder.toString()); <add> System.out.println("JSql -> upsertQuerySet -> queryArgs : " + queryArgs); <add> <add> return new JSqlQuerySet(queryBuilder.toString(), queryArgs.toArray(), this); <add> } <add> <add> // Helper varient, without default or misc fields <add> public JSqlQuerySet upsertQuerySet( // <add> String tableName, // Table name to upsert on <add> // <add> String[] uniqueColumns, // The unique column names <add> Object[] uniqueValues, // The row unique identifier values <add> // <add> String[] insertColumns, // Columns names to update <add> Object[] insertValues // Values to update <add> ) throws JSqlException { <add> return upsertQuerySet(tableName, uniqueColumns, uniqueValues, insertColumns, insertValues, null, null, null); <add> } <add> <ide> }
Java
apache-2.0
34756ae7280fef4a108358107b5ba55555fa97d1
0
gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom
/* * Copyright 2016 Crown Copyright * * 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 stroom.search.server.taskqueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import stroom.task.server.StroomThreadGroup; import stroom.util.spring.StroomShutdown; import stroom.util.spring.StroomStartup; import stroom.util.thread.CustomThreadFactory; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class TaskExecutor { private static final int DEFAULT_MAX_THREADS = 5; private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class); private volatile int maxThreads = DEFAULT_MAX_THREADS; private final AtomicInteger totalThreads = new AtomicInteger(); private final ConcurrentSkipListSet<TaskProducer> producers = new ConcurrentSkipListSet<>(); private final AtomicReference<TaskProducer> lastProducer = new AtomicReference<>(); private final ReentrantLock taskLock = new ReentrantLock(); private final Condition condition = taskLock.newCondition(); private final String name; private volatile ExecutorService executor; private volatile boolean running; public TaskExecutor(final String name) { this.name = name; } @StroomStartup public synchronized void start() { if (!running) { running = true; final ThreadGroup poolThreadGroup = new ThreadGroup(StroomThreadGroup.instance(), name); final CustomThreadFactory threadFactory = new CustomThreadFactory(name, poolThreadGroup, 5); executor = Executors.newSingleThreadExecutor(threadFactory); executor.execute(() -> { while (running) { taskLock.lock(); try { Runnable task = execNextTask(); if (task == null) { condition.await(); } } catch (final InterruptedException e) { // Clear the interrupt state. Thread.interrupted(); } catch (final RuntimeException e) { LOGGER.error(e.getMessage(), e); } finally { taskLock.unlock(); } } }); } } @StroomShutdown public synchronized void stop() { if (running) { running = false; // Wake up any waiting threads. signalAll(); executor.shutdown(); } } final void addProducer(final TaskProducer producer) { producers.add(producer); } final void removeProducer(final TaskProducer producer) { producers.remove(producer); } final void signalAll() { taskLock.lock(); try { condition.signalAll(); } finally { taskLock.unlock(); } } private Runnable execNextTask() { TaskProducer producer = null; Runnable task = null; final int total = totalThreads.getAndIncrement(); boolean executing = false; try { if (total < maxThreads) { // Try and get a task from usable producers. final int tries = producers.size(); for (int i = 0; i < tries && task == null; i++) { producer = nextProducer(); if (producer != null) { task = producer.next(); } } final TaskProducer currentProducer = producer; final Runnable currentTask = task; if (currentTask != null) { executing = true; CompletableFuture.runAsync(currentTask, currentProducer.getExecutor()) .thenAccept(result -> complete()) .exceptionally(t -> { complete(); LOGGER.error(t.getMessage(), t); return null; }); } } } finally { if (!executing) { totalThreads.decrementAndGet(); } } return task; } private void complete() { totalThreads.decrementAndGet(); signalAll(); } private TaskProducer nextProducer() { TaskProducer current; TaskProducer producer; do { current = lastProducer.get(); producer = current; try { if (producer == null) { producer = producers.first(); } else { producer = producers.higher(producer); if (producer == null) { producer = producers.first(); } } } catch (final Exception e) { // Ignore. } } while (!lastProducer.compareAndSet(current, producer)); return producer; } public void setMaxThreads(final int maxThreads) { this.maxThreads = maxThreads; } }
stroom-index/src/main/java/stroom/search/server/taskqueue/TaskExecutor.java
/* * Copyright 2016 Crown Copyright * * 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 stroom.search.server.taskqueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import stroom.task.server.StroomThreadGroup; import stroom.util.spring.StroomShutdown; import stroom.util.thread.CustomThreadFactory; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class TaskExecutor { private static final int DEFAULT_MAX_THREADS = 5; private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class); private volatile int maxThreads = DEFAULT_MAX_THREADS; private final AtomicInteger totalThreads = new AtomicInteger(); private final ConcurrentSkipListSet<TaskProducer> producers = new ConcurrentSkipListSet<>(); private final AtomicReference<TaskProducer> lastProducer = new AtomicReference<>(); private final ReentrantLock taskLock = new ReentrantLock(); private final Condition condition = taskLock.newCondition(); private final ExecutorService executor; private volatile boolean running = true; public TaskExecutor(final String name) { final ThreadGroup poolThreadGroup = new ThreadGroup(StroomThreadGroup.instance(), name); final CustomThreadFactory threadFactory = new CustomThreadFactory(name, poolThreadGroup, 5); executor = Executors.newSingleThreadExecutor(threadFactory); executor.execute(() -> { while (running) { taskLock.lock(); try { Runnable task = execNextTask(); if (task == null) { condition.await(); } } catch (final InterruptedException e) { // Clear the interrupt state. Thread.interrupted(); } catch (final RuntimeException e) { LOGGER.error(e.getMessage(), e); } finally { taskLock.unlock(); } } }); } @StroomShutdown public void stop() { running = false; // Wake up any waiting threads. signalAll(); executor.shutdown(); } final void addProducer(final TaskProducer producer) { producers.add(producer); } final void removeProducer(final TaskProducer producer) { producers.remove(producer); } final void signalAll() { taskLock.lock(); try { condition.signalAll(); } finally { taskLock.unlock(); } } private Runnable execNextTask() { TaskProducer producer = null; Runnable task = null; final int total = totalThreads.getAndIncrement(); boolean executing = false; try { if (total < maxThreads) { // Try and get a task from usable producers. final int tries = producers.size(); for (int i = 0; i < tries && task == null; i++) { producer = nextProducer(); if (producer != null) { task = producer.next(); } } final TaskProducer currentProducer = producer; final Runnable currentTask = task; if (currentTask != null) { executing = true; CompletableFuture.runAsync(currentTask, currentProducer.getExecutor()) .thenAccept(result -> complete()) .exceptionally(t -> { complete(); LOGGER.error(t.getMessage(), t); return null; }); } } } finally { if (!executing) { totalThreads.decrementAndGet(); } } return task; } private void complete() { totalThreads.decrementAndGet(); signalAll(); } private TaskProducer nextProducer() { TaskProducer current; TaskProducer producer; do { current = lastProducer.get(); producer = current; try { if (producer == null) { producer = producers.first(); } else { producer = producers.higher(producer); if (producer == null) { producer = producers.first(); } } } catch (final Exception e) { // Ignore. } } while (!lastProducer.compareAndSet(current, producer)); return producer; } public void setMaxThreads(final int maxThreads) { this.maxThreads = maxThreads; } }
Now only starts the executor when started by lifecycle
stroom-index/src/main/java/stroom/search/server/taskqueue/TaskExecutor.java
Now only starts the executor when started by lifecycle
<ide><path>troom-index/src/main/java/stroom/search/server/taskqueue/TaskExecutor.java <ide> import org.slf4j.LoggerFactory; <ide> import stroom.task.server.StroomThreadGroup; <ide> import stroom.util.spring.StroomShutdown; <add>import stroom.util.spring.StroomStartup; <ide> import stroom.util.thread.CustomThreadFactory; <ide> <ide> import java.util.concurrent.CompletableFuture; <ide> private final ReentrantLock taskLock = new ReentrantLock(); <ide> private final Condition condition = taskLock.newCondition(); <ide> <del> private final ExecutorService executor; <del> private volatile boolean running = true; <add> private final String name; <add> private volatile ExecutorService executor; <add> private volatile boolean running; <ide> <ide> public TaskExecutor(final String name) { <del> final ThreadGroup poolThreadGroup = new ThreadGroup(StroomThreadGroup.instance(), name); <del> final CustomThreadFactory threadFactory = new CustomThreadFactory(name, poolThreadGroup, 5); <del> executor = Executors.newSingleThreadExecutor(threadFactory); <add> this.name = name; <add> } <ide> <del> executor.execute(() -> { <del> while (running) { <del> taskLock.lock(); <del> try { <del> Runnable task = execNextTask(); <del> if (task == null) { <del> condition.await(); <add> @StroomStartup <add> public synchronized void start() { <add> if (!running) { <add> running = true; <add> <add> final ThreadGroup poolThreadGroup = new ThreadGroup(StroomThreadGroup.instance(), name); <add> final CustomThreadFactory threadFactory = new CustomThreadFactory(name, poolThreadGroup, 5); <add> executor = Executors.newSingleThreadExecutor(threadFactory); <add> executor.execute(() -> { <add> while (running) { <add> taskLock.lock(); <add> try { <add> Runnable task = execNextTask(); <add> if (task == null) { <add> condition.await(); <add> } <add> } catch (final InterruptedException e) { <add> // Clear the interrupt state. <add> Thread.interrupted(); <add> } catch (final RuntimeException e) { <add> LOGGER.error(e.getMessage(), e); <add> } finally { <add> taskLock.unlock(); <ide> } <del> } catch (final InterruptedException e) { <del> // Clear the interrupt state. <del> Thread.interrupted(); <del> } catch (final RuntimeException e) { <del> LOGGER.error(e.getMessage(), e); <del> } finally { <del> taskLock.unlock(); <ide> } <del> } <del> }); <add> }); <add> } <ide> } <ide> <ide> @StroomShutdown <del> public void stop() { <del> running = false; <del> // Wake up any waiting threads. <del> signalAll(); <del> executor.shutdown(); <add> public synchronized void stop() { <add> if (running) { <add> running = false; <add> // Wake up any waiting threads. <add> signalAll(); <add> executor.shutdown(); <add> } <ide> } <ide> <ide> final void addProducer(final TaskProducer producer) {
Java
epl-1.0
error: pathspec 'jenjin-core-client/src/test/java/com/jenjinstudios/client/AuthClientTest.java' did not match any file(s) known to git
46ae8eb380d3c3ad136445c816a205e434051192
1
floralvikings/jenjin
package com.jenjinstudios.client; import com.jenjinstudios.client.net.AuthClient; import com.jenjinstudios.client.net.ClientUser; import com.jenjinstudios.core.MessageIO; import org.testng.Assert; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; /** * @author Caleb Brinkman */ public class AuthClientTest { @Test public void testIsLoggedIn() { MessageIO messageIO = mock(MessageIO.class); ClientUser clientUser = mock(ClientUser.class); boolean random = Math.random() * 10 % 2 == 0; AuthClient authClient = new AuthClient(messageIO, clientUser); authClient.setLoggedIn(random); Assert.assertEquals(authClient.isLoggedIn(), random); } @Test public void testLoggedInTime() { MessageIO messageIO = mock(MessageIO.class); ClientUser clientUser = mock(ClientUser.class); long random = (long) (Math.random() * 1000); AuthClient authClient = new AuthClient(messageIO, clientUser); authClient.setLoggedInTime(random); Assert.assertEquals(authClient.getLoggedInTime(), random); } @Test public void testGetUser() { MessageIO messageIO = mock(MessageIO.class); ClientUser clientUser = mock(ClientUser.class); AuthClient authClient = new AuthClient(messageIO, clientUser); Assert.assertEquals(authClient.getUser(), clientUser); } }
jenjin-core-client/src/test/java/com/jenjinstudios/client/AuthClientTest.java
Added AuthClientTest back with much simpler tests
jenjin-core-client/src/test/java/com/jenjinstudios/client/AuthClientTest.java
Added AuthClientTest back with much simpler tests
<ide><path>enjin-core-client/src/test/java/com/jenjinstudios/client/AuthClientTest.java <add>package com.jenjinstudios.client; <add> <add>import com.jenjinstudios.client.net.AuthClient; <add>import com.jenjinstudios.client.net.ClientUser; <add>import com.jenjinstudios.core.MessageIO; <add>import org.testng.Assert; <add>import org.testng.annotations.Test; <add> <add>import static org.mockito.Mockito.mock; <add> <add>/** <add> * @author Caleb Brinkman <add> */ <add>public class AuthClientTest <add>{ <add> @Test <add> public void testIsLoggedIn() { <add> MessageIO messageIO = mock(MessageIO.class); <add> ClientUser clientUser = mock(ClientUser.class); <add> boolean random = Math.random() * 10 % 2 == 0; <add> AuthClient authClient = new AuthClient(messageIO, clientUser); <add> authClient.setLoggedIn(random); <add> <add> Assert.assertEquals(authClient.isLoggedIn(), random); <add> } <add> <add> @Test <add> public void testLoggedInTime() { <add> MessageIO messageIO = mock(MessageIO.class); <add> ClientUser clientUser = mock(ClientUser.class); <add> long random = (long) (Math.random() * 1000); <add> AuthClient authClient = new AuthClient(messageIO, clientUser); <add> authClient.setLoggedInTime(random); <add> <add> Assert.assertEquals(authClient.getLoggedInTime(), random); <add> } <add> <add> @Test <add> public void testGetUser() { <add> MessageIO messageIO = mock(MessageIO.class); <add> ClientUser clientUser = mock(ClientUser.class); <add> AuthClient authClient = new AuthClient(messageIO, clientUser); <add> <add> Assert.assertEquals(authClient.getUser(), clientUser); <add> } <add>}
Java
mit
7fa52abd31dc5739d137ec659e4df4bfb9d43f3c
0
BloomBooks/BloomReader,BloomBooks/BloomReader
package org.sil.bloom.reader; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import java.io.File; /* We were storing thumbnails with the extension .png but now that we have .jpg thumbnails too, we're keeping the extension out of the filename. This task cleans up any old thumbnails stored with the old naming system. */ public class ThumbnailCleanup extends AsyncTask<File, Void, Void> { public static final String DID_THUMB_CLEANUP = "didThumbCleanupRight"; private SharedPreferences values; public ThumbnailCleanup(Context context){ values = context.getSharedPreferences(BloomReaderApplication.SHARED_PREFERENCES_TAG, 0); } @Override public Void doInBackground(File... files){ // Only need to run this once if (values.getBoolean(DID_THUMB_CLEANUP, false)) return null; File thumbsDirectory = files[0]; String[] filenames = thumbsDirectory.list(); for(String filename : filenames){ if (filename.endsWith(".png")) new File(thumbsDirectory + File.separator + filename).delete(); } SharedPreferences.Editor valuesEditor = values.edit(); valuesEditor.putBoolean(DID_THUMB_CLEANUP, true); valuesEditor.commit(); return null; } }
app/src/main/java/org/sil/bloom/reader/ThumbnailCleanup.java
package org.sil.bloom.reader; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import java.io.File; /* We were storing thumbnails with the extension .png but now that we have .jpg thumbnails too, we're keeping the extension out of the filename. This task cleans up any old thumbnails stored with the old naming system. */ public class ThumbnailCleanup extends AsyncTask<File, Void, Void> { public static final String DID_THUMB_CLEANUP = "didThumbCleanup"; private SharedPreferences values; public ThumbnailCleanup(Context context){ values = context.getSharedPreferences(BloomReaderApplication.SHARED_PREFERENCES_TAG, 0); } @Override public Void doInBackground(File... files){ // Only need to run this once if (values.getBoolean(DID_THUMB_CLEANUP, false)) return null; File thumbsDirectory = files[0]; String[] paths = thumbsDirectory.list(); for(String path : paths){ if (path.endsWith(".png")) new File(path).delete(); } SharedPreferences.Editor valuesEditor = values.edit(); valuesEditor.putBoolean(DID_THUMB_CLEANUP, true); valuesEditor.commit(); return null; } }
[5726] Fix path error in thumbnail cleanup
app/src/main/java/org/sil/bloom/reader/ThumbnailCleanup.java
[5726] Fix path error in thumbnail cleanup
<ide><path>pp/src/main/java/org/sil/bloom/reader/ThumbnailCleanup.java <ide> <ide> public class ThumbnailCleanup extends AsyncTask<File, Void, Void> { <ide> <del> public static final String DID_THUMB_CLEANUP = "didThumbCleanup"; <add> public static final String DID_THUMB_CLEANUP = "didThumbCleanupRight"; <ide> <ide> private SharedPreferences values; <ide> <ide> return null; <ide> <ide> File thumbsDirectory = files[0]; <del> String[] paths = thumbsDirectory.list(); <del> for(String path : paths){ <del> if (path.endsWith(".png")) <del> new File(path).delete(); <add> String[] filenames = thumbsDirectory.list(); <add> for(String filename : filenames){ <add> if (filename.endsWith(".png")) <add> new File(thumbsDirectory + File.separator + filename).delete(); <ide> } <ide> <ide> SharedPreferences.Editor valuesEditor = values.edit();
Java
apache-2.0
d65d4ed7e8ffc7848fdba63a6de2ec8775f81944
0
alficles/incubator-trafficcontrol,robert-butts/traffic_control,serDrem/incubator-trafficcontrol,alficles/incubator-trafficcontrol,mdb/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,mdb/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,dangogh/traffic_control,mtorluemke/traffic_control,alficles/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,robert-butts/traffic_control,zhilhuan/incubator-trafficcontrol,mtorluemke/traffic_control,zhilhuan/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,dangogh/traffic_control,knutsel/traffic_control-1,zhilhuan/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,robert-butts/traffic_control,mtorluemke/traffic_control,orifinkelman/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,elsloo/traffic_control,mitchell852/traffic_control,dangogh/traffic_control,weifensh/incubator-trafficcontrol,mitchell852/traffic_control,amiryesh/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,mtorluemke/traffic_control,robert-butts/traffic_control,amiryesh/incubator-trafficcontrol,mtorluemke/traffic_control,hbeatty/incubator-trafficcontrol,mdb/incubator-trafficcontrol,mdb/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,mitchell852/traffic_control,elsloo/traffic_control,hbeatty/incubator-trafficcontrol,alficles/incubator-trafficcontrol,mdb/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,robert-butts/traffic_control,jeffmart/incubator-trafficcontrol,mitchell852/traffic_control,knutsel/traffic_control-1,alficles/incubator-trafficcontrol,mdb/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,elsloo/traffic_control,hbeatty/incubator-trafficcontrol,dangogh/traffic_control,zhilhuan/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,dangogh/traffic_control,mitchell852/traffic_control,mdb/incubator-trafficcontrol,robert-butts/traffic_control,alficles/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,elsloo/traffic_control,jeffmart/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,robert-butts/traffic_control,hbeatty/incubator-trafficcontrol,elsloo/traffic_control,mdb/incubator-trafficcontrol,mtorluemke/traffic_control,amiryesh/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,serDrem/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,mitchell852/traffic_control,serDrem/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,mtorluemke/traffic_control,naamashoresh/incubator-trafficcontrol,alficles/incubator-trafficcontrol,dangogh/traffic_control,mitchell852/traffic_control,knutsel/traffic_control-1,weifensh/incubator-trafficcontrol,alficles/incubator-trafficcontrol,elsloo/traffic_control,rscrimojr/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,mtorluemke/traffic_control,elsloo/traffic_control,serDrem/incubator-trafficcontrol,dangogh/traffic_control,serDrem/incubator-trafficcontrol,knutsel/traffic_control-1,mitchell852/traffic_control,orifinkelman/incubator-trafficcontrol,alficles/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,elsloo/traffic_control,robert-butts/traffic_control,alficles/incubator-trafficcontrol,elsloo/traffic_control,knutsel/traffic_control-1,naamashoresh/incubator-trafficcontrol,dangogh/traffic_control,knutsel/traffic_control-1,naamashoresh/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,mtorluemke/traffic_control,mitchell852/traffic_control,elsloo/traffic_control,weifensh/incubator-trafficcontrol,zhilhuan/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,naamashoresh/incubator-trafficcontrol,knutsel/traffic_control-1,orifinkelman/incubator-trafficcontrol,orifinkelman/incubator-trafficcontrol,dangogh/traffic_control,zhilhuan/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,robert-butts/traffic_control,zhilhuan/incubator-trafficcontrol,weifensh/incubator-trafficcontrol,mdb/incubator-trafficcontrol,mdb/incubator-trafficcontrol,mtorluemke/traffic_control,hbeatty/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,knutsel/traffic_control-1,amiryesh/incubator-trafficcontrol,amiryesh/incubator-trafficcontrol,dangogh/traffic_control,serDrem/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,mitchell852/traffic_control,robert-butts/traffic_control,serDrem/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,knutsel/traffic_control-1,naamashoresh/incubator-trafficcontrol,hbeatty/incubator-trafficcontrol,rscrimojr/incubator-trafficcontrol,jeffmart/incubator-trafficcontrol,knutsel/traffic_control-1
package com.comcast.cdn.traffic_control.traffic_router.core.secure; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class CertificateData { @JsonProperty private String deliveryservice; @JsonProperty private Certificate certificate; public String getDeliveryservice() { return deliveryservice; } public void setDeliveryservice(final String deliveryservice) { this.deliveryservice = deliveryservice; } public Certificate getCertificate() { return certificate; } public void setCertificate(final Certificate certificate) { this.certificate = certificate; } @Override @SuppressWarnings("PMD") public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final CertificateData that = (CertificateData) o; if (deliveryservice != null ? !deliveryservice.equals(that.deliveryservice) : that.deliveryservice != null) return false; return certificate != null ? certificate.equals(that.certificate) : that.certificate == null; } @Override public int hashCode() { int result = deliveryservice != null ? deliveryservice.hashCode() : 0; result = 31 * result + (certificate != null ? certificate.hashCode() : 0); return result; } }
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/secure/CertificateData.java
package com.comcast.cdn.traffic_control.traffic_router.core.secure; import com.fasterxml.jackson.annotation.JsonProperty; public class CertificateData { @JsonProperty private String deliveryservice; @JsonProperty private Certificate certificate; public String getDeliveryservice() { return deliveryservice; } public void setDeliveryservice(final String deliveryservice) { this.deliveryservice = deliveryservice; } public Certificate getCertificate() { return certificate; } public void setCertificate(final Certificate certificate) { this.certificate = certificate; } @Override @SuppressWarnings("PMD") public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final CertificateData that = (CertificateData) o; if (deliveryservice != null ? !deliveryservice.equals(that.deliveryservice) : that.deliveryservice != null) return false; return certificate != null ? certificate.equals(that.certificate) : that.certificate == null; } @Override public int hashCode() { int result = deliveryservice != null ? deliveryservice.hashCode() : 0; result = 31 * result + (certificate != null ? certificate.hashCode() : 0); return result; } }
TR now ignores all json fields for certificate data except deliveryservice and certificate
traffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/secure/CertificateData.java
TR now ignores all json fields for certificate data except deliveryservice and certificate
<ide><path>raffic_router/core/src/main/java/com/comcast/cdn/traffic_control/traffic_router/core/secure/CertificateData.java <ide> package com.comcast.cdn.traffic_control.traffic_router.core.secure; <ide> <add>import com.fasterxml.jackson.annotation.JsonIgnoreProperties; <ide> import com.fasterxml.jackson.annotation.JsonProperty; <ide> <add>@JsonIgnoreProperties(ignoreUnknown = true) <ide> public class CertificateData { <ide> @JsonProperty <ide> private String deliveryservice;
Java
mit
0e4f960f2298f1a24533466e99acb3c38160c485
0
Narwhalprime/simcity201-team-project
package simcity.gui; import housing.Housing; import housing.ResidentAgent.State; import housing.gui.HousingAnimationPanel; import housing.test.mock.LoggedEvent; import javax.swing.*; import market.Market; import market.gui.MarketAnimationPanel; import java.awt.*; import java.awt.event.*; import restaurant_bayou.gui.BayouAnimationPanel; import restaurant_bayou.gui.RestaurantBayou; import restaurant_rancho.gui.RanchoAnimationPanel; import restaurant_rancho.gui.RestaurantRancho; import restaurant_rancho.gui.RestaurantRanchoGui; import restaurant_rancho.gui.RestaurantRancho; import restaurant_pizza.gui.RestaurantPizza; import restaurant_pizza.gui.PizzaAnimationPanel; import simcity.PersonAgent; public class SimCityGui extends JFrame implements ActionListener { public static final int WINDOWX = 800; public static final int WINDOWY = 600; String name; SimCityPanel simCityPanel; JPanel cards; enum Panel {housing, rancho, bayou, market, bank, pizza}; Panel currP; public static RestaurantRancho restRancho; public RanchoAnimationPanel ranchoAniPanel = new RanchoAnimationPanel(); public static Housing hauntedMansion; public HousingAnimationPanel housAniPanel = new HousingAnimationPanel(); public static RestaurantBayou restBayou; public BayouAnimationPanel bayouAniPanel = new BayouAnimationPanel(); public static Market mickeysMarket; public MarketAnimationPanel markAniPanel = new MarketAnimationPanel(); public static RestaurantPizza restPizza; public PizzaAnimationPanel pizzaAniPanel = new PizzaAnimationPanel(); CityAnimationPanel cityAniPanel = new CityAnimationPanel(); private JPanel cityBanner = new JPanel(); private JPanel zoomBanner = new JPanel(); private JPanel cityAnimation = new JPanel(); private JPanel zoomAnimation = new JPanel(); private JPanel cityPanel = new JPanel(); private JPanel zoomPanel = new JPanel(); private JLabel cityLabel = new JLabel("Disney City View"); private JLabel zoomLabel = new JLabel("Click on a Building to see Animation Inside"); private JButton panelB = new JButton("next panel"); public SimCityGui(String name) { // int delay = 1000; //milliseconds // ActionListener taskPerformer = new ActionListener() { // public void actionPerformed(ActionEvent evt) { //// housAniPanel.update(); // } // }; // new Timer(delay, taskPerformer).start(); cards = new JPanel(new CardLayout()); cards.add(housAniPanel, "Housing"); cards.add(markAniPanel, "Market"); cards.add(ranchoAniPanel, "Rancho"); cards.add(bayouAniPanel, "Bayou"); cards.add(pizzaAniPanel, "Pizza"); panelB.addActionListener(this); panelB.setPreferredSize(new Dimension(0, 0)); currP = Panel.housing; // Restaurants etc. must be created before simCityPanel is constructed, as demonstrated below restRancho = new RestaurantRancho(this, "Rancho Del Zocalo"); restBayou = new RestaurantBayou(this, "The Blue Bayou"); restPizza = new RestaurantPizza(this); hauntedMansion = new Housing(this, "Haunted Mansion"); mickeysMarket = new Market(this, "Mickey's Market"); simCityPanel = new SimCityPanel(this); setLayout(new GridBagLayout()); setBounds(WINDOWX/20, WINDOWX/20, WINDOWX, WINDOWY); GridBagConstraints c = new GridBagConstraints(); //c.fill = GridBagConstraints.BOTH; GridBagConstraints c1 = new GridBagConstraints(); c1.fill = GridBagConstraints.BOTH; c1.weightx = .5; c1.gridx = 0; c1.gridy = 0; c1.gridwidth = 3; cityBanner.setBorder(BorderFactory.createTitledBorder("City Banner")); add(cityBanner, c1); GridBagConstraints c3 = new GridBagConstraints(); c3.fill = GridBagConstraints.BOTH; c3.weightx = .5; c3.gridx = 5; c3.gridy = 0; c3.gridwidth = 5; zoomBanner.setBorder(BorderFactory.createTitledBorder("Zoom Banner")); add(zoomBanner, c3); GridBagConstraints c2 = new GridBagConstraints(); c2.fill = GridBagConstraints.BOTH; c2.weightx = .5; c2.weighty = .32; c2.gridx = 0; c2.gridy = 1; c2.gridwidth = 3; c2.gridheight = 3; cityAnimation.setLayout(new BoxLayout(cityAnimation, BoxLayout.Y_AXIS)); cityAnimation.add(cityAniPanel); //cityAnimation.setBorder(BorderFactory.createTitledBorder("City Animation")); add(cityAnimation, c2); GridBagConstraints c4 = new GridBagConstraints(); c4.fill = GridBagConstraints.BOTH; c4.weightx = .5; c4.weighty=.32; c4.gridx = 3; c4.gridy=1; c4.gridwidth = GridBagConstraints.REMAINDER; c4.gridheight = 3; zoomAnimation.setLayout(new BoxLayout(zoomAnimation, BoxLayout.Y_AXIS)); zoomAnimation.add(cards); // ranchoAniPanel.setVisible(false); // zoomAnimation.add(housAniPanel); //zoomAnimation.setBorder(BorderFactory.createTitledBorder("Zoom Animation")); add(zoomAnimation, c4); GridBagConstraints c5 = new GridBagConstraints(); c5.fill = GridBagConstraints.BOTH; c5.weightx= .5; c5.weighty = .18; c5.gridx=0; c5.gridy=5; c5.gridwidth = 3; c5.gridheight = 2; cityPanel.setBorder(BorderFactory.createTitledBorder("City Panel")); add(cityPanel, c5); GridBagConstraints c6 = new GridBagConstraints(); c6.fill = GridBagConstraints.BOTH; c6.weightx= 0; c6.weighty = .18; c6.gridx=3; c6.gridy=5; c6.gridwidth = GridBagConstraints.REMAINDER; c6.gridheight =2; zoomPanel.setBorder(BorderFactory.createTitledBorder("Zoom Panel")); add(panelB, c6); } public static void main(String[] args) { SimCityGui gui = new SimCityGui("Sim City Disneyland"); gui.setTitle("SimCity Disneyland"); gui.setVisible(true); gui.setResizable(false); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); restRancho.addPerson(null, "Cook", "cook", 50); restRancho.addPerson(null, "Waiter", "w", 50); restRancho.addPerson(null, "Cashier", "cash", 50); restRancho.addPerson(null, "Market", "Trader Joes", 50); restRancho.addPerson(null, "Host", "Host", 50); restRancho.addPerson(null, "Customer", "Sally", 50); restPizza.addPerson(null, "Cook", "cook", 50); restPizza.addPerson(null, "Waiter", "w", 50); restPizza.addPerson(null, "Cashier", "cash", 50); restPizza.addPerson(null, "Host", "Host", 50); restPizza.addPerson(null, "Customer", "Sally", 50); mickeysMarket.addPerson(null, "Manager", "MRAWP", 100, ""); mickeysMarket.addPerson(null, "Cashier", "Kapow", 100, ""); mickeysMarket.addPerson(null, "Worker", "Bleep", 100, ""); mickeysMarket.addPerson(null, "Customer", "Beebop", 100, "American"); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == panelB) { CardLayout cl = (CardLayout)(cards.getLayout()); if (currP == Panel.pizza) { System.out.println("showing housing"); cl.show(cards, "Housing"); currP = Panel.housing; } else if (currP == Panel.housing) { System.out.println("showing market"); cl.show(cards, "Market"); currP = Panel.market; } else if (currP == Panel.market) { System.out.println("showing rancho"); cl.show(cards, "Rancho"); currP = Panel.rancho; } else if (currP == Panel.rancho) { System.out.println("showing bayou"); cl.show(cards, "Bayou"); currP = Panel.bayou; } else if (currP == Panel.bayou) { System.out.println("showing pizza"); cl.show(cards, "Pizza"); currP = Panel.pizza; } } } }
src/simcity/gui/SimCityGui.java
package simcity.gui; import housing.Housing; import housing.ResidentAgent.State; import housing.gui.HousingAnimationPanel; import housing.test.mock.LoggedEvent; import javax.swing.*; import market.Market; import market.gui.MarketAnimationPanel; import java.awt.*; import java.awt.event.*; import restaurant_bayou.gui.BayouAnimationPanel; import restaurant_bayou.gui.RestaurantBayou; import restaurant_rancho.gui.RanchoAnimationPanel; import restaurant_rancho.gui.RestaurantRancho; import restaurant_rancho.gui.RestaurantRanchoGui; import restaurant_rancho.gui.RestaurantRancho; import restaurant_pizza.gui.RestaurantPizza; import restaurant_pizza.gui.PizzaAnimationPanel; import simcity.PersonAgent; public class SimCityGui extends JFrame implements ActionListener { public static final int WINDOWX = 800; public static final int WINDOWY = 600; String name; SimCityPanel simCityPanel; JPanel cards; enum Panel {housing, rancho, bayou, market, bank, pizza}; Panel currP; public static RestaurantRancho restRancho; public RanchoAnimationPanel ranchoAniPanel = new RanchoAnimationPanel(); public static Housing hauntedMansion; public HousingAnimationPanel housAniPanel = new HousingAnimationPanel(); public static RestaurantBayou restBayou; public BayouAnimationPanel bayouAniPanel = new BayouAnimationPanel(); public static Market mickeysMarket; public MarketAnimationPanel markAniPanel = new MarketAnimationPanel(); public static RestaurantPizza restPizza; public PizzaAnimationPanel pizzaAniPanel = new PizzaAnimationPanel(); CityAnimationPanel cityAniPanel = new CityAnimationPanel(); private JPanel cityBanner = new JPanel(); private JPanel zoomBanner = new JPanel(); private JPanel cityAnimation = new JPanel(); private JPanel zoomAnimation = new JPanel(); private JPanel cityPanel = new JPanel(); private JPanel zoomPanel = new JPanel(); private JLabel cityLabel = new JLabel("Disney City View"); private JLabel zoomLabel = new JLabel("Click on a Building to see Animation Inside"); private JButton panelB = new JButton("next panel"); public SimCityGui(String name) { // int delay = 1000; //milliseconds // ActionListener taskPerformer = new ActionListener() { // public void actionPerformed(ActionEvent evt) { //// housAniPanel.update(); // } // }; // new Timer(delay, taskPerformer).start(); cards = new JPanel(new CardLayout()); cards.add(housAniPanel, "Housing"); cards.add(markAniPanel, "Market"); cards.add(ranchoAniPanel, "Rancho"); cards.add(bayouAniPanel, "Bayou"); cards.add(pizzaAniPanel, "Pizza"); panelB.addActionListener(this); panelB.setPreferredSize(new Dimension(0, 0)); currP = Panel.housing; // Restaurants etc. must be created before simCityPanel is constructed, as demonstrated below restRancho = new RestaurantRancho(this, "Rancho Del Zocalo"); restBayou = new RestaurantBayou(this, "The Blue Bayou"); restPizza = new RestaurantPizza(this); simCityPanel = new SimCityPanel(this); hauntedMansion = new Housing(this, "Haunted Mansion"); mickeysMarket = new Market(this, "Mickey's Market"); setLayout(new GridBagLayout()); setBounds(WINDOWX/20, WINDOWX/20, WINDOWX, WINDOWY); GridBagConstraints c = new GridBagConstraints(); //c.fill = GridBagConstraints.BOTH; GridBagConstraints c1 = new GridBagConstraints(); c1.fill = GridBagConstraints.BOTH; c1.weightx = .5; c1.gridx = 0; c1.gridy = 0; c1.gridwidth = 3; cityBanner.setBorder(BorderFactory.createTitledBorder("City Banner")); add(cityBanner, c1); GridBagConstraints c3 = new GridBagConstraints(); c3.fill = GridBagConstraints.BOTH; c3.weightx = .5; c3.gridx = 5; c3.gridy = 0; c3.gridwidth = 5; zoomBanner.setBorder(BorderFactory.createTitledBorder("Zoom Banner")); add(zoomBanner, c3); GridBagConstraints c2 = new GridBagConstraints(); c2.fill = GridBagConstraints.BOTH; c2.weightx = .5; c2.weighty = .32; c2.gridx = 0; c2.gridy = 1; c2.gridwidth = 3; c2.gridheight = 3; cityAnimation.setLayout(new BoxLayout(cityAnimation, BoxLayout.Y_AXIS)); cityAnimation.add(cityAniPanel); //cityAnimation.setBorder(BorderFactory.createTitledBorder("City Animation")); add(cityAnimation, c2); GridBagConstraints c4 = new GridBagConstraints(); c4.fill = GridBagConstraints.BOTH; c4.weightx = .5; c4.weighty=.32; c4.gridx = 3; c4.gridy=1; c4.gridwidth = GridBagConstraints.REMAINDER; c4.gridheight = 3; zoomAnimation.setLayout(new BoxLayout(zoomAnimation, BoxLayout.Y_AXIS)); zoomAnimation.add(cards); // ranchoAniPanel.setVisible(false); // zoomAnimation.add(housAniPanel); //zoomAnimation.setBorder(BorderFactory.createTitledBorder("Zoom Animation")); add(zoomAnimation, c4); GridBagConstraints c5 = new GridBagConstraints(); c5.fill = GridBagConstraints.BOTH; c5.weightx= .5; c5.weighty = .18; c5.gridx=0; c5.gridy=5; c5.gridwidth = 3; c5.gridheight = 2; cityPanel.setBorder(BorderFactory.createTitledBorder("City Panel")); add(cityPanel, c5); GridBagConstraints c6 = new GridBagConstraints(); c6.fill = GridBagConstraints.BOTH; c6.weightx= 0; c6.weighty = .18; c6.gridx=3; c6.gridy=5; c6.gridwidth = GridBagConstraints.REMAINDER; c6.gridheight =2; zoomPanel.setBorder(BorderFactory.createTitledBorder("Zoom Panel")); add(panelB, c6); } public static void main(String[] args) { SimCityGui gui = new SimCityGui("Sim City Disneyland"); gui.setTitle("SimCity Disneyland"); gui.setVisible(true); gui.setResizable(false); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); restRancho.addPerson(null, "Cook", "cook", 50); restRancho.addPerson(null, "Waiter", "w", 50); restRancho.addPerson(null, "Cashier", "cash", 50); restRancho.addPerson(null, "Market", "Trader Joes", 50); restRancho.addPerson(null, "Host", "Host", 50); restRancho.addPerson(null, "Customer", "Sally", 50); restPizza.addPerson(null, "Cook", "cook", 50); restPizza.addPerson(null, "Waiter", "w", 50); restPizza.addPerson(null, "Cashier", "cash", 50); restPizza.addPerson(null, "Host", "Host", 50); restPizza.addPerson(null, "Customer", "Sally", 50); mickeysMarket.addPerson(null, "Manager", "MRAWP", 100); mickeysMarket.addPerson(null, "Cashier", "Kapow", 100); mickeysMarket.addPerson(null, "Worker", "Bleep", 100); mickeysMarket.addPerson(null, "Customer", "Beebop", 100); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == panelB) { CardLayout cl = (CardLayout)(cards.getLayout()); if (currP == Panel.pizza) { System.out.println("showing housing"); cl.show(cards, "Housing"); currP = Panel.housing; } else if (currP == Panel.housing) { System.out.println("showing market"); cl.show(cards, "Market"); currP = Panel.market; } else if (currP == Panel.market) { System.out.println("showing rancho"); cl.show(cards, "Rancho"); currP = Panel.rancho; } else if (currP == Panel.rancho) { System.out.println("showing bayou"); cl.show(cards, "Bayou"); currP = Panel.bayou; } else if (currP == Panel.bayou) { System.out.println("showing pizza"); cl.show(cards, "Pizza"); currP = Panel.pizza; } } } }
modified simcitygui
src/simcity/gui/SimCityGui.java
modified simcitygui
<ide><path>rc/simcity/gui/SimCityGui.java <ide> restRancho = new RestaurantRancho(this, "Rancho Del Zocalo"); <ide> restBayou = new RestaurantBayou(this, "The Blue Bayou"); <ide> restPizza = new RestaurantPizza(this); <del> <del> simCityPanel = new SimCityPanel(this); <del> <ide> hauntedMansion = new Housing(this, "Haunted Mansion"); <ide> mickeysMarket = new Market(this, "Mickey's Market"); <add> <add> simCityPanel = new SimCityPanel(this); <ide> <ide> setLayout(new GridBagLayout()); <ide> setBounds(WINDOWX/20, WINDOWX/20, WINDOWX, WINDOWY); <ide> restPizza.addPerson(null, "Host", "Host", 50); <ide> restPizza.addPerson(null, "Customer", "Sally", 50); <ide> <del> mickeysMarket.addPerson(null, "Manager", "MRAWP", 100); <del> mickeysMarket.addPerson(null, "Cashier", "Kapow", 100); <del> mickeysMarket.addPerson(null, "Worker", "Bleep", 100); <del> mickeysMarket.addPerson(null, "Customer", "Beebop", 100); <add> mickeysMarket.addPerson(null, "Manager", "MRAWP", 100, ""); <add> mickeysMarket.addPerson(null, "Cashier", "Kapow", 100, ""); <add> mickeysMarket.addPerson(null, "Worker", "Bleep", 100, ""); <add> mickeysMarket.addPerson(null, "Customer", "Beebop", 100, "American"); <ide> <ide> } <ide>
Java
mit
f61e13db851874d27f4a580aabaa50781c2454e8
0
opacapp/opacclient,raphaelm/opacclient,ruediger-w/opacclient,ruediger-w/opacclient,johan12345/opacclient,ruediger-w/opacclient,opacapp/opacclient,ruediger-w/opacclient,raphaelm/opacclient,raphaelm/opacclient,opacapp/opacclient,johan12345/opacclient,opacapp/opacclient,johan12345/opacclient,johan12345/opacclient,johan12345/opacclient,opacapp/opacclient,geomcmaster/opacclient,geomcmaster/opacclient,ruediger-w/opacclient,geomcmaster/opacclient
/** * Copyright (C) 2013 by Raphael Michel under the MIT license: * * 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 de.geeksfactory.opacclient.barcode; import android.app.Activity; import android.support.v7.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import de.geeksfactory.opacclient.R; import de.geeksfactory.opacclient.utils.CompatibilityUtils; public class BarcodeScanIntegrator { public static final int REQUEST_CODE_QRDROID = 0x0000094c; public static final int REQUEST_CODE_ZXING = 0x0000094d; private Activity ctx = null; public BarcodeScanIntegrator(Activity ctx) { this.ctx = ctx; } public static ScanResult parseActivityResult(int requestCode, int resultCode, Intent idata) { if (resultCode != Activity.RESULT_OK || idata == null || idata.getExtras() == null) { return null; } if (requestCode == REQUEST_CODE_QRDROID) { String result = idata.getExtras().getString("la.droid.qr.result"); return new ScanResult(result, null); } else if (requestCode == REQUEST_CODE_ZXING) { String contents = idata.getStringExtra("SCAN_RESULT"); String formatName = idata.getStringExtra("SCAN_RESULT_FORMAT"); return new ScanResult(contents, formatName); } else { return null; } } private static Collection<String> list(String... values) { return Collections.unmodifiableCollection(Arrays.asList(values)); } public void initiateScan() { PackageManager pm = ctx.getPackageManager(); // TODO: We should probably use PackageManager.getInstalledPackages() and iterate through // all of them to avoid those try/catch-blocks try { pm.getPackageInfo("com.google.zxing.client.android", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("com.srowen.bs.android", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("com.srowen.bs.android.simple", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("com.srowen.bs.android.simple", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("la.droid.qr", 0); initiate_scan_qrdroid(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("la.droid.qr.priva", 0); initiate_scan_qrdroid(); return; } catch (NameNotFoundException e) { } download_dialog(); } public void download_dialog() { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(ctx); downloadDialog.setTitle(R.string.barcode_title); downloadDialog.setMessage(R.string.barcode_desc); downloadDialog.setPositiveButton(R.string.barcode_gplay, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri .parse("market://details?id=com.google.zxing.client.android"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { ctx.startActivity(intent); } catch (ActivityNotFoundException anfe) { // Hmm, market is not installed } } }); downloadDialog.setNeutralButton(R.string.barcode_amazon, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri .parse("http://www.amazon.com/gp/mas/dl/android?p=com.google" + ".zxing.client.android"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); ctx.startActivity(intent); } }); downloadDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog alert = downloadDialog.create(); alert.show(); } public void initiate_scan_zxing() { /*final Collection<String> desiredBarcodeFormats = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128");*/ Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); intentScan.addCategory(Intent.CATEGORY_DEFAULT); // check which types of codes to scan for /*if (desiredBarcodeFormats != null) { // set the desired barcode types StringBuilder joinedByComma = new StringBuilder(); for (String format : desiredBarcodeFormats) { if (joinedByComma.length() > 0) { joinedByComma.append(','); } joinedByComma.append(format); } intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString()); }*/ String targetAppPackage = findTargetAppPackage(intentScan); if (targetAppPackage == null) { download_dialog(); return; } intentScan.setPackage(targetAppPackage); intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intentScan.addFlags(CompatibilityUtils.getNewDocumentIntentFlag()); ctx.startActivityForResult(intentScan, REQUEST_CODE_ZXING); } private String findTargetAppPackage(Intent intent) { final Collection<String> targetApplications = list( "com.google.zxing.client.android", "com.srowen.bs.android", "com.srowen.bs.android.simple"); PackageManager pm = ctx.getPackageManager(); List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (availableApps != null) { for (ResolveInfo availableApp : availableApps) { String packageName = availableApp.activityInfo.packageName; if (targetApplications.contains(packageName)) { return packageName; } } } return null; } public void initiate_scan_qrdroid() { Intent qrDroid = new Intent("la.droid.qr.scan"); qrDroid.putExtra("la.droid.qr.complete", true); ctx.startActivityForResult(qrDroid, REQUEST_CODE_QRDROID); } public static class ScanResult { private final String contents; private final String formatName; public ScanResult(String contents, String formatName) { this.contents = contents; this.formatName = formatName; } /** * @return raw content of barcode */ public String getContents() { return contents; } /** * @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more * format names. */ public String getFormatName() { return formatName; } } }
opacclient/opacapp/src/main/java/de/geeksfactory/opacclient/barcode/BarcodeScanIntegrator.java
/** * Copyright (C) 2013 by Raphael Michel under the MIT license: * * 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 de.geeksfactory.opacclient.barcode; import android.app.Activity; import android.support.v7.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import de.geeksfactory.opacclient.R; import de.geeksfactory.opacclient.utils.CompatibilityUtils; public class BarcodeScanIntegrator { public static final int REQUEST_CODE_QRDROID = 0x0000094c; public static final int REQUEST_CODE_ZXING = 0x0000094d; private Activity ctx = null; public BarcodeScanIntegrator(Activity ctx) { this.ctx = ctx; } public static ScanResult parseActivityResult(int requestCode, int resultCode, Intent idata) { if (resultCode != Activity.RESULT_OK || idata == null || idata.getExtras() == null) { return null; } if (requestCode == REQUEST_CODE_QRDROID) { String result = idata.getExtras().getString("la.droid.qr.result"); return new ScanResult(result, null); } else if (requestCode == REQUEST_CODE_ZXING) { String contents = idata.getStringExtra("SCAN_RESULT"); String formatName = idata.getStringExtra("SCAN_RESULT_FORMAT"); return new ScanResult(contents, formatName); } else { return null; } } private static Collection<String> list(String... values) { return Collections.unmodifiableCollection(Arrays.asList(values)); } public void initiateScan() { PackageManager pm = ctx.getPackageManager(); // TODO: We should probably use PackageManager.getInstalledPackages() and iterate through // all of them to avoid those try/catch-blocks try { pm.getPackageInfo("com.google.zxing.client.android", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("com.srowen.bs.android", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("com.srowen.bs.android.simple", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("com.srowen.bs.android.simple", 0); initiate_scan_zxing(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("la.droid.qr", 0); initiate_scan_qrdroid(); return; } catch (NameNotFoundException e) { } try { pm.getPackageInfo("la.droid.qr.priva", 0); initiate_scan_qrdroid(); return; } catch (NameNotFoundException e) { } download_dialog(); } public void download_dialog() { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(ctx); downloadDialog.setTitle(R.string.barcode_title); downloadDialog.setMessage(R.string.barcode_desc); downloadDialog.setPositiveButton(R.string.barcode_gplay, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri .parse("market://details?id=com.google.zxing.client.android"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { ctx.startActivity(intent); } catch (ActivityNotFoundException anfe) { // Hmm, market is not installed } } }); downloadDialog.setNeutralButton(R.string.barcode_amazon, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri .parse("http://www.amazon.com/gp/mas/dl/android?p=com.google" + ".zxing.client.android"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); ctx.startActivity(intent); } }); downloadDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog alert = downloadDialog.create(); alert.show(); } public void initiate_scan_zxing() { final Collection<String> desiredBarcodeFormats = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128"); Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); intentScan.addCategory(Intent.CATEGORY_DEFAULT); // check which types of codes to scan for if (desiredBarcodeFormats != null) { // set the desired barcode types StringBuilder joinedByComma = new StringBuilder(); for (String format : desiredBarcodeFormats) { if (joinedByComma.length() > 0) { joinedByComma.append(','); } joinedByComma.append(format); } intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString()); } String targetAppPackage = findTargetAppPackage(intentScan); if (targetAppPackage == null) { download_dialog(); return; } intentScan.setPackage(targetAppPackage); intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intentScan.addFlags(CompatibilityUtils.getNewDocumentIntentFlag()); ctx.startActivityForResult(intentScan, REQUEST_CODE_ZXING); } private String findTargetAppPackage(Intent intent) { final Collection<String> targetApplications = list( "com.google.zxing.client.android", "com.srowen.bs.android", "com.srowen.bs.android.simple"); PackageManager pm = ctx.getPackageManager(); List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (availableApps != null) { for (ResolveInfo availableApp : availableApps) { String packageName = availableApp.activityInfo.packageName; if (targetApplications.contains(packageName)) { return packageName; } } } return null; } public void initiate_scan_qrdroid() { Intent qrDroid = new Intent("la.droid.qr.scan"); qrDroid.putExtra("la.droid.qr.complete", true); ctx.startActivityForResult(qrDroid, REQUEST_CODE_QRDROID); } public static class ScanResult { private final String contents; private final String formatName; public ScanResult(String contents, String formatName) { this.contents = contents; this.formatName = formatName; } /** * @return raw content of barcode */ public String getContents() { return contents; } /** * @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more * format names. */ public String getFormatName() { return formatName; } } }
Enable QR scanning (because why not?)
opacclient/opacapp/src/main/java/de/geeksfactory/opacclient/barcode/BarcodeScanIntegrator.java
Enable QR scanning (because why not?)
<ide><path>pacclient/opacapp/src/main/java/de/geeksfactory/opacclient/barcode/BarcodeScanIntegrator.java <ide> } <ide> <ide> public void initiate_scan_zxing() { <del> final Collection<String> desiredBarcodeFormats = list("UPC_A", "UPC_E", <del> "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128"); <add> /*final Collection<String> desiredBarcodeFormats = list("UPC_A", "UPC_E", <add> "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128");*/ <ide> <ide> Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); <ide> intentScan.addCategory(Intent.CATEGORY_DEFAULT); <ide> <ide> // check which types of codes to scan for <del> if (desiredBarcodeFormats != null) { <add> /*if (desiredBarcodeFormats != null) { <ide> // set the desired barcode types <ide> StringBuilder joinedByComma = new StringBuilder(); <ide> for (String format : desiredBarcodeFormats) { <ide> joinedByComma.append(format); <ide> } <ide> intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString()); <del> } <add> }*/ <ide> <ide> String targetAppPackage = findTargetAppPackage(intentScan); <ide> if (targetAppPackage == null) {
JavaScript
mit
3c8e00182d569220b6b675be874301e2a0e7d30c
0
tpoikela/battles,tpoikela/battles,tpoikela/battles,tpoikela/battles,tpoikela/battles
/* Base class foe entities such as actors and items in the game. Each entity can * contain any number of components. The base class provides functionality such * as emitting specific events when component is added/removed. Each entity has * also unique ID which is preserved throughout single game. */ const RG = require('./rg'); export default class Entity { constructor() { this._id = Entity.idCount++; this._comps = {}; } getID() {return this._id;} setID(id) {this._id = id;} /* Gets component with given name. If entity has multiple of them, returns * the first found. */ get(name) { const compList = this.getList(name); if (compList.length > 0) { return compList[0]; } return null; } getList(typeName) { const comps = Object.values(this._comps); return comps.filter(comp => comp.getType() === typeName); } /* Adds a new component into the entity. */ add(nameOrComp, comp) { let compName = nameOrComp; let compObj = comp; if (typeof nameOrComp === 'object') { compObj = nameOrComp; compName = nameOrComp.getType(); } this._comps[compObj.getID()] = compObj; compObj.entityAddCallback(this); RG.POOL.emitEvent(compName, {entity: this, add: true}); } has(name) { const compList = this.getList(name); return compList.length > 0; } /* Removes given component type or component. If string is given, removes * the first matching, otherwise removes by comp ID. */ remove(nameOrComp) { if (typeof nameOrComp === 'object') { const id = nameOrComp.getID(); if (this._comps.hasOwnProperty(id)) { const comp = this._comps[id]; const compName = comp.getType(); comp.entityRemoveCallback(this); delete this._comps[id]; RG.POOL.emitEvent(compName, {entity: this, remove: true}); } } else { const compList = this.getList(nameOrComp); if (compList.length > 0) { this.remove(compList[0]); } } } /* Removes all components of the given type. */ removeAll(nameOrComp) { let compName = nameOrComp; if (typeof nameOrComp === 'object') { compName = nameOrComp.getType(); } const list = this.getList(compName); list.forEach(comp => {this.remove(comp);}); } /* Replaces ALL components of given type. */ replace(nameOrComp, comp) { this.removeAll(nameOrComp); if (comp) { this.add(nameOrComp, comp); } else { this.add(nameOrComp); } } getComponents() {return this._comps;} } Entity.idCount = 0; Entity.createEntityID = () => { const id = Entity.prototype.idCount; Entity.prototype.idCount += 1; return id; }; Entity.getIDCount = () => Entity.idCount;
client/src/entity.js
/* Base class foe entities such as actors and items in the game. Each entity can * contain any number of components. The base class provides functionality such * as emitting specific events when component is added/removed. Each entity has * also unique ID which is preserved throughout single game. */ const RG = require('./rg'); export default class Entity { constructor() { this._id = Entity.idCount++; this._comps = {}; } getID() {return this._id;} setID(id) {this._id = id;} get(name) { if (this._comps.hasOwnProperty(name)) {return this._comps[name];} return null; } add(nameOrComp, comp) { let compName = nameOrComp; let compObj = comp; if (typeof nameOrComp === 'object') { compObj = nameOrComp; compName = nameOrComp.getType(); } this._comps[compName] = compObj; compObj.entityAddCallback(this); RG.POOL.emitEvent(compName, {entity: this, add: true}); } has(name) { return this._comps.hasOwnProperty(name); } remove(name) { if (this._comps.hasOwnProperty(name)) { const comp = this._comps[name]; comp.entityRemoveCallback(this); delete this._comps[name]; RG.POOL.emitEvent(name, {entity: this, remove: true}); } } getComponents() {return this._comps;} } Entity.idCount = 0; Entity.createEntityID = () => { const id = Entity.prototype.idCount; Entity.prototype.idCount += 1; return id; }; Entity.getIDCount = () => Entity.idCount;
Added support for multiple comps of same type. Issue was raised by Shield spell.
client/src/entity.js
Added support for multiple comps of same type. Issue was raised by Shield spell.
<ide><path>lient/src/entity.js <ide> getID() {return this._id;} <ide> setID(id) {this._id = id;} <ide> <add> /* Gets component with given name. If entity has multiple of them, returns <add> * the first found. */ <ide> get(name) { <del> if (this._comps.hasOwnProperty(name)) {return this._comps[name];} <add> const compList = this.getList(name); <add> if (compList.length > 0) { <add> return compList[0]; <add> } <ide> return null; <ide> } <ide> <add> getList(typeName) { <add> const comps = Object.values(this._comps); <add> return comps.filter(comp => comp.getType() === typeName); <add> } <add> <add> /* Adds a new component into the entity. */ <ide> add(nameOrComp, comp) { <ide> let compName = nameOrComp; <ide> let compObj = comp; <ide> compObj = nameOrComp; <ide> compName = nameOrComp.getType(); <ide> } <del> this._comps[compName] = compObj; <add> this._comps[compObj.getID()] = compObj; <ide> compObj.entityAddCallback(this); <ide> RG.POOL.emitEvent(compName, {entity: this, add: true}); <ide> } <ide> <ide> has(name) { <del> return this._comps.hasOwnProperty(name); <add> const compList = this.getList(name); <add> return compList.length > 0; <ide> } <ide> <del> remove(name) { <del> if (this._comps.hasOwnProperty(name)) { <del> const comp = this._comps[name]; <del> comp.entityRemoveCallback(this); <del> delete this._comps[name]; <del> RG.POOL.emitEvent(name, {entity: this, remove: true}); <add> /* Removes given component type or component. If string is given, removes <add> * the first matching, otherwise removes by comp ID. <add> */ <add> remove(nameOrComp) { <add> if (typeof nameOrComp === 'object') { <add> const id = nameOrComp.getID(); <add> if (this._comps.hasOwnProperty(id)) { <add> const comp = this._comps[id]; <add> const compName = comp.getType(); <add> comp.entityRemoveCallback(this); <add> delete this._comps[id]; <add> RG.POOL.emitEvent(compName, {entity: this, remove: true}); <add> } <add> } <add> else { <add> const compList = this.getList(nameOrComp); <add> if (compList.length > 0) { <add> this.remove(compList[0]); <add> } <add> } <add> } <add> <add> /* Removes all components of the given type. */ <add> removeAll(nameOrComp) { <add> let compName = nameOrComp; <add> if (typeof nameOrComp === 'object') { <add> compName = nameOrComp.getType(); <add> } <add> const list = this.getList(compName); <add> list.forEach(comp => {this.remove(comp);}); <add> } <add> <add> /* Replaces ALL components of given type. */ <add> replace(nameOrComp, comp) { <add> this.removeAll(nameOrComp); <add> if (comp) { <add> this.add(nameOrComp, comp); <add> } <add> else { <add> this.add(nameOrComp); <ide> } <ide> } <ide>
Java
mit
662cbea2da30537b6153c07aea0c5a6e6c2b0968
0
trendrr/java-oss-lib,MarkG/java-oss-lib
/** * */ package com.trendrr.oss.casting; import com.trendrr.oss.StringHelper; import com.trendrr.oss.TypeCast; /** * @author Dustin Norlander * @created Nov 30, 2010 * */ public class NumberCaster extends TypeCaster<Number> { /* (non-Javadoc) * @see com.trendrr.oss.casting.TypeCaster#cast(java.lang.Object) */ @Override protected Number doCast(Class cls, Object obj) { try { if (obj instanceof Number) { Number num = (Number)obj; return this.fromNumber(cls, num); } //we remove characters that could resonably be associated with a number String str = TypeCast.cast(String.class, obj); if (str == null) return null; // We need to count on this string being only a number. // if we are too aggressive things like {this:70} will parse to a number when we don't want it to. str = StringHelper.removeAll(TypeCast.cast(String.class, obj), ' ', ',', '$').trim(); if (cls.equals(Long.class)) { return Long.parseLong(str); } else { //just parse to a double and try again. Double num = Double.parseDouble(str); if (num.isInfinite() || num.isNaN()) return null; return this.fromNumber(cls, num); } } catch (Exception x) { } return null; } private Number fromNumber(Class cls, Number num) { if (cls.equals(Number.class)) { return num; } if (cls.equals(Byte.class)) { return num.byteValue(); } if (cls.equals(Short.class)) { return num.shortValue(); } if (cls.equals(Integer.class)) { return num.intValue(); } if (cls.equals(Double.class)) { return num.doubleValue(); } if (cls.equals(Long.class)) { return num.longValue(); } if (cls.equals(Float.class)) { return num.floatValue(); } return null; } }
src/main/com/trendrr/oss/casting/NumberCaster.java
/** * */ package com.trendrr.oss.casting; import com.trendrr.oss.StringHelper; import com.trendrr.oss.TypeCast; /** * @author Dustin Norlander * @created Nov 30, 2010 * */ public class NumberCaster extends TypeCaster<Number> { /* (non-Javadoc) * @see com.trendrr.oss.casting.TypeCaster#cast(java.lang.Object) */ @Override protected Number doCast(Class cls, Object obj) { try { if (obj instanceof Number) { Number num = (Number)obj; return this.fromNumber(cls, num); } //we remove characters that could resonably be associated with a number String str = TypeCast.cast(String.class, obj); if (str == null) return null; str = str.replaceAll("[^0-9\\.\\-eE]", "");//StringHelper.removeAll(TypeCast.cast(String.class, obj), ' ', ',', '$'); if (cls.equals(Long.class)) { return Long.parseLong(str); } else { //just parse to a double and try again. Double num = Double.parseDouble(str); if (num.isInfinite() || num.isNaN()) return null; return this.fromNumber(cls, num); } } catch (Exception x) { } return null; } private Number fromNumber(Class cls, Number num) { if (cls.equals(Number.class)) { return num; } if (cls.equals(Byte.class)) { return num.byteValue(); } if (cls.equals(Short.class)) { return num.shortValue(); } if (cls.equals(Integer.class)) { return num.intValue(); } if (cls.equals(Double.class)) { return num.doubleValue(); } if (cls.equals(Long.class)) { return num.longValue(); } if (cls.equals(Float.class)) { return num.floatValue(); } return null; } }
revert back to minimal cleaning of string before we try to parse the number
src/main/com/trendrr/oss/casting/NumberCaster.java
revert back to minimal cleaning of string before we try to parse the number
<ide><path>rc/main/com/trendrr/oss/casting/NumberCaster.java <ide> String str = TypeCast.cast(String.class, obj); <ide> if (str == null) <ide> return null; <del> str = str.replaceAll("[^0-9\\.\\-eE]", "");//StringHelper.removeAll(TypeCast.cast(String.class, obj), ' ', ',', '$'); <add> // We need to count on this string being only a number. <add> // if we are too aggressive things like {this:70} will parse to a number when we don't want it to. <add> str = StringHelper.removeAll(TypeCast.cast(String.class, obj), ' ', ',', '$').trim(); <ide> <ide> if (cls.equals(Long.class)) { <ide> return Long.parseLong(str);
Java
apache-2.0
ab4fb7a22f34adaae4a45429a117f7a89b4acfdf
0
slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer,slipstream/SlipStreamServer
package com.sixsq.slipstream.persistence; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -=================================================================- */ import java.io.Serializable; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Lob; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; import org.simpleframework.xml.Attribute; import com.sixsq.slipstream.exceptions.ValidationException; @MappedSuperclass @SuppressWarnings("serial") public abstract class Metadata implements Serializable { protected Date creation = new Date(); @Attribute(required = false) @Temporal(TemporalType.TIMESTAMP) protected Date lastModified; @SuppressWarnings("unused") @Deprecated private int jpaVersion; @Attribute(required = false) protected ModuleCategory category; @Attribute(required = false) @Lob protected String description; @Attribute(required = false) protected boolean deleted; protected Metadata() { } public abstract String getResourceUri(); public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public String getParent() { return ""; } public abstract String getName(); public abstract void setName(String name) throws ValidationException; @Attribute(required = false) @Temporal(TemporalType.TIMESTAMP) public Date getCreation() { return creation; } @Attribute(required = false) @Temporal(TemporalType.TIMESTAMP) public void setCreation(Date creation) { this.creation = creation; } public Date getLastModified() { return lastModified; } public void setLastModified() { this.lastModified = new Date(); } public ModuleCategory getCategory() { return category; } public void setCategory(ModuleCategory category) { this.category = category; } public void setCategory(String category) { this.category = ModuleCategory.valueOf(category); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public static String URLEncode(String url) { if (url == null) { return url; } return url.replace(" ", "+"); } public void validate() throws ValidationException { boolean isInvalid = false; isInvalid = (getName() == null) || ("".equals(getName())); if (isInvalid) { throw (new ValidationException("Name cannot be empty")); } } public Metadata store() { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); Metadata obj = em.merge(this); transaction.commit(); em.close(); return obj; } public void remove() { remove(getResourceUri(), this.getClass()); } public static void remove(String resourceUri, Class<? extends Metadata> c) { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); Metadata fromDb = em.find(c, resourceUri); if (fromDb != null) { em.remove(fromDb); } transaction.commit(); em.close(); } protected void throwValidationException(String error) throws ValidationException { throw new ValidationException(error); } protected Metadata copyTo(Metadata copy) throws ValidationException { copy.setCreation(getCreation()); copy.setLastModified(); copy.setCategory(getCategory()); copy.setDeleted(deleted); copy.setDescription(getDescription()); copy.setName(getName()); return copy; } /** * Fix deserialization (e.g. from xml) lists and maps containers. */ public void postDeserialization() { } }
jar-persistence/src/main/java/com/sixsq/slipstream/persistence/Metadata.java
package com.sixsq.slipstream.persistence; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.com) * ===== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -=================================================================- */ import java.io.Serializable; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.Lob; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; import org.simpleframework.xml.Attribute; import com.sixsq.slipstream.exceptions.ValidationException; @MappedSuperclass @SuppressWarnings("serial") public abstract class Metadata implements Serializable { protected Date creation = new Date(); @Attribute(required = false) @Temporal(TemporalType.TIMESTAMP) protected Date lastModified; @Version private int jpaVersion; @Attribute(required = false) protected ModuleCategory category; @Attribute(required = false) @Lob protected String description; @Attribute(required = false) protected boolean deleted; protected Metadata() { } public abstract String getResourceUri(); public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public String getParent() { return ""; } public abstract String getName(); public abstract void setName(String name) throws ValidationException; @Attribute(required = false) @Temporal(TemporalType.TIMESTAMP) public Date getCreation() { return creation; } @Attribute(required = false) @Temporal(TemporalType.TIMESTAMP) public void setCreation(Date creation) { this.creation = creation; } public Date getLastModified() { return lastModified; } public void setLastModified() { this.lastModified = new Date(); } public ModuleCategory getCategory() { return category; } public void setCategory(ModuleCategory category) { this.category = category; } public void setCategory(String category) { this.category = ModuleCategory.valueOf(category); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public static String URLEncode(String url) { if (url == null) { return url; } return url.replace(" ", "+"); } public void validate() throws ValidationException { boolean isInvalid = false; isInvalid = (getName() == null) || ("".equals(getName())); if (isInvalid) { throw (new ValidationException("Name cannot be empty")); } } public Metadata store() { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); Metadata obj = em.merge(this); transaction.commit(); em.close(); return obj; } public void remove() { remove(getResourceUri(), this.getClass()); } public static void remove(String resourceUri, Class<? extends Metadata> c) { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); Metadata fromDb = em.find(c, resourceUri); if (fromDb != null) { em.remove(fromDb); } transaction.commit(); em.close(); } protected void throwValidationException(String error) throws ValidationException { throw new ValidationException(error); } protected Metadata copyTo(Metadata copy) throws ValidationException { copy.setCreation(getCreation()); copy.setLastModified(); copy.setCategory(getCategory()); copy.setDeleted(deleted); copy.setDescription(getDescription()); copy.setName(getName()); return copy; } /** * Fix deserialization (e.g. from xml) lists and maps containers. */ public void postDeserialization() { } }
Remove Version attribute Lost reason for having used it Deprecated field
jar-persistence/src/main/java/com/sixsq/slipstream/persistence/Metadata.java
Remove Version attribute Lost reason for having used it Deprecated field
<ide><path>ar-persistence/src/main/java/com/sixsq/slipstream/persistence/Metadata.java <ide> @Temporal(TemporalType.TIMESTAMP) <ide> protected Date lastModified; <ide> <del> @Version <add> @SuppressWarnings("unused") <add> @Deprecated <ide> private int jpaVersion; <ide> <ide> @Attribute(required = false)
Java
bsd-3-clause
1fda4aa9fe22af878b4f75532e6bf570c75d4361
0
NCIP/catissue-advanced-query,NCIP/catissue-advanced-query
package edu.wustl.common.query.impl; /** * QueryIdentifier is responsible for solely * identifying a query * * @author ravindra_jain * @version 1.0 * */ public class QueryIdentifierObject { private int queryId; private int userId; /** * DEFAULT CONSTRUCTOR */ public QueryIdentifierObject() { } /** * CONSTRUCTOR */ public QueryIdentifierObject(int queryId, int userId) { this.queryId = queryId; this.userId = userId; } /** * * @return */ public int getQueryId() { return queryId; } /** * * @return */ public int getUserId() { return userId; } /** * * @param queryId */ public void setQueryId(int queryId) { this.queryId = queryId; } /** * * @param userId */ public void setUserId(int userId) { this.userId = userId; } @Override public boolean equals(Object obj) { if (this.getClass().getName().equals(obj.getClass().getName())) { QueryIdentifierObject queryIdObj = (QueryIdentifierObject) obj; if(this.queryId == queryIdObj.queryId && this.userId == queryIdObj.userId) { return true; } } return false; } }
WEB-INF/src/edu/wustl/common/query/impl/QueryIdentifierObject.java
package edu.wustl.common.query.impl; import edu.wustl.common.beans.NameValueBean; /** * QueryIdentifier is responsible for solely * identifying a query * * @author ravindra_jain * @version 1.0 * */ public class QueryIdentifierObject { private int queryId; private int userId; /** * DEFAULT CONSTRUCTOR */ public QueryIdentifierObject() { } /** * CONSTRUCTOR */ public QueryIdentifierObject(int queryId, int userId) { this.queryId = queryId; this.userId = userId; } /** * * @return */ public int getQueryId() { return queryId; } /** * * @return */ public int getUserId() { return userId; } /** * * @param queryId */ public void setQueryId(int queryId) { this.queryId = queryId; } /** * * @param userId */ public void setUserId(int userId) { this.userId = userId; } @Override public boolean equals(Object obj) { if (this.getClass().getName().equals(obj.getClass().getName())) { QueryIdentifierObject queryIdObj = (QueryIdentifierObject) obj; if(this.queryId == queryIdObj.queryId && this.userId == queryIdObj.userId) { return true; } } return false; } }
removed unused imports SVN-Revision: 4431
WEB-INF/src/edu/wustl/common/query/impl/QueryIdentifierObject.java
removed unused imports
<ide><path>EB-INF/src/edu/wustl/common/query/impl/QueryIdentifierObject.java <ide> package edu.wustl.common.query.impl; <ide> <del>import edu.wustl.common.beans.NameValueBean; <ide> <ide> /** <ide> * QueryIdentifier is responsible for solely
Java
mit
acbc121484ba43d9e1322f40823951dcaca7319c
0
kiruthikasp/PushPlugin,kiruthikasp/PushPlugin,kiruthikasp/PushPlugin,kiruthikasp/PushPlugin,kiruthikasp/PushPlugin
src/android/com/adobe/phonegap/push/RingtonePickerActivity.java
package com.adobe.phonegap.push; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import com.google.android.gms.gcm.GcmPubSub; import com.google.android.gms.iid.InstanceID; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import android.net.Uri; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; public class RingtonePickerActivity extends Activity implements OnClickListener{ Ringtone rt; RingtoneManager mRingtoneManager; TextView text; Button button1; Cursor mcursor; Intent Mringtone; String title; @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (rt.isPlaying()) { rt.stop(); } else { } } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //the following appends the cursor with the cursor that is used when the ringtone picker pops up mRingtoneManager = new RingtoneManager(this); mcursor = mRingtoneManager.getCursor(); title = mRingtoneManager.EXTRA_RINGTONE_TITLE; text = (TextView)findViewById(R.id.textadd); button1 = (Button)findViewById(R.id.button01); button1.setOnClickListener(this); } //adds a menu item from the res/menu/menu.xml @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } //adds an action to the button click @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.item1: if (rt.isPlaying()) { rt.stop(); } finish(); break; } return true; } @Override public void onClick(View arg0) { // TODO Auto-generated method stub //Starts the intent or Activity of the ringtone manager, opens popup box Mringtone = new Intent(mRingtoneManager.ACTION_RINGTONE_PICKER); //specifies what type of tone we want, in this case "ringtone", can be notification if you want Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE); //gives the title of the RingtoneManager picker title Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_TITLE, "This is the title Of Your Picker!"); //returns true shows the rest of the song on the device in the default location Mringtone.getBooleanExtra(mRingtoneManager.EXTRA_RINGTONE_INCLUDE_DRM, true); String uri = null; //chooses and keeps the selected item as a uri if ( uri != null ) { Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse( uri )); } else { Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri)null); } startActivityForResult(Mringtone, 0); } protected void onActivityResult(int requestCode, int resultCode, Intent Mringtone) { switch (resultCode) { /* * */ case RESULT_OK: //sents the ringtone that is picked in the Ringtone Picker Dialog Uri uri = Mringtone.getParcelableExtra(mRingtoneManager.EXTRA_RINGTONE_PICKED_URI); //send the output of the selected to a string String test = uri.toString(); //the program creates a "line break" when using the "\n" inside a string value text.setText("\n " + test + "\n " + title); //prints out the result in the console window Log.i("Sample", "uri " + uri); //this passed the ringtone selected from the user to a new method play(uri); //inserts another line break for more data, this times adds the cursor count on the selected item text.append("\n " + mcursor.getCount()); //set default ringtone try { RingtoneManager.setActualDefaultRingtoneUri(this, resultCode, uri); } catch (Exception localException) { } break; } } //this method captures the ringtone from the selection and plays it in the main activity private void play(Uri uri) { // TODO Auto-generated method stub if (uri != null) { //in order to play the ringtone, you need to create a new Ringtone with RingtoneManager and pass it to a variable rt = mRingtoneManager.getRingtone(this, uri); rt.play(); } } }
Delete RingtonePickerActivity.java
src/android/com/adobe/phonegap/push/RingtonePickerActivity.java
Delete RingtonePickerActivity.java
<ide><path>rc/android/com/adobe/phonegap/push/RingtonePickerActivity.java <del>package com.adobe.phonegap.push; <del> <del>import android.app.NotificationManager; <del>import android.content.Context; <del>import android.content.SharedPreferences; <del>import android.os.Bundle; <del>import android.util.Log; <del>import android.content.Context; <del>import android.content.Intent; <del>import android.media.RingtoneManager; <del> <del>import com.google.android.gms.gcm.GcmPubSub; <del>import com.google.android.gms.iid.InstanceID; <del> <del>import org.apache.cordova.CallbackContext; <del>import org.apache.cordova.CordovaInterface; <del>import org.apache.cordova.CordovaPlugin; <del>import org.apache.cordova.CordovaWebView; <del>import org.apache.cordova.PluginResult; <del>import org.json.JSONArray; <del>import android.net.Uri; <del>import org.json.JSONException; <del>import org.json.JSONObject; <del> <del>import java.io.IOException; <del>import java.util.Collections; <del>import java.util.HashSet; <del>import java.util.Iterator; <del> <del>public class RingtonePickerActivity extends Activity implements OnClickListener{ <del> <del>Ringtone rt; <del>RingtoneManager mRingtoneManager; <del>TextView text; <del>Button button1; <del>Cursor mcursor; <del>Intent Mringtone; <del>String title; <del> <del>@Override <del>protected void onDestroy() { <del>// TODO Auto-generated method stub <del>super.onDestroy(); <del>if (rt.isPlaying()) { <del>rt.stop(); <del>} else { <del> <del>} <del>} <del> <del>@Override <del>protected void onPause() { <del>// TODO Auto-generated method stub <del>super.onPause(); <del> <del>} <del> <del>/** Called when the activity is first created. */ <del>@Override <del>public void onCreate(Bundle savedInstanceState) { <del>super.onCreate(savedInstanceState); <del>setContentView(R.layout.main); <del> <del>//the following appends the cursor with the cursor that is used when the ringtone picker pops up <del>mRingtoneManager = new RingtoneManager(this); <del>mcursor = mRingtoneManager.getCursor(); <del>title = mRingtoneManager.EXTRA_RINGTONE_TITLE; <del> <del>text = (TextView)findViewById(R.id.textadd); <del>button1 = (Button)findViewById(R.id.button01); <del>button1.setOnClickListener(this); <del>} <del> <del>//adds a menu item from the res/menu/menu.xml <del>@Override <del>public boolean onCreateOptionsMenu(Menu menu) { <del>MenuInflater inflater = getMenuInflater(); <del>inflater.inflate(R.menu.menu, menu); <del>return true; <del>} <del> <del>//adds an action to the button click <del>@Override <del>public boolean onOptionsItemSelected(MenuItem item) { <del>switch (item.getItemId()) { <del>case R.id.item1: <del>if (rt.isPlaying()) { <del>rt.stop(); <del>} <del>finish(); <del>break; <del>} <del>return true; <del>} <del> <del>@Override <del>public void onClick(View arg0) { <del>// TODO Auto-generated method stub <del>//Starts the intent or Activity of the ringtone manager, opens popup box <del>Mringtone = new Intent(mRingtoneManager.ACTION_RINGTONE_PICKER); <del> <del>//specifies what type of tone we want, in this case "ringtone", can be notification if you want <del>Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE); <del> <del>//gives the title of the RingtoneManager picker title <del>Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_TITLE, "This is the title Of Your Picker!"); <del> <del>//returns true shows the rest of the song on the device in the default location <del>Mringtone.getBooleanExtra(mRingtoneManager.EXTRA_RINGTONE_INCLUDE_DRM, true); <del> <del>String uri = null; <del>//chooses and keeps the selected item as a uri <del>if ( uri != null ) { <del>Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse( uri )); <del>} else { <del>Mringtone.putExtra(mRingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri)null); <del>} <del> <del>startActivityForResult(Mringtone, 0); <del> <del> <del>} <del> <del>protected void onActivityResult(int requestCode, int resultCode, Intent Mringtone) { <del>switch (resultCode) { <del>/* <del>* <del>*/ <del>case RESULT_OK: <del>//sents the ringtone that is picked in the Ringtone Picker Dialog <del>Uri uri = Mringtone.getParcelableExtra(mRingtoneManager.EXTRA_RINGTONE_PICKED_URI); <del> <del>//send the output of the selected to a string <del>String test = uri.toString(); <del> <del>//the program creates a "line break" when using the "\n" inside a string value <del>text.setText("\n " + test + "\n " + title); <del> <del>//prints out the result in the console window <del>Log.i("Sample", "uri " + uri); <del> <del>//this passed the ringtone selected from the user to a new method <del>play(uri); <del> <del>//inserts another line break for more data, this times adds the cursor count on the selected item <del>text.append("\n " + mcursor.getCount()); <del> <del>//set default ringtone <del>try <del>{ <del>RingtoneManager.setActualDefaultRingtoneUri(this, resultCode, uri); <del>} <del>catch (Exception localException) <del>{ <del> <del>} <del>break; <del> <del> <del>} <del> <del>} <del> <del> <del>//this method captures the ringtone from the selection and plays it in the main activity <del>private void play(Uri uri) { <del>// TODO Auto-generated method stub <del>if (uri != null) { <del> <del>//in order to play the ringtone, you need to create a new Ringtone with RingtoneManager and pass it to a variable <del>rt = mRingtoneManager.getRingtone(this, uri); <del>rt.play(); <del> <del>} <del>} <del> <del> <del>}
Java
apache-2.0
34a3d69de3a6e523d5d664a1a251a826842689cd
0
drndos/pentaho-kettle,emartin-pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,ddiroma/pentaho-kettle,Advent51/pentaho-kettle,flbrino/pentaho-kettle,stevewillcock/pentaho-kettle,mbatchelor/pentaho-kettle,sajeetharan/pentaho-kettle,pavel-sakun/pentaho-kettle,jbrant/pentaho-kettle,roboguy/pentaho-kettle,marcoslarsen/pentaho-kettle,rmansoor/pentaho-kettle,hudak/pentaho-kettle,bmorrise/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,denisprotopopov/pentaho-kettle,andrei-viaryshka/pentaho-kettle,CapeSepias/pentaho-kettle,pedrofvteixeira/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,mattyb149/pentaho-kettle,drndos/pentaho-kettle,rfellows/pentaho-kettle,yshakhau/pentaho-kettle,matrix-stone/pentaho-kettle,mattyb149/pentaho-kettle,graimundo/pentaho-kettle,nanata1115/pentaho-kettle,mdamour1976/pentaho-kettle,drndos/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,lgrill-pentaho/pentaho-kettle,mkambol/pentaho-kettle,gretchiemoran/pentaho-kettle,YuryBY/pentaho-kettle,aminmkhan/pentaho-kettle,cjsonger/pentaho-kettle,Advent51/pentaho-kettle,marcoslarsen/pentaho-kettle,DFieldFL/pentaho-kettle,tkafalas/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,tmcsantos/pentaho-kettle,codek/pentaho-kettle,emartin-pentaho/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,brosander/pentaho-kettle,kurtwalker/pentaho-kettle,airy-ict/pentaho-kettle,mkambol/pentaho-kettle,MikhailHubanau/pentaho-kettle,jbrant/pentaho-kettle,YuryBY/pentaho-kettle,flbrino/pentaho-kettle,matrix-stone/pentaho-kettle,tkafalas/pentaho-kettle,codek/pentaho-kettle,ccaspanello/pentaho-kettle,pymjer/pentaho-kettle,kurtwalker/pentaho-kettle,bmorrise/pentaho-kettle,rfellows/pentaho-kettle,MikhailHubanau/pentaho-kettle,wseyler/pentaho-kettle,akhayrutdinov/pentaho-kettle,stepanovdg/pentaho-kettle,birdtsai/pentaho-kettle,zlcnju/kettle,ma459006574/pentaho-kettle,e-cuellar/pentaho-kettle,akhayrutdinov/pentaho-kettle,emartin-pentaho/pentaho-kettle,nanata1115/pentaho-kettle,aminmkhan/pentaho-kettle,birdtsai/pentaho-kettle,SergeyTravin/pentaho-kettle,SergeyTravin/pentaho-kettle,aminmkhan/pentaho-kettle,ivanpogodin/pentaho-kettle,andrei-viaryshka/pentaho-kettle,zlcnju/kettle,EcoleKeine/pentaho-kettle,graimundo/pentaho-kettle,ddiroma/pentaho-kettle,GauravAshara/pentaho-kettle,lgrill-pentaho/pentaho-kettle,zlcnju/kettle,zlcnju/kettle,DFieldFL/pentaho-kettle,roboguy/pentaho-kettle,flbrino/pentaho-kettle,ViswesvarSekar/pentaho-kettle,denisprotopopov/pentaho-kettle,HiromuHota/pentaho-kettle,skofra0/pentaho-kettle,brosander/pentaho-kettle,jbrant/pentaho-kettle,stepanovdg/pentaho-kettle,nantunes/pentaho-kettle,pavel-sakun/pentaho-kettle,sajeetharan/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,wseyler/pentaho-kettle,pentaho/pentaho-kettle,e-cuellar/pentaho-kettle,bmorrise/pentaho-kettle,flbrino/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,ma459006574/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,rfellows/pentaho-kettle,ivanpogodin/pentaho-kettle,tkafalas/pentaho-kettle,CapeSepias/pentaho-kettle,SergeyTravin/pentaho-kettle,airy-ict/pentaho-kettle,sajeetharan/pentaho-kettle,hudak/pentaho-kettle,gretchiemoran/pentaho-kettle,nanata1115/pentaho-kettle,pavel-sakun/pentaho-kettle,matthewtckr/pentaho-kettle,stevewillcock/pentaho-kettle,pentaho/pentaho-kettle,wseyler/pentaho-kettle,e-cuellar/pentaho-kettle,marcoslarsen/pentaho-kettle,pymjer/pentaho-kettle,DFieldFL/pentaho-kettle,pentaho/pentaho-kettle,nicoben/pentaho-kettle,EcoleKeine/pentaho-kettle,aminmkhan/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,HiromuHota/pentaho-kettle,emartin-pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,Advent51/pentaho-kettle,dkincade/pentaho-kettle,akhayrutdinov/pentaho-kettle,EcoleKeine/pentaho-kettle,matrix-stone/pentaho-kettle,GauravAshara/pentaho-kettle,matthewtckr/pentaho-kettle,roboguy/pentaho-kettle,ccaspanello/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,mattyb149/pentaho-kettle,mbatchelor/pentaho-kettle,birdtsai/pentaho-kettle,rmansoor/pentaho-kettle,kurtwalker/pentaho-kettle,mkambol/pentaho-kettle,skofra0/pentaho-kettle,HiromuHota/pentaho-kettle,ViswesvarSekar/pentaho-kettle,rmansoor/pentaho-kettle,mbatchelor/pentaho-kettle,nantunes/pentaho-kettle,bmorrise/pentaho-kettle,tmcsantos/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,tkafalas/pentaho-kettle,sajeetharan/pentaho-kettle,ViswesvarSekar/pentaho-kettle,airy-ict/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,matrix-stone/pentaho-kettle,gretchiemoran/pentaho-kettle,cjsonger/pentaho-kettle,birdtsai/pentaho-kettle,CapeSepias/pentaho-kettle,mdamour1976/pentaho-kettle,YuryBY/pentaho-kettle,alina-ipatina/pentaho-kettle,CapeSepias/pentaho-kettle,wseyler/pentaho-kettle,matthewtckr/pentaho-kettle,HiromuHota/pentaho-kettle,yshakhau/pentaho-kettle,matthewtckr/pentaho-kettle,eayoungs/pentaho-kettle,nantunes/pentaho-kettle,dkincade/pentaho-kettle,airy-ict/pentaho-kettle,pedrofvteixeira/pentaho-kettle,ccaspanello/pentaho-kettle,yshakhau/pentaho-kettle,andrei-viaryshka/pentaho-kettle,alina-ipatina/pentaho-kettle,pedrofvteixeira/pentaho-kettle,gretchiemoran/pentaho-kettle,yshakhau/pentaho-kettle,rmansoor/pentaho-kettle,codek/pentaho-kettle,hudak/pentaho-kettle,cjsonger/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,hudak/pentaho-kettle,GauravAshara/pentaho-kettle,eayoungs/pentaho-kettle,graimundo/pentaho-kettle,mkambol/pentaho-kettle,mattyb149/pentaho-kettle,cjsonger/pentaho-kettle,pentaho/pentaho-kettle,tmcsantos/pentaho-kettle,jbrant/pentaho-kettle,alina-ipatina/pentaho-kettle,eayoungs/pentaho-kettle,ViswesvarSekar/pentaho-kettle,skofra0/pentaho-kettle,e-cuellar/pentaho-kettle,pavel-sakun/pentaho-kettle,DFieldFL/pentaho-kettle,YuryBY/pentaho-kettle,marcoslarsen/pentaho-kettle,pedrofvteixeira/pentaho-kettle,lgrill-pentaho/pentaho-kettle,dkincade/pentaho-kettle,codek/pentaho-kettle,denisprotopopov/pentaho-kettle,ma459006574/pentaho-kettle,ivanpogodin/pentaho-kettle,nantunes/pentaho-kettle,brosander/pentaho-kettle,stevewillcock/pentaho-kettle,pminutillo/pentaho-kettle,GauravAshara/pentaho-kettle,eayoungs/pentaho-kettle,pminutillo/pentaho-kettle,mdamour1976/pentaho-kettle,ccaspanello/pentaho-kettle,pymjer/pentaho-kettle,EcoleKeine/pentaho-kettle,SergeyTravin/pentaho-kettle,Advent51/pentaho-kettle,akhayrutdinov/pentaho-kettle,skofra0/pentaho-kettle,nicoben/pentaho-kettle,ma459006574/pentaho-kettle,roboguy/pentaho-kettle,alina-ipatina/pentaho-kettle,ivanpogodin/pentaho-kettle,MikhailHubanau/pentaho-kettle,pminutillo/pentaho-kettle,stepanovdg/pentaho-kettle,drndos/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,tmcsantos/pentaho-kettle,nicoben/pentaho-kettle,lgrill-pentaho/pentaho-kettle,ddiroma/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,mbatchelor/pentaho-kettle,brosander/pentaho-kettle,nicoben/pentaho-kettle,ddiroma/pentaho-kettle,pymjer/pentaho-kettle,dkincade/pentaho-kettle,mdamour1976/pentaho-kettle,nanata1115/pentaho-kettle,denisprotopopov/pentaho-kettle,graimundo/pentaho-kettle,pminutillo/pentaho-kettle,stevewillcock/pentaho-kettle
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans.steps.tableinput; import java.util.List; import java.util.Map; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.shared.SharedObjectInterface; import org.pentaho.di.trans.DatabaseImpact; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.w3c.dom.Node; /* * Created on 2-jun-2003 * */ public class TableInputMeta extends BaseStepMeta implements StepMetaInterface { private DatabaseMeta databaseMeta; private String sql; private String rowLimit; /** Which step is providing the date, just the name?*/ private String lookupFromStepname; /** The step to lookup from */ private StepMeta lookupFromStep; /** Should I execute once per row? */ private boolean executeEachInputRow; private boolean variableReplacementActive; private boolean lazyConversionActive; public TableInputMeta() { super(); } /** * @return Returns true if the step should be run per row */ public boolean isExecuteEachInputRow() { return executeEachInputRow; } /** * @param oncePerRow true if the step should be run per row */ public void setExecuteEachInputRow(boolean oncePerRow) { this.executeEachInputRow = oncePerRow; } /** * @return Returns the database. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * @param database The database to set. */ public void setDatabaseMeta(DatabaseMeta database) { this.databaseMeta = database; } /** * @return Returns the rowLimit. */ public String getRowLimit() { return rowLimit; } /** * @param rowLimit The rowLimit to set. */ public void setRowLimit(String rowLimit) { this.rowLimit = rowLimit; } /** * @return Returns the sql. */ public String getSQL() { return sql; } /** * @param sql The sql to set. */ public void setSQL(String sql) { this.sql = sql; } /** * @return Returns the lookupFromStep. */ public StepMeta getLookupFromStep() { return lookupFromStep; } /** * @param lookupFromStep The lookupFromStep to set. */ public void setLookupFromStep(StepMeta lookupFromStep) { this.lookupFromStep = lookupFromStep; } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode, databases); } public Object clone() { TableInputMeta retval = (TableInputMeta)super.clone(); return retval; } private void readData(Node stepnode, List<? extends SharedObjectInterface> databases) throws KettleXMLException { try { databaseMeta = DatabaseMeta.findDatabase(databases, XMLHandler.getTagValue(stepnode, "connection")); sql = XMLHandler.getTagValue(stepnode, "sql"); rowLimit = XMLHandler.getTagValue(stepnode, "limit"); lookupFromStepname = XMLHandler.getTagValue(stepnode, "lookup"); executeEachInputRow = "Y".equals(XMLHandler.getTagValue(stepnode, "execute_each_row")); variableReplacementActive = "Y".equals(XMLHandler.getTagValue(stepnode, "variables_active")); lazyConversionActive = "Y".equals(XMLHandler.getTagValue(stepnode, "lazy_conversion_active")); } catch(Exception e) { throw new KettleXMLException("Unable to load step info from XML", e); } } public void setDefault() { databaseMeta = null; sql = "SELECT <values> FROM <table name> WHERE <conditions>"; rowLimit = "0"; } /** * @return the informational source steps, if any. Null is the default: none. */ public String[] getInfoSteps() { if (getLookupStepname()==null) return null; return new String[] { getLookupStepname() }; } /** * @param infoSteps The info-step(s) to set */ public void setInfoSteps(StepMeta[] infoSteps) { if (infoSteps!=null && infoSteps.length>0) { lookupFromStep = infoSteps[0]; } } public void getFields(RowMetaInterface row, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { if (databaseMeta==null) return; // TODO: throw an exception here boolean param=false; Database db = new Database(loggingObject, databaseMeta); databases = new Database[] { db }; // keep track of it for canceling purposes... // First try without connecting to the database... (can be S L O W) String sNewSQL = sql; if (isVariableReplacementActive()) sNewSQL = db.environmentSubstitute(sql); // TODO SB RowMetaInterface add=null; try { add = db.getQueryFields(sNewSQL, param); } catch(KettleDatabaseException dbe) { throw new KettleStepException("Unable to get queryfields for SQL: "+Const.CR+sNewSQL, dbe); } if (add!=null) { for (int i=0;i<add.size();i++) { ValueMetaInterface v=add.getValueMeta(i); v.setOrigin(origin); } row.addRowMeta( add ); } else { try { db.connect(); RowMetaInterface paramRowMeta=null; Object[] paramData=null; if (getLookupStepname()!=null) { param=true; if (info.length>=0 && info[0]!=null) { paramRowMeta=info[0]; paramData = RowDataUtil.allocateRowData(paramRowMeta.size()); } } add = db.getQueryFields(sNewSQL, param, paramRowMeta, paramData); if (add==null) return; for (int i=0;i<add.size();i++) { ValueMetaInterface v=add.getValueMeta(i); v.setOrigin(origin); } row.addRowMeta( add ); } catch(KettleException ke) { throw new KettleStepException("Unable to get queryfields for SQL: "+Const.CR+sNewSQL, ke); } finally { db.disconnect(); } } } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" "+XMLHandler.addTagValue("connection", databaseMeta==null?"":databaseMeta.getName())); retval.append(" "+XMLHandler.addTagValue("sql", sql)); retval.append(" "+XMLHandler.addTagValue("limit", rowLimit)); retval.append(" "+XMLHandler.addTagValue("lookup", getLookupStepname())); retval.append(" "+XMLHandler.addTagValue("execute_each_row", executeEachInputRow)); retval.append(" "+XMLHandler.addTagValue("variables_active", variableReplacementActive)); retval.append(" "+XMLHandler.addTagValue("lazy_conversion_active", lazyConversionActive)); return retval.toString(); } public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { databaseMeta = rep.loadDatabaseMetaFromStepAttribute(id_step, "id_connection", databases); //$NON-NLS-1$ sql = rep.getStepAttributeString (id_step, "sql"); rowLimit = rep.getStepAttributeString(id_step, "limit"); if (rowLimit==null) { rowLimit = Long.toString( rep.getStepAttributeInteger(id_step, "limit") ); } lookupFromStepname = rep.getStepAttributeString (id_step, "lookup"); executeEachInputRow = rep.getStepAttributeBoolean(id_step, "execute_each_row"); variableReplacementActive = rep.getStepAttributeBoolean(id_step, "variables_active"); lazyConversionActive = rep.getStepAttributeBoolean(id_step, "lazy_conversion_active"); } catch(Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } } public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException { try { rep.saveDatabaseMetaStepAttribute(id_transformation, id_step, "id_connection", databaseMeta); rep.saveStepAttribute(id_transformation, id_step, "sql", sql); rep.saveStepAttribute(id_transformation, id_step, "limit", rowLimit); rep.saveStepAttribute(id_transformation, id_step, "lookup", getLookupStepname()); rep.saveStepAttribute(id_transformation, id_step, "execute_each_row", executeEachInputRow); rep.saveStepAttribute(id_transformation, id_step, "variables_active", variableReplacementActive); rep.saveStepAttribute(id_transformation, id_step, "lazy_conversion_active", lazyConversionActive); // Also, save the step-database relationship! if (databaseMeta!=null) rep.insertStepDatabase(id_transformation, id_step, databaseMeta.getObjectId()); } catch(Exception e) { throw new KettleException("Unable to save step information to the repository for id_step="+id_step, e); } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { CheckResult cr; if (databaseMeta!=null) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "Connection exists", stepMeta); remarks.add(cr); Database db = new Database(loggingObject, databaseMeta); db.shareVariablesWith(transMeta); databases = new Database[] { db }; // keep track of it for canceling purposes... try { db.connect(); cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "Connection to database OK", stepMeta); remarks.add(cr); if (sql!=null && sql.length()!=0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "SQL statement is entered", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "SQL statement is missing.", stepMeta); remarks.add(cr); } } catch(KettleException e) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "An error occurred: "+e.getMessage(), stepMeta); remarks.add(cr); } finally { db.disconnect(); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Please select or create a connection to use", stepMeta); remarks.add(cr); } // See if we have an informative step... if (getLookupStepname()!=null) { boolean found=false; for (int i=0;i<input.length;i++) { if (getLookupStepname().equalsIgnoreCase(input[i])) found=true; } if (found) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "Previous step to read info from ["+getLookupStepname()+"] is found.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Previous step to read info from ["+getLookupStepname()+"] is not found.", stepMeta); remarks.add(cr); } // Count the number of ? in the SQL string: int count=0; for (int i=0;i<sql.length();i++) { char c = sql.charAt(i); if (c=='\'') // skip to next quote! { do { i++; c = sql.charAt(i); } while (c!='\''); } if (c=='?') count++; } // Verify with the number of informative fields... if (info!=null) { if(count == info.size()) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "This step is expecting and receiving "+info.size()+" fields of input from the previous step.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "This step is receiving "+info.size()+" but not the expected "+count+" fields of input from the previous step.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Input step name is not recognized!", stepMeta); remarks.add(cr); } } else { if (input.length>0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Step is not expecting info from input steps.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "No input expected, no input provided.", stepMeta); remarks.add(cr); } } } public String getLookupStepname() { if (lookupFromStep!=null && lookupFromStep.getName()!=null && lookupFromStep.getName().length()>0 ) return lookupFromStep.getName(); return null; } /** * @param steps optionally search the info step in a list of steps */ public void searchInfoAndTargetSteps(List<StepMeta> steps) { lookupFromStep = StepMeta.findStep(steps, lookupFromStepname); } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new TableInput(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new TableInputData(); } public void analyseImpact(List<DatabaseImpact> impact, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) throws KettleStepException { // Find the lookupfields... RowMetaInterface out = new RowMeta(); // TODO: this builds, but does it work in all cases. getFields(out, stepMeta.getName(), new RowMetaInterface[] { info }, null, transMeta); if (out!=null) { for (int i=0;i<out.size();i++) { ValueMetaInterface outvalue = out.getValueMeta(i); DatabaseImpact ii = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_READ, transMeta.getName(), stepMeta.getName(), databaseMeta.getDatabaseName(), "", outvalue.getName(), outvalue.getName(), stepMeta.getName(), sql, "read from one or more database tables via SQL statement" ); impact.add(ii); } } } public DatabaseMeta[] getUsedDatabaseConnections() { if (databaseMeta!=null) { return new DatabaseMeta[] { databaseMeta }; } else { return super.getUsedDatabaseConnections(); } } /** * @return Returns the variableReplacementActive. */ public boolean isVariableReplacementActive() { return variableReplacementActive; } /** * @param variableReplacementActive The variableReplacementActive to set. */ public void setVariableReplacementActive(boolean variableReplacementActive) { this.variableReplacementActive = variableReplacementActive; } /** * @return the lazyConversionActive */ public boolean isLazyConversionActive() { return lazyConversionActive; } /** * @param lazyConversionActive the lazyConversionActive to set */ public void setLazyConversionActive(boolean lazyConversionActive) { this.lazyConversionActive = lazyConversionActive; } }
src/org/pentaho/di/trans/steps/tableinput/TableInputMeta.java
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans.steps.tableinput; import java.util.List; import java.util.Map; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.shared.SharedObjectInterface; import org.pentaho.di.trans.DatabaseImpact; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.w3c.dom.Node; /* * Created on 2-jun-2003 * */ public class TableInputMeta extends BaseStepMeta implements StepMetaInterface { private DatabaseMeta databaseMeta; private String sql; private String rowLimit; /** Which step is providing the date, just the name?*/ private String lookupFromStepname; /** The step to lookup from */ private StepMeta lookupFromStep; /** Should I execute once per row? */ private boolean executeEachInputRow; private boolean variableReplacementActive; private boolean lazyConversionActive; public TableInputMeta() { super(); } /** * @return Returns true if the step should be run per row */ public boolean isExecuteEachInputRow() { return executeEachInputRow; } /** * @param oncePerRow true if the step should be run per row */ public void setExecuteEachInputRow(boolean oncePerRow) { this.executeEachInputRow = oncePerRow; } /** * @return Returns the database. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * @param database The database to set. */ public void setDatabaseMeta(DatabaseMeta database) { this.databaseMeta = database; } /** * @return Returns the rowLimit. */ public String getRowLimit() { return rowLimit; } /** * @param rowLimit The rowLimit to set. */ public void setRowLimit(String rowLimit) { this.rowLimit = rowLimit; } /** * @return Returns the sql. */ public String getSQL() { return sql; } /** * @param sql The sql to set. */ public void setSQL(String sql) { this.sql = sql; } /** * @return Returns the lookupFromStep. */ public StepMeta getLookupFromStep() { return lookupFromStep; } /** * @param lookupFromStep The lookupFromStep to set. */ public void setLookupFromStep(StepMeta lookupFromStep) { this.lookupFromStep = lookupFromStep; } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode, databases); } public Object clone() { TableInputMeta retval = (TableInputMeta)super.clone(); return retval; } private void readData(Node stepnode, List<? extends SharedObjectInterface> databases) throws KettleXMLException { try { databaseMeta = DatabaseMeta.findDatabase(databases, XMLHandler.getTagValue(stepnode, "connection")); sql = XMLHandler.getTagValue(stepnode, "sql"); rowLimit = XMLHandler.getTagValue(stepnode, "limit"); lookupFromStepname = XMLHandler.getTagValue(stepnode, "lookup"); executeEachInputRow = "Y".equals(XMLHandler.getTagValue(stepnode, "execute_each_row")); variableReplacementActive = "Y".equals(XMLHandler.getTagValue(stepnode, "variables_active")); lazyConversionActive = "Y".equals(XMLHandler.getTagValue(stepnode, "lazy_conversion_active")); } catch(Exception e) { throw new KettleXMLException("Unable to load step info from XML", e); } } public void setDefault() { databaseMeta = null; sql = "SELECT <values> FROM <table name> WHERE <conditions>"; rowLimit = "0"; } /** * @return the informational source steps, if any. Null is the default: none. */ public String[] getInfoSteps() { if (getLookupStepname()==null) return null; return new String[] { getLookupStepname() }; } /** * @param infoSteps The info-step(s) to set */ public void setInfoSteps(StepMeta[] infoSteps) { if (infoSteps!=null && infoSteps.length>0) { lookupFromStep = infoSteps[0]; } } public void getFields(RowMetaInterface row, String origin, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { if (databaseMeta==null) return; // TODO: throw an exception here boolean param=false; Database db = new Database(loggingObject, databaseMeta); databases = new Database[] { db }; // keep track of it for canceling purposes... // First try without connecting to the database... (can be S L O W) String sNewSQL = sql; if (isVariableReplacementActive()) sNewSQL = db.environmentSubstitute(sql); // TODO SB RowMetaInterface add=null; try { add = db.getQueryFields(sNewSQL, param); } catch(KettleDatabaseException dbe) { throw new KettleStepException("Unable to get queryfields for SQL: "+Const.CR+sNewSQL, dbe); } if (add!=null) { for (int i=0;i<add.size();i++) { ValueMetaInterface v=add.getValueMeta(i); v.setOrigin(origin); } row.addRowMeta( add ); } else { try { db.connect(); RowMetaInterface paramRowMeta=null; Object[] paramData=null; if (getLookupStepname()!=null) { param=true; if (info.length>=0 && info[0]!=null) { paramRowMeta=info[0]; paramData = RowDataUtil.allocateRowData(paramRowMeta.size()); } } add = db.getQueryFields(sNewSQL, param, paramRowMeta, paramData); if (add==null) return; for (int i=0;i<add.size();i++) { ValueMetaInterface v=add.getValueMeta(i); v.setOrigin(origin); } row.addRowMeta( add ); } catch(KettleException ke) { throw new KettleStepException("Unable to get queryfields for SQL: "+Const.CR+sNewSQL, ke); } finally { db.disconnect(); } } } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" "+XMLHandler.addTagValue("connection", databaseMeta==null?"":databaseMeta.getName())); retval.append(" "+XMLHandler.addTagValue("sql", sql)); retval.append(" "+XMLHandler.addTagValue("limit", rowLimit)); retval.append(" "+XMLHandler.addTagValue("lookup", getLookupStepname())); retval.append(" "+XMLHandler.addTagValue("execute_each_row", executeEachInputRow)); retval.append(" "+XMLHandler.addTagValue("variables_active", variableReplacementActive)); retval.append(" "+XMLHandler.addTagValue("lazy_conversion_active", lazyConversionActive)); return retval.toString(); } public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { databaseMeta = rep.loadDatabaseMetaFromStepAttribute(id_step, "id_connection", databases); //$NON-NLS-1$ sql = rep.getStepAttributeString (id_step, "sql"); String rowLimit = rep.getStepAttributeString(id_step, "limit"); if (rowLimit==null) { rowLimit = Long.toString( rep.getStepAttributeInteger(id_step, "limit") ); } lookupFromStepname = rep.getStepAttributeString (id_step, "lookup"); executeEachInputRow = rep.getStepAttributeBoolean(id_step, "execute_each_row"); variableReplacementActive = rep.getStepAttributeBoolean(id_step, "variables_active"); lazyConversionActive = rep.getStepAttributeBoolean(id_step, "lazy_conversion_active"); } catch(Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } } public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException { try { rep.saveDatabaseMetaStepAttribute(id_transformation, id_step, "id_connection", databaseMeta); rep.saveStepAttribute(id_transformation, id_step, "sql", sql); rep.saveStepAttribute(id_transformation, id_step, "limit", rowLimit); rep.saveStepAttribute(id_transformation, id_step, "lookup", getLookupStepname()); rep.saveStepAttribute(id_transformation, id_step, "execute_each_row", executeEachInputRow); rep.saveStepAttribute(id_transformation, id_step, "variables_active", variableReplacementActive); rep.saveStepAttribute(id_transformation, id_step, "lazy_conversion_active", lazyConversionActive); // Also, save the step-database relationship! if (databaseMeta!=null) rep.insertStepDatabase(id_transformation, id_step, databaseMeta.getObjectId()); } catch(Exception e) { throw new KettleException("Unable to save step information to the repository for id_step="+id_step, e); } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { CheckResult cr; if (databaseMeta!=null) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "Connection exists", stepMeta); remarks.add(cr); Database db = new Database(loggingObject, databaseMeta); db.shareVariablesWith(transMeta); databases = new Database[] { db }; // keep track of it for canceling purposes... try { db.connect(); cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "Connection to database OK", stepMeta); remarks.add(cr); if (sql!=null && sql.length()!=0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "SQL statement is entered", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "SQL statement is missing.", stepMeta); remarks.add(cr); } } catch(KettleException e) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "An error occurred: "+e.getMessage(), stepMeta); remarks.add(cr); } finally { db.disconnect(); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Please select or create a connection to use", stepMeta); remarks.add(cr); } // See if we have an informative step... if (getLookupStepname()!=null) { boolean found=false; for (int i=0;i<input.length;i++) { if (getLookupStepname().equalsIgnoreCase(input[i])) found=true; } if (found) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "Previous step to read info from ["+getLookupStepname()+"] is found.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Previous step to read info from ["+getLookupStepname()+"] is not found.", stepMeta); remarks.add(cr); } // Count the number of ? in the SQL string: int count=0; for (int i=0;i<sql.length();i++) { char c = sql.charAt(i); if (c=='\'') // skip to next quote! { do { i++; c = sql.charAt(i); } while (c!='\''); } if (c=='?') count++; } // Verify with the number of informative fields... if (info!=null) { if(count == info.size()) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "This step is expecting and receiving "+info.size()+" fields of input from the previous step.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "This step is receiving "+info.size()+" but not the expected "+count+" fields of input from the previous step.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Input step name is not recognized!", stepMeta); remarks.add(cr); } } else { if (input.length>0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, "Step is not expecting info from input steps.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, "No input expected, no input provided.", stepMeta); remarks.add(cr); } } } public String getLookupStepname() { if (lookupFromStep!=null && lookupFromStep.getName()!=null && lookupFromStep.getName().length()>0 ) return lookupFromStep.getName(); return null; } /** * @param steps optionally search the info step in a list of steps */ public void searchInfoAndTargetSteps(List<StepMeta> steps) { lookupFromStep = StepMeta.findStep(steps, lookupFromStepname); } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new TableInput(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new TableInputData(); } public void analyseImpact(List<DatabaseImpact> impact, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) throws KettleStepException { // Find the lookupfields... RowMetaInterface out = new RowMeta(); // TODO: this builds, but does it work in all cases. getFields(out, stepMeta.getName(), new RowMetaInterface[] { info }, null, transMeta); if (out!=null) { for (int i=0;i<out.size();i++) { ValueMetaInterface outvalue = out.getValueMeta(i); DatabaseImpact ii = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_READ, transMeta.getName(), stepMeta.getName(), databaseMeta.getDatabaseName(), "", outvalue.getName(), outvalue.getName(), stepMeta.getName(), sql, "read from one or more database tables via SQL statement" ); impact.add(ii); } } } public DatabaseMeta[] getUsedDatabaseConnections() { if (databaseMeta!=null) { return new DatabaseMeta[] { databaseMeta }; } else { return super.getUsedDatabaseConnections(); } } /** * @return Returns the variableReplacementActive. */ public boolean isVariableReplacementActive() { return variableReplacementActive; } /** * @param variableReplacementActive The variableReplacementActive to set. */ public void setVariableReplacementActive(boolean variableReplacementActive) { this.variableReplacementActive = variableReplacementActive; } /** * @return the lazyConversionActive */ public boolean isLazyConversionActive() { return lazyConversionActive; } /** * @param lazyConversionActive the lazyConversionActive to set */ public void setLazyConversionActive(boolean lazyConversionActive) { this.lazyConversionActive = lazyConversionActive; } }
Fixed reading rowLimit into table input step git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@11747 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src/org/pentaho/di/trans/steps/tableinput/TableInputMeta.java
Fixed reading rowLimit into table input step
<ide><path>rc/org/pentaho/di/trans/steps/tableinput/TableInputMeta.java <ide> databaseMeta = rep.loadDatabaseMetaFromStepAttribute(id_step, "id_connection", databases); //$NON-NLS-1$ <ide> <ide> sql = rep.getStepAttributeString (id_step, "sql"); <del> String rowLimit = rep.getStepAttributeString(id_step, "limit"); <add> rowLimit = rep.getStepAttributeString(id_step, "limit"); <ide> if (rowLimit==null) { <ide> rowLimit = Long.toString( rep.getStepAttributeInteger(id_step, "limit") ); <ide> }
Java
apache-2.0
d87983d7f22843e7f86bbbb08549e2599feae4c4
0
Activiti/Activiti,Activiti/Activiti
package org.activiti.spring.boot.process; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import org.activiti.api.process.model.ProcessDefinition; import org.activiti.api.process.model.ProcessInstance; import org.activiti.api.process.model.builders.ProcessPayloadBuilder; import org.activiti.api.process.model.payloads.SignalPayload; import org.activiti.api.process.model.payloads.UpdateProcessPayload; import org.activiti.api.process.runtime.ProcessAdminRuntime; import org.activiti.api.process.runtime.ProcessRuntime; import org.activiti.api.process.runtime.conf.ProcessRuntimeConfiguration; import org.activiti.api.runtime.shared.query.Page; import org.activiti.api.runtime.shared.query.Pageable; import org.activiti.core.common.spring.security.policies.ProcessSecurityPoliciesManager; import org.activiti.engine.RepositoryService; import org.activiti.engine.RuntimeService; import org.activiti.runtime.api.impl.ProcessAdminRuntimeImpl; import org.activiti.runtime.api.impl.ProcessRuntimeImpl; import org.activiti.runtime.api.model.impl.APIProcessDefinitionConverter; import org.activiti.runtime.api.model.impl.APIProcessInstanceConverter; import org.activiti.runtime.api.model.impl.APIVariableInstanceConverter; import org.activiti.spring.boot.RuntimeTestConfiguration; import org.activiti.spring.boot.security.util.SecurityUtil; import org.activiti.spring.boot.test.util.ProcessCleanUpUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.access.AccessDeniedException; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class ProcessRuntimeTest { private static final String CATEGORIZE_PROCESS = "categorizeProcess"; private static final String CATEGORIZE_HUMAN_PROCESS = "categorizeHumanProcess"; private static final String ONE_STEP_PROCESS = "OneStepProcess"; private static final String SUB_PROCESS = "subProcess"; private static final String SUPER_PROCESS = "superProcess"; @Autowired private ProcessRuntime processRuntime; @Autowired private ProcessAdminRuntime processAdminRuntime; @Autowired private SecurityUtil securityUtil; @Autowired private RepositoryService repositoryService; @Autowired private APIProcessDefinitionConverter processDefinitionConverter; @Autowired private RuntimeService runtimeService; @Autowired private ProcessSecurityPoliciesManager securityPoliciesManager; @Autowired private APIProcessInstanceConverter processInstanceConverter; @Autowired private APIVariableInstanceConverter variableInstanceConverter; @Autowired private ProcessRuntimeConfiguration configuration; @Autowired private ApplicationEventPublisher applicationEventPublisher; private ApplicationEventPublisher eventPublisher; private ProcessRuntime processRuntimeMock; private ProcessAdminRuntime processAdminRuntimeMock; @Autowired private ProcessCleanUpUtil processCleanUpUtil; @After public void cleanUp(){ processCleanUpUtil.cleanUpWithAdmin(); } @Before public void init() { eventPublisher = spy(applicationEventPublisher); processRuntimeMock = spy(new ProcessRuntimeImpl(repositoryService, processDefinitionConverter, runtimeService, securityPoliciesManager, processInstanceConverter, variableInstanceConverter, configuration, eventPublisher)); processAdminRuntimeMock = spy(new ProcessAdminRuntimeImpl(repositoryService, processDefinitionConverter, runtimeService, processInstanceConverter, eventPublisher)); //Reset test variables RuntimeTestConfiguration.processImageConnectorExecuted = false; RuntimeTestConfiguration.tagImageConnectorExecuted = false; RuntimeTestConfiguration.discardImageConnectorExecuted = false; } @Test public void shouldGetConfiguration() { securityUtil.logInAs("salaboy"); //when ProcessRuntimeConfiguration configuration = processRuntime.configuration(); //then assertThat(configuration).isNotNull(); } @Test public void shouldGetAvailableProcessDefinitionForTheGivenUser() { securityUtil.logInAs("salaboy"); //when Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 50)); //then assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()) .extracting(ProcessDefinition::getKey) .contains(CATEGORIZE_PROCESS, CATEGORIZE_HUMAN_PROCESS, ONE_STEP_PROCESS); } @Test public void createProcessInstanceAndValidateHappyPath() { securityUtil.logInAs("salaboy"); //when ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", true) .build()); assertThat(RuntimeTestConfiguration.completedProcesses).contains(categorizeProcess.getId()); //then assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.COMPLETED); assertThat(RuntimeTestConfiguration.processImageConnectorExecuted).isEqualTo(true); assertThat(RuntimeTestConfiguration.tagImageConnectorExecuted).isEqualTo(true); assertThat(RuntimeTestConfiguration.discardImageConnectorExecuted).isEqualTo(false); } @Test public void createProcessInstanceAndValidateDiscardPath() { securityUtil.logInAs("salaboy"); //when ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", false) .build()); assertThat(RuntimeTestConfiguration.completedProcesses).contains(categorizeProcess.getId()); //then assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.COMPLETED); assertThat(RuntimeTestConfiguration.processImageConnectorExecuted).isEqualTo(true); assertThat(RuntimeTestConfiguration.tagImageConnectorExecuted).isEqualTo(false); assertThat(RuntimeTestConfiguration.discardImageConnectorExecuted).isEqualTo(true); } @Test public void shouldGetProcessDefinitionFromDefinitionKey() { securityUtil.logInAs("salaboy"); //when ProcessDefinition categorizeHumanProcess = processRuntime.processDefinition(CATEGORIZE_HUMAN_PROCESS); //then assertThat(categorizeHumanProcess).isNotNull(); assertThat(categorizeHumanProcess.getName()).isEqualTo(CATEGORIZE_HUMAN_PROCESS); assertThat(categorizeHumanProcess.getId()).contains(CATEGORIZE_HUMAN_PROCESS); } @Test public void getProcessInstances() { securityUtil.logInAs("salaboy"); //when Page<ProcessInstance> processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); //then assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); //given // start a process with a business key to check filters processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withVariable("name","garth") .withVariable("age",45) .withBusinessKey("my business key") .build()); //when processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); // check for other key processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances().withBusinessKey("other key") .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances().withBusinessKey("my business key") .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); ProcessInstance processInstance = processInstancePage.getContent().get(0); ProcessInstance suspendedProcessInstance = processRuntime.suspend(ProcessPayloadBuilder.suspend(processInstance)); assertThat(suspendedProcessInstance).isNotNull(); assertThat(suspendedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.SUSPENDED); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processRuntime.resume(ProcessPayloadBuilder.resume(processInstance)); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); ProcessInstance getSingleProcessInstance = processRuntime.processInstance(processInstance.getId()); assertThat(getSingleProcessInstance).isNotNull(); assertThat(getSingleProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); // I need to clean up the Process Instances that I started because @WithMockUser cannot be used in @Before method ProcessInstance deletedProcessInstance = processRuntime.delete(ProcessPayloadBuilder.delete(getSingleProcessInstance)); assertThat(deletedProcessInstance).isNotNull(); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); } @Test public void deleteProcessInstance() { securityUtil.logInAs("salaboy"); ProcessRuntimeConfiguration configuration = processRuntime.configuration(); assertThat(configuration).isNotNull(); Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 50)); assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()).extracting((ProcessDefinition pd) -> pd.getKey()) .contains(CATEGORIZE_HUMAN_PROCESS); // start a process with a business key to check filters ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withVariable("name","garth") .withVariable("age",45) .withBusinessKey("my business key") .build()); assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); Page<ProcessInstance> processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); ProcessInstance deletedProcessInstance = processRuntime.delete(ProcessPayloadBuilder.delete(categorizeProcess)); assertThat(deletedProcessInstance).isNotNull(); assertThat(deletedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.DELETED); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); } @Test() public void adminFailTest() { securityUtil.logInAs("salaboy"); //when Throwable throwable = catchThrowable(() -> processAdminRuntime.processInstance("fakeId")); //then assertThat(throwable) .isInstanceOf(AccessDeniedException.class); } @Test() public void userFailTest() { securityUtil.logInAs("admin"); //when Throwable throwable = catchThrowable(() -> processRuntime.processDefinitions(Pageable.of(0, 50))); //then assertThat(throwable) .isInstanceOf(AccessDeniedException.class); } @Test public void updateProcessInstance() { securityUtil.logInAs("salaboy"); ProcessRuntimeConfiguration configuration = processRuntime.configuration(); assertThat(configuration).isNotNull(); Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 50)); assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()).extracting((ProcessDefinition pd) -> pd.getKey()) .contains(CATEGORIZE_HUMAN_PROCESS); // start a process with a business key to check filters ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withBusinessKey("my business key") .withProcessInstanceName("my process name") .build()); assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); assertThat(categorizeProcess.getName()).isEqualTo("my process name"); //assertThat(categorizeProcess.getDescription()).isNull(); // //To do: currently Description is not possible to update // // update a process Page<ProcessInstance> processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); ProcessInstance processInstance = processInstancePage.getContent().get(0); UpdateProcessPayload updateProcessPayload = ProcessPayloadBuilder.update() .withProcessInstanceId(processInstance.getId()) .withBusinessKey(processInstance.getBusinessKey() + " UPDATED") .withProcessInstanceName(processInstance.getName() + " UPDATED") .build(); ProcessInstance updatedProcessInstance = processRuntime.update(updateProcessPayload); assertThat(updatedProcessInstance).isNotNull(); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstance = processInstancePage.getContent().get(0); assertThat(processInstance.getName()).isEqualTo("my process name UPDATED"); assertThat(processInstance.getBusinessKey()).isEqualTo("my business key UPDATED"); // delete a process to avoid possible problems with other tests ProcessInstance deletedProcessInstance = processRuntime.delete(ProcessPayloadBuilder.delete(categorizeProcess)); assertThat(deletedProcessInstance).isNotNull(); assertThat(deletedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.DELETED); } @Test public void updateProcessInstanceAdmin() { securityUtil.logInAs("admin"); Page<ProcessDefinition> processDefinitionPage = processAdminRuntime.processDefinitions(Pageable.of(0, 50)); assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()).extracting((ProcessDefinition pd) -> pd.getKey()) .contains(CATEGORIZE_HUMAN_PROCESS); // start a process with a business key to check filters ProcessInstance categorizeProcess = processAdminRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withBusinessKey("my business key") .withProcessInstanceName("my process name") .build()); assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); assertThat(categorizeProcess.getName()).isEqualTo("my process name"); // update a process Page<ProcessInstance> processInstancePage = processAdminRuntime.processInstances(Pageable.of(0, 50)); ProcessInstance processInstance = processInstancePage.getContent().get(0); UpdateProcessPayload updateProcessPayload = ProcessPayloadBuilder.update() .withProcessInstanceId(processInstance.getId()) .withBusinessKey(processInstance.getBusinessKey() + " UPDATED") .withProcessInstanceName(processInstance.getName() + " UPDATED") .build(); ProcessInstance updatedProcessInstance = processAdminRuntime.update(updateProcessPayload); assertThat(updatedProcessInstance).isNotNull(); processInstancePage = processAdminRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstance = processInstancePage.getContent().get(0); assertThat(processInstance.getName()).isEqualTo("my process name UPDATED"); assertThat(processInstance.getBusinessKey()).isEqualTo("my business key UPDATED"); // delete a process to avoid possible problems with other tests ProcessInstance deletedProcessInstance = processAdminRuntime.delete(ProcessPayloadBuilder.delete(categorizeProcess)); assertThat(deletedProcessInstance).isNotNull(); assertThat(deletedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.DELETED); } @Test public void getSubprocesses() { securityUtil.logInAs("salaboy"); Page<ProcessInstance> processInstancePage; ProcessInstance parentProcess,subProcess; //given // start a process with a business key to check filters parentProcess=processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(SUPER_PROCESS) .withBusinessKey("my superprocess key") .build()); //when processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .build()); //Check that we have parent process and subprocess assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(2); assertThat( processInstancePage.getContent().get(0).getProcessDefinitionKey()).isEqualTo(SUPER_PROCESS); assertThat( processInstancePage.getContent().get(1).getProcessDefinitionKey()).isEqualTo(SUB_PROCESS); //Check that parentProcess has 1 subprocess processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .subprocesses(parentProcess.getId())); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); subProcess=processInstancePage.getContent().get(0); assertThat(subProcess.getProcessDefinitionKey()).isEqualTo(SUB_PROCESS); assertThat(subProcess.getParentId()).isEqualTo(parentProcess.getId()); assertThat(subProcess.getProcessDefinitionVersion()).isEqualTo(1); processRuntime.delete(ProcessPayloadBuilder.delete(subProcess)); processRuntime.delete(ProcessPayloadBuilder.delete(parentProcess)); } @Test public void signal() { securityUtil.logInAs("salaboy"); // when SignalPayload signalPayload = new SignalPayload("The Signal", null); processRuntimeMock.signal(signalPayload); Page<ProcessInstance> processInstancePage = processRuntimeMock.processInstances(Pageable.of(0, 50)); // then assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); assertThat(processInstancePage.getContent().get(0).getProcessDefinitionKey()).isEqualTo("processWithSignalStart1"); verify(eventPublisher).publishEvent(signalPayload); processRuntimeMock.delete(ProcessPayloadBuilder.delete(processInstancePage.getContent().get(0).getId())); } @Test public void signalAdmin() { securityUtil.logInAs("admin"); // when SignalPayload signalPayload = new SignalPayload("The Signal", null); processAdminRuntimeMock.signal(signalPayload); verify(eventPublisher).publishEvent(signalPayload); Page<ProcessInstance> processInstancePage = processAdminRuntimeMock.processInstances(Pageable.of(0, 50)); // then assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); assertThat(processInstancePage.getContent().get(0).getProcessDefinitionKey()).isEqualTo("processWithSignalStart1"); processAdminRuntimeMock.delete(ProcessPayloadBuilder.delete(processInstancePage.getContent().get(0).getId())); } }
activiti-spring-boot-starter/src/test/java/org/activiti/spring/boot/process/ProcessRuntimeTest.java
package org.activiti.spring.boot.process; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.spy; import static org.assertj.core.api.Assertions.catchThrowable; import org.activiti.api.process.model.ProcessDefinition; import org.activiti.api.process.model.ProcessInstance; import org.activiti.api.process.model.builders.ProcessPayloadBuilder; import org.activiti.api.process.model.payloads.SignalPayload; import org.activiti.api.process.model.payloads.UpdateProcessPayload; import org.activiti.api.process.runtime.ProcessAdminRuntime; import org.activiti.api.process.runtime.ProcessRuntime; import org.activiti.api.process.runtime.conf.ProcessRuntimeConfiguration; import org.activiti.api.runtime.shared.query.Page; import org.activiti.api.runtime.shared.query.Pageable; import org.activiti.core.common.spring.security.policies.ProcessSecurityPoliciesManager; import org.activiti.engine.RepositoryService; import org.activiti.engine.RuntimeService; import org.activiti.runtime.api.impl.ProcessAdminRuntimeImpl; import org.activiti.runtime.api.impl.ProcessRuntimeImpl; import org.activiti.runtime.api.model.impl.APIProcessDefinitionConverter; import org.activiti.runtime.api.model.impl.APIProcessInstanceConverter; import org.activiti.runtime.api.model.impl.APIVariableInstanceConverter; import org.activiti.spring.boot.RuntimeTestConfiguration; import org.activiti.spring.boot.security.util.SecurityUtil; import org.activiti.spring.boot.test.util.ProcessCleanUpUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.access.AccessDeniedException; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class ProcessRuntimeTest { private static final String CATEGORIZE_PROCESS = "categorizeProcess"; private static final String CATEGORIZE_HUMAN_PROCESS = "categorizeHumanProcess"; private static final String ONE_STEP_PROCESS = "OneStepProcess"; private static final String SUB_PROCESS = "subProcess"; private static final String SUPER_PROCESS = "superProcess"; @Autowired private ProcessRuntime processRuntime; @Autowired private ProcessAdminRuntime processAdminRuntime; @Autowired private SecurityUtil securityUtil; @Autowired private RepositoryService repositoryService; @Autowired private APIProcessDefinitionConverter processDefinitionConverter; @Autowired private RuntimeService runtimeService; @Autowired private ProcessSecurityPoliciesManager securityPoliciesManager; @Autowired private APIProcessInstanceConverter processInstanceConverter; @Autowired private APIVariableInstanceConverter variableInstanceConverter; @Autowired private ProcessRuntimeConfiguration configuration; @Mock private ApplicationEventPublisher eventPublisher; private ProcessRuntime processRuntimeMock; private ProcessAdminRuntime processAdminRuntimeMock; @Autowired private ProcessCleanUpUtil processCleanUpUtil; @After public void cleanUp(){ processCleanUpUtil.cleanUpWithAdmin(); } @Before public void init() { processRuntimeMock = spy(new ProcessRuntimeImpl(repositoryService, processDefinitionConverter, runtimeService, securityPoliciesManager, processInstanceConverter, variableInstanceConverter, configuration, eventPublisher)); processAdminRuntimeMock = spy(new ProcessAdminRuntimeImpl(repositoryService, processDefinitionConverter, runtimeService, processInstanceConverter, eventPublisher)); //Reset test variables RuntimeTestConfiguration.processImageConnectorExecuted = false; RuntimeTestConfiguration.tagImageConnectorExecuted = false; RuntimeTestConfiguration.discardImageConnectorExecuted = false; } @Test public void shouldGetConfiguration() { securityUtil.logInAs("salaboy"); //when ProcessRuntimeConfiguration configuration = processRuntime.configuration(); //then assertThat(configuration).isNotNull(); } @Test public void shouldGetAvailableProcessDefinitionForTheGivenUser() { securityUtil.logInAs("salaboy"); //when Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 50)); //then assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()) .extracting(ProcessDefinition::getKey) .contains(CATEGORIZE_PROCESS, CATEGORIZE_HUMAN_PROCESS, ONE_STEP_PROCESS); } @Test public void createProcessInstanceAndValidateHappyPath() { securityUtil.logInAs("salaboy"); //when ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", true) .build()); assertThat(RuntimeTestConfiguration.completedProcesses).contains(categorizeProcess.getId()); //then assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.COMPLETED); assertThat(RuntimeTestConfiguration.processImageConnectorExecuted).isEqualTo(true); assertThat(RuntimeTestConfiguration.tagImageConnectorExecuted).isEqualTo(true); assertThat(RuntimeTestConfiguration.discardImageConnectorExecuted).isEqualTo(false); } @Test public void createProcessInstanceAndValidateDiscardPath() { securityUtil.logInAs("salaboy"); //when ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_PROCESS) .withVariable("expectedKey", false) .build()); assertThat(RuntimeTestConfiguration.completedProcesses).contains(categorizeProcess.getId()); //then assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.COMPLETED); assertThat(RuntimeTestConfiguration.processImageConnectorExecuted).isEqualTo(true); assertThat(RuntimeTestConfiguration.tagImageConnectorExecuted).isEqualTo(false); assertThat(RuntimeTestConfiguration.discardImageConnectorExecuted).isEqualTo(true); } @Test public void shouldGetProcessDefinitionFromDefinitionKey() { securityUtil.logInAs("salaboy"); //when ProcessDefinition categorizeHumanProcess = processRuntime.processDefinition(CATEGORIZE_HUMAN_PROCESS); //then assertThat(categorizeHumanProcess).isNotNull(); assertThat(categorizeHumanProcess.getName()).isEqualTo(CATEGORIZE_HUMAN_PROCESS); assertThat(categorizeHumanProcess.getId()).contains(CATEGORIZE_HUMAN_PROCESS); } @Test public void getProcessInstances() { securityUtil.logInAs("salaboy"); //when Page<ProcessInstance> processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); //then assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); //given // start a process with a business key to check filters processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withVariable("name","garth") .withVariable("age",45) .withBusinessKey("my business key") .build()); //when processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); // check for other key processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances().withBusinessKey("other key") .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances().withBusinessKey("my business key") .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); ProcessInstance processInstance = processInstancePage.getContent().get(0); ProcessInstance suspendedProcessInstance = processRuntime.suspend(ProcessPayloadBuilder.suspend(processInstance)); assertThat(suspendedProcessInstance).isNotNull(); assertThat(suspendedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.SUSPENDED); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processRuntime.resume(ProcessPayloadBuilder.resume(processInstance)); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .suspended() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .active() .build()); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); ProcessInstance getSingleProcessInstance = processRuntime.processInstance(processInstance.getId()); assertThat(getSingleProcessInstance).isNotNull(); assertThat(getSingleProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); // I need to clean up the Process Instances that I started because @WithMockUser cannot be used in @Before method ProcessInstance deletedProcessInstance = processRuntime.delete(ProcessPayloadBuilder.delete(getSingleProcessInstance)); assertThat(deletedProcessInstance).isNotNull(); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); } @Test public void deleteProcessInstance() { securityUtil.logInAs("salaboy"); ProcessRuntimeConfiguration configuration = processRuntime.configuration(); assertThat(configuration).isNotNull(); Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 50)); assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()).extracting((ProcessDefinition pd) -> pd.getKey()) .contains(CATEGORIZE_HUMAN_PROCESS); // start a process with a business key to check filters ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withVariable("name","garth") .withVariable("age",45) .withBusinessKey("my business key") .build()); assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); Page<ProcessInstance> processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); ProcessInstance deletedProcessInstance = processRuntime.delete(ProcessPayloadBuilder.delete(categorizeProcess)); assertThat(deletedProcessInstance).isNotNull(); assertThat(deletedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.DELETED); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(0); } @Test() public void adminFailTest() { securityUtil.logInAs("salaboy"); //when Throwable throwable = catchThrowable(() -> processAdminRuntime.processInstance("fakeId")); //then assertThat(throwable) .isInstanceOf(AccessDeniedException.class); } @Test() public void userFailTest() { securityUtil.logInAs("admin"); //when Throwable throwable = catchThrowable(() -> processRuntime.processDefinitions(Pageable.of(0, 50))); //then assertThat(throwable) .isInstanceOf(AccessDeniedException.class); } @Test public void updateProcessInstance() { securityUtil.logInAs("salaboy"); ProcessRuntimeConfiguration configuration = processRuntime.configuration(); assertThat(configuration).isNotNull(); Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 50)); assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()).extracting((ProcessDefinition pd) -> pd.getKey()) .contains(CATEGORIZE_HUMAN_PROCESS); // start a process with a business key to check filters ProcessInstance categorizeProcess = processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withBusinessKey("my business key") .withProcessInstanceName("my process name") .build()); assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); assertThat(categorizeProcess.getName()).isEqualTo("my process name"); //assertThat(categorizeProcess.getDescription()).isNull(); // //To do: currently Description is not possible to update // // update a process Page<ProcessInstance> processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); ProcessInstance processInstance = processInstancePage.getContent().get(0); UpdateProcessPayload updateProcessPayload = ProcessPayloadBuilder.update() .withProcessInstanceId(processInstance.getId()) .withBusinessKey(processInstance.getBusinessKey() + " UPDATED") .withProcessInstanceName(processInstance.getName() + " UPDATED") .build(); ProcessInstance updatedProcessInstance = processRuntime.update(updateProcessPayload); assertThat(updatedProcessInstance).isNotNull(); processInstancePage = processRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstance = processInstancePage.getContent().get(0); assertThat(processInstance.getName()).isEqualTo("my process name UPDATED"); assertThat(processInstance.getBusinessKey()).isEqualTo("my business key UPDATED"); // delete a process to avoid possible problems with other tests ProcessInstance deletedProcessInstance = processRuntime.delete(ProcessPayloadBuilder.delete(categorizeProcess)); assertThat(deletedProcessInstance).isNotNull(); assertThat(deletedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.DELETED); } @Test public void updateProcessInstanceAdmin() { securityUtil.logInAs("admin"); Page<ProcessDefinition> processDefinitionPage = processAdminRuntime.processDefinitions(Pageable.of(0, 50)); assertThat(processDefinitionPage.getContent()).isNotNull(); assertThat(processDefinitionPage.getContent()).extracting((ProcessDefinition pd) -> pd.getKey()) .contains(CATEGORIZE_HUMAN_PROCESS); // start a process with a business key to check filters ProcessInstance categorizeProcess = processAdminRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(CATEGORIZE_HUMAN_PROCESS) .withVariable("expectedKey", true) .withBusinessKey("my business key") .withProcessInstanceName("my process name") .build()); assertThat(categorizeProcess).isNotNull(); assertThat(categorizeProcess.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.RUNNING); assertThat(categorizeProcess.getName()).isEqualTo("my process name"); // update a process Page<ProcessInstance> processInstancePage = processAdminRuntime.processInstances(Pageable.of(0, 50)); ProcessInstance processInstance = processInstancePage.getContent().get(0); UpdateProcessPayload updateProcessPayload = ProcessPayloadBuilder.update() .withProcessInstanceId(processInstance.getId()) .withBusinessKey(processInstance.getBusinessKey() + " UPDATED") .withProcessInstanceName(processInstance.getName() + " UPDATED") .build(); ProcessInstance updatedProcessInstance = processAdminRuntime.update(updateProcessPayload); assertThat(updatedProcessInstance).isNotNull(); processInstancePage = processAdminRuntime.processInstances(Pageable.of(0, 50)); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); processInstance = processInstancePage.getContent().get(0); assertThat(processInstance.getName()).isEqualTo("my process name UPDATED"); assertThat(processInstance.getBusinessKey()).isEqualTo("my business key UPDATED"); // delete a process to avoid possible problems with other tests ProcessInstance deletedProcessInstance = processAdminRuntime.delete(ProcessPayloadBuilder.delete(categorizeProcess)); assertThat(deletedProcessInstance).isNotNull(); assertThat(deletedProcessInstance.getStatus()).isEqualTo(ProcessInstance.ProcessInstanceStatus.DELETED); } @Test public void getSubprocesses() { securityUtil.logInAs("salaboy"); Page<ProcessInstance> processInstancePage; ProcessInstance parentProcess,subProcess; //given // start a process with a business key to check filters parentProcess=processRuntime.start(ProcessPayloadBuilder.start() .withProcessDefinitionKey(SUPER_PROCESS) .withBusinessKey("my superprocess key") .build()); //when processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .processInstances() .build()); //Check that we have parent process and subprocess assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(2); assertThat( processInstancePage.getContent().get(0).getProcessDefinitionKey()).isEqualTo(SUPER_PROCESS); assertThat( processInstancePage.getContent().get(1).getProcessDefinitionKey()).isEqualTo(SUB_PROCESS); //Check that parentProcess has 1 subprocess processInstancePage = processRuntime.processInstances(Pageable.of(0, 50), ProcessPayloadBuilder .subprocesses(parentProcess.getId())); assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); subProcess=processInstancePage.getContent().get(0); assertThat(subProcess.getProcessDefinitionKey()).isEqualTo(SUB_PROCESS); assertThat(subProcess.getParentId()).isEqualTo(parentProcess.getId()); assertThat(subProcess.getProcessDefinitionVersion()).isEqualTo(1); processRuntime.delete(ProcessPayloadBuilder.delete(subProcess)); processRuntime.delete(ProcessPayloadBuilder.delete(parentProcess)); } @Test public void signal() { securityUtil.logInAs("salaboy"); // when SignalPayload signalPayload = new SignalPayload("The Signal", null); processRuntimeMock.signal(signalPayload); Page<ProcessInstance> processInstancePage = processRuntimeMock.processInstances(Pageable.of(0, 50)); // then assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); assertThat(processInstancePage.getContent().get(0).getProcessDefinitionKey()).isEqualTo("processWithSignalStart1"); verify(eventPublisher).publishEvent(signalPayload); processRuntimeMock.delete(ProcessPayloadBuilder.delete(processInstancePage.getContent().get(0).getId())); } @Test public void signalAdmin() { securityUtil.logInAs("admin"); // when SignalPayload signalPayload = new SignalPayload("The Signal", null); processAdminRuntimeMock.signal(signalPayload); verify(eventPublisher).publishEvent(signalPayload); Page<ProcessInstance> processInstancePage = processAdminRuntimeMock.processInstances(Pageable.of(0, 50)); // then assertThat(processInstancePage).isNotNull(); assertThat(processInstancePage.getContent()).hasSize(1); assertThat(processInstancePage.getContent().get(0).getProcessDefinitionKey()).isEqualTo("processWithSignalStart1"); processAdminRuntimeMock.delete(ProcessPayloadBuilder.delete(processInstancePage.getContent().get(0).getId())); } }
fix: use spy on eventPublisher in ProcessRuntimeTest
activiti-spring-boot-starter/src/test/java/org/activiti/spring/boot/process/ProcessRuntimeTest.java
fix: use spy on eventPublisher in ProcessRuntimeTest
<ide><path>ctiviti-spring-boot-starter/src/test/java/org/activiti/spring/boot/process/ProcessRuntimeTest.java <ide> package org.activiti.spring.boot.process; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <add>import static org.assertj.core.api.Assertions.catchThrowable; <add>import static org.mockito.Mockito.spy; <ide> import static org.mockito.Mockito.verify; <del>import static org.mockito.Mockito.spy; <del>import static org.assertj.core.api.Assertions.catchThrowable; <ide> <ide> import org.activiti.api.process.model.ProcessDefinition; <ide> import org.activiti.api.process.model.ProcessInstance; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <del>import org.mockito.Mock; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.boot.test.context.SpringBootTest; <ide> import org.springframework.context.ApplicationEventPublisher; <ide> @Autowired <ide> private ProcessRuntimeConfiguration configuration; <ide> <del> @Mock <add> @Autowired <add> private ApplicationEventPublisher applicationEventPublisher; <add> <ide> private ApplicationEventPublisher eventPublisher; <ide> <ide> private ProcessRuntime processRuntimeMock; <ide> <ide> @Before <ide> public void init() { <add> eventPublisher = spy(applicationEventPublisher); <add> <ide> processRuntimeMock = spy(new ProcessRuntimeImpl(repositoryService, <ide> processDefinitionConverter, <ide> runtimeService,
Java
apache-2.0
0bf906dd65a17a11e12e1aa212abce493c83b668
0
alireza-hosseini/libgdx,czyzby/libgdx,MovingBlocks/libgdx,titovmaxim/libgdx,alireza-hosseini/libgdx,TheAks999/libgdx,noelsison2/libgdx,thepullman/libgdx,basherone/libgdxcn,hyvas/libgdx,jberberick/libgdx,saqsun/libgdx,anserran/libgdx,alex-dorokhov/libgdx,Wisienkas/libgdx,saqsun/libgdx,Heart2009/libgdx,thepullman/libgdx,junkdog/libgdx,libgdx/libgdx,djom20/libgdx,Deftwun/libgdx,Senth/libgdx,Deftwun/libgdx,BlueRiverInteractive/libgdx,JDReutt/libgdx,MathieuDuponchelle/gdx,djom20/libgdx,jasonwee/libgdx,stinsonga/libgdx,antag99/libgdx,ninoalma/libgdx,anserran/libgdx,MathieuDuponchelle/gdx,codepoke/libgdx,FredGithub/libgdx,sjosegarcia/libgdx,EsikAntony/libgdx,UnluckyNinja/libgdx,sinistersnare/libgdx,del-sol/libgdx,curtiszimmerman/libgdx,Dzamir/libgdx,davebaol/libgdx,TheAks999/libgdx,ThiagoGarciaAlves/libgdx,ya7lelkom/libgdx,309746069/libgdx,xranby/libgdx,xpenatan/libgdx-LWJGL3,josephknight/libgdx,alex-dorokhov/libgdx,ninoalma/libgdx,jsjolund/libgdx,thepullman/libgdx,antag99/libgdx,toloudis/libgdx,1yvT0s/libgdx,antag99/libgdx,Zonglin-Li6565/libgdx,djom20/libgdx,bsmr-java/libgdx,MadcowD/libgdx,JDReutt/libgdx,ThiagoGarciaAlves/libgdx,anserran/libgdx,del-sol/libgdx,saqsun/libgdx,Wisienkas/libgdx,stickyd/libgdx,tell10glu/libgdx,Badazdz/libgdx,1yvT0s/libgdx,EsikAntony/libgdx,MetSystem/libgdx,libgdx/libgdx,KrisLee/libgdx,TheAks999/libgdx,toa5/libgdx,ryoenji/libgdx,billgame/libgdx,FyiurAmron/libgdx,haedri/libgdx-1,saltares/libgdx,alex-dorokhov/libgdx,titovmaxim/libgdx,toloudis/libgdx,Zonglin-Li6565/libgdx,Dzamir/libgdx,billgame/libgdx,Zomby2D/libgdx,ttencate/libgdx,revo09/libgdx,Gliby/libgdx,josephknight/libgdx,samskivert/libgdx,realitix/libgdx,firefly2442/libgdx,srwonka/libGdx,codepoke/libgdx,tommyettinger/libgdx,ryoenji/libgdx,xoppa/libgdx,lordjone/libgdx,xpenatan/libgdx-LWJGL3,kzganesan/libgdx,revo09/libgdx,yangweigbh/libgdx,toloudis/libgdx,yangweigbh/libgdx,revo09/libgdx,davebaol/libgdx,tommyettinger/libgdx,stinsonga/libgdx,bgroenks96/libgdx,basherone/libgdxcn,ttencate/libgdx,Dzamir/libgdx,bgroenks96/libgdx,realitix/libgdx,luischavez/libgdx,ztv/libgdx,mumer92/libgdx,Dzamir/libgdx,noelsison2/libgdx,del-sol/libgdx,ryoenji/libgdx,djom20/libgdx,firefly2442/libgdx,saqsun/libgdx,ThiagoGarciaAlves/libgdx,fiesensee/libgdx,katiepino/libgdx,Heart2009/libgdx,nudelchef/libgdx,Heart2009/libgdx,xranby/libgdx,PedroRomanoBarbosa/libgdx,del-sol/libgdx,xoppa/libgdx,Xhanim/libgdx,curtiszimmerman/libgdx,jsjolund/libgdx,copystudy/libgdx,tommyettinger/libgdx,stinsonga/libgdx,azakhary/libgdx,TheAks999/libgdx,antag99/libgdx,Wisienkas/libgdx,codepoke/libgdx,nave966/libgdx,youprofit/libgdx,nave966/libgdx,bsmr-java/libgdx,ya7lelkom/libgdx,gouessej/libgdx,katiepino/libgdx,Dzamir/libgdx,fwolff/libgdx,FyiurAmron/libgdx,toa5/libgdx,ninoalma/libgdx,NathanSweet/libgdx,mumer92/libgdx,lordjone/libgdx,designcrumble/libgdx,antag99/libgdx,samskivert/libgdx,shiweihappy/libgdx,lordjone/libgdx,bsmr-java/libgdx,kzganesan/libgdx,gf11speed/libgdx,nudelchef/libgdx,petugez/libgdx,NathanSweet/libgdx,1yvT0s/libgdx,nave966/libgdx,anserran/libgdx,samskivert/libgdx,gdos/libgdx,collinsmith/libgdx,fwolff/libgdx,stickyd/libgdx,ThiagoGarciaAlves/libgdx,MovingBlocks/libgdx,czyzby/libgdx,ztv/libgdx,PedroRomanoBarbosa/libgdx,kotcrab/libgdx,ttencate/libgdx,FyiurAmron/libgdx,gouessej/libgdx,stickyd/libgdx,tommycli/libgdx,bladecoder/libgdx,firefly2442/libgdx,ttencate/libgdx,nudelchef/libgdx,Thotep/libgdx,nudelchef/libgdx,petugez/libgdx,fwolff/libgdx,billgame/libgdx,MathieuDuponchelle/gdx,ztv/libgdx,codepoke/libgdx,fiesensee/libgdx,ricardorigodon/libgdx,azakhary/libgdx,Senth/libgdx,alireza-hosseini/libgdx,MetSystem/libgdx,saqsun/libgdx,tommyettinger/libgdx,Badazdz/libgdx,MikkelTAndersen/libgdx,yangweigbh/libgdx,sarkanyi/libgdx,kotcrab/libgdx,GreenLightning/libgdx,lordjone/libgdx,katiepino/libgdx,czyzby/libgdx,mumer92/libgdx,bgroenks96/libgdx,MetSystem/libgdx,Deftwun/libgdx,flaiker/libgdx,copystudy/libgdx,FredGithub/libgdx,bgroenks96/libgdx,srwonka/libGdx,xranby/libgdx,davebaol/libgdx,firefly2442/libgdx,Gliby/libgdx,copystudy/libgdx,samskivert/libgdx,kagehak/libgdx,petugez/libgdx,ninoalma/libgdx,JFixby/libgdx,ya7lelkom/libgdx,nrallakis/libgdx,bsmr-java/libgdx,curtiszimmerman/libgdx,js78/libgdx,PedroRomanoBarbosa/libgdx,bladecoder/libgdx,nrallakis/libgdx,mumer92/libgdx,junkdog/libgdx,Senth/libgdx,nudelchef/libgdx,Badazdz/libgdx,sjosegarcia/libgdx,collinsmith/libgdx,anserran/libgdx,mumer92/libgdx,tell10glu/libgdx,realitix/libgdx,josephknight/libgdx,TheAks999/libgdx,sarkanyi/libgdx,thepullman/libgdx,Zonglin-Li6565/libgdx,gf11speed/libgdx,MetSystem/libgdx,youprofit/libgdx,zhimaijoy/libgdx,nelsonsilva/libgdx,xpenatan/libgdx-LWJGL3,MadcowD/libgdx,azakhary/libgdx,youprofit/libgdx,basherone/libgdxcn,toa5/libgdx,309746069/libgdx,jsjolund/libgdx,ricardorigodon/libgdx,stickyd/libgdx,UnluckyNinja/libgdx,bladecoder/libgdx,copystudy/libgdx,davebaol/libgdx,bladecoder/libgdx,ztv/libgdx,bgroenks96/libgdx,Thotep/libgdx,fwolff/libgdx,MikkelTAndersen/libgdx,nave966/libgdx,Thotep/libgdx,MovingBlocks/libgdx,yangweigbh/libgdx,cypherdare/libgdx,Dzamir/libgdx,libgdx/libgdx,gdos/libgdx,jasonwee/libgdx,alireza-hosseini/libgdx,Arcnor/libgdx,xranby/libgdx,js78/libgdx,FyiurAmron/libgdx,BlueRiverInteractive/libgdx,designcrumble/libgdx,Gliby/libgdx,stickyd/libgdx,titovmaxim/libgdx,SidneyXu/libgdx,JDReutt/libgdx,saltares/libgdx,mumer92/libgdx,KrisLee/libgdx,Zomby2D/libgdx,Gliby/libgdx,djom20/libgdx,Badazdz/libgdx,ya7lelkom/libgdx,billgame/libgdx,tommyettinger/libgdx,MetSystem/libgdx,haedri/libgdx-1,Badazdz/libgdx,collinsmith/libgdx,sinistersnare/libgdx,petugez/libgdx,sjosegarcia/libgdx,309746069/libgdx,firefly2442/libgdx,Heart2009/libgdx,shiweihappy/libgdx,petugez/libgdx,czyzby/libgdx,alireza-hosseini/libgdx,anserran/libgdx,Xhanim/libgdx,stickyd/libgdx,designcrumble/libgdx,designcrumble/libgdx,designcrumble/libgdx,hyvas/libgdx,ricardorigodon/libgdx,MikkelTAndersen/libgdx,youprofit/libgdx,MovingBlocks/libgdx,shiweihappy/libgdx,snovak/libgdx,lordjone/libgdx,NathanSweet/libgdx,SidneyXu/libgdx,hyvas/libgdx,309746069/libgdx,Zomby2D/libgdx,mumer92/libgdx,SidneyXu/libgdx,fiesensee/libgdx,youprofit/libgdx,sarkanyi/libgdx,saltares/libgdx,thepullman/libgdx,realitix/libgdx,JDReutt/libgdx,NathanSweet/libgdx,shiweihappy/libgdx,alex-dorokhov/libgdx,haedri/libgdx-1,yangweigbh/libgdx,xoppa/libgdx,tell10glu/libgdx,MathieuDuponchelle/gdx,gf11speed/libgdx,katiepino/libgdx,noelsison2/libgdx,SidneyXu/libgdx,curtiszimmerman/libgdx,kotcrab/libgdx,xranby/libgdx,JFixby/libgdx,ya7lelkom/libgdx,xpenatan/libgdx-LWJGL3,alex-dorokhov/libgdx,snovak/libgdx,Zomby2D/libgdx,flaiker/libgdx,tell10glu/libgdx,sjosegarcia/libgdx,saltares/libgdx,KrisLee/libgdx,srwonka/libGdx,js78/libgdx,zhimaijoy/libgdx,nelsonsilva/libgdx,KrisLee/libgdx,snovak/libgdx,srwonka/libGdx,toloudis/libgdx,bladecoder/libgdx,PedroRomanoBarbosa/libgdx,Heart2009/libgdx,ricardorigodon/libgdx,junkdog/libgdx,junkdog/libgdx,srwonka/libGdx,gdos/libgdx,Xhanim/libgdx,Arcnor/libgdx,gouessej/libgdx,andyvand/libgdx,nooone/libgdx,zommuter/libgdx,andyvand/libgdx,Wisienkas/libgdx,Xhanim/libgdx,basherone/libgdxcn,kagehak/libgdx,tommycli/libgdx,MadcowD/libgdx,zommuter/libgdx,jsjolund/libgdx,sinistersnare/libgdx,snovak/libgdx,antag99/libgdx,djom20/libgdx,kotcrab/libgdx,Heart2009/libgdx,bsmr-java/libgdx,ryoenji/libgdx,MikkelTAndersen/libgdx,jberberick/libgdx,EsikAntony/libgdx,youprofit/libgdx,junkdog/libgdx,hyvas/libgdx,Badazdz/libgdx,srwonka/libGdx,xoppa/libgdx,UnluckyNinja/libgdx,nave966/libgdx,GreenLightning/libgdx,jberberick/libgdx,ttencate/libgdx,shiweihappy/libgdx,ztv/libgdx,titovmaxim/libgdx,shiweihappy/libgdx,flaiker/libgdx,fiesensee/libgdx,EsikAntony/libgdx,gouessej/libgdx,jasonwee/libgdx,yangweigbh/libgdx,andyvand/libgdx,1yvT0s/libgdx,toa5/libgdx,tommycli/libgdx,ztv/libgdx,JFixby/libgdx,js78/libgdx,kotcrab/libgdx,309746069/libgdx,zhimaijoy/libgdx,bgroenks96/libgdx,azakhary/libgdx,curtiszimmerman/libgdx,toa5/libgdx,xpenatan/libgdx-LWJGL3,Zomby2D/libgdx,gdos/libgdx,xpenatan/libgdx-LWJGL3,codepoke/libgdx,designcrumble/libgdx,1yvT0s/libgdx,MovingBlocks/libgdx,nelsonsilva/libgdx,ryoenji/libgdx,BlueRiverInteractive/libgdx,youprofit/libgdx,luischavez/libgdx,luischavez/libgdx,haedri/libgdx-1,noelsison2/libgdx,Heart2009/libgdx,sarkanyi/libgdx,kzganesan/libgdx,katiepino/libgdx,jsjolund/libgdx,PedroRomanoBarbosa/libgdx,js78/libgdx,zommuter/libgdx,azakhary/libgdx,Thotep/libgdx,zhimaijoy/libgdx,haedri/libgdx-1,GreenLightning/libgdx,nave966/libgdx,junkdog/libgdx,jasonwee/libgdx,samskivert/libgdx,cypherdare/libgdx,josephknight/libgdx,nave966/libgdx,junkdog/libgdx,SidneyXu/libgdx,josephknight/libgdx,anserran/libgdx,nooone/libgdx,1yvT0s/libgdx,Senth/libgdx,nrallakis/libgdx,saqsun/libgdx,nelsonsilva/libgdx,titovmaxim/libgdx,Wisienkas/libgdx,zhimaijoy/libgdx,BlueRiverInteractive/libgdx,nrallakis/libgdx,TheAks999/libgdx,toa5/libgdx,KrisLee/libgdx,nrallakis/libgdx,BlueRiverInteractive/libgdx,haedri/libgdx-1,anserran/libgdx,MadcowD/libgdx,JFixby/libgdx,Arcnor/libgdx,ya7lelkom/libgdx,Dzamir/libgdx,MikkelTAndersen/libgdx,junkdog/libgdx,nudelchef/libgdx,MikkelTAndersen/libgdx,titovmaxim/libgdx,samskivert/libgdx,collinsmith/libgdx,sjosegarcia/libgdx,Zonglin-Li6565/libgdx,snovak/libgdx,JDReutt/libgdx,MovingBlocks/libgdx,firefly2442/libgdx,realitix/libgdx,ttencate/libgdx,UnluckyNinja/libgdx,copystudy/libgdx,GreenLightning/libgdx,realitix/libgdx,GreenLightning/libgdx,tommycli/libgdx,andyvand/libgdx,hyvas/libgdx,309746069/libgdx,Thotep/libgdx,UnluckyNinja/libgdx,fwolff/libgdx,gdos/libgdx,luischavez/libgdx,kzganesan/libgdx,BlueRiverInteractive/libgdx,xpenatan/libgdx-LWJGL3,bsmr-java/libgdx,TheAks999/libgdx,collinsmith/libgdx,bsmr-java/libgdx,sinistersnare/libgdx,kagehak/libgdx,JDReutt/libgdx,haedri/libgdx-1,del-sol/libgdx,zommuter/libgdx,titovmaxim/libgdx,ThiagoGarciaAlves/libgdx,EsikAntony/libgdx,JDReutt/libgdx,alireza-hosseini/libgdx,collinsmith/libgdx,ninoalma/libgdx,revo09/libgdx,UnluckyNinja/libgdx,Thotep/libgdx,Heart2009/libgdx,TheAks999/libgdx,youprofit/libgdx,kzganesan/libgdx,gf11speed/libgdx,luischavez/libgdx,bgroenks96/libgdx,stinsonga/libgdx,titovmaxim/libgdx,UnluckyNinja/libgdx,Gliby/libgdx,js78/libgdx,MikkelTAndersen/libgdx,shiweihappy/libgdx,fwolff/libgdx,ninoalma/libgdx,jsjolund/libgdx,nudelchef/libgdx,MetSystem/libgdx,tell10glu/libgdx,fiesensee/libgdx,mumer92/libgdx,Zonglin-Li6565/libgdx,nrallakis/libgdx,MadcowD/libgdx,revo09/libgdx,ThiagoGarciaAlves/libgdx,PedroRomanoBarbosa/libgdx,nooone/libgdx,ricardorigodon/libgdx,zommuter/libgdx,copystudy/libgdx,luischavez/libgdx,zhimaijoy/libgdx,yangweigbh/libgdx,andyvand/libgdx,kagehak/libgdx,gouessej/libgdx,copystudy/libgdx,petugez/libgdx,309746069/libgdx,xoppa/libgdx,gf11speed/libgdx,realitix/libgdx,sjosegarcia/libgdx,alireza-hosseini/libgdx,SidneyXu/libgdx,srwonka/libGdx,FyiurAmron/libgdx,saltares/libgdx,ztv/libgdx,NathanSweet/libgdx,Wisienkas/libgdx,zommuter/libgdx,ttencate/libgdx,alex-dorokhov/libgdx,js78/libgdx,kotcrab/libgdx,davebaol/libgdx,cypherdare/libgdx,MovingBlocks/libgdx,azakhary/libgdx,MetSystem/libgdx,MathieuDuponchelle/gdx,jasonwee/libgdx,kagehak/libgdx,gf11speed/libgdx,EsikAntony/libgdx,jsjolund/libgdx,sinistersnare/libgdx,designcrumble/libgdx,tommycli/libgdx,jberberick/libgdx,BlueRiverInteractive/libgdx,MathieuDuponchelle/gdx,djom20/libgdx,xoppa/libgdx,Arcnor/libgdx,jberberick/libgdx,zhimaijoy/libgdx,sjosegarcia/libgdx,gf11speed/libgdx,gdos/libgdx,BlueRiverInteractive/libgdx,revo09/libgdx,petugez/libgdx,FyiurAmron/libgdx,jsjolund/libgdx,KrisLee/libgdx,cypherdare/libgdx,josephknight/libgdx,toa5/libgdx,MadcowD/libgdx,1yvT0s/libgdx,gouessej/libgdx,jasonwee/libgdx,Xhanim/libgdx,tell10glu/libgdx,flaiker/libgdx,MikkelTAndersen/libgdx,1yvT0s/libgdx,Arcnor/libgdx,FredGithub/libgdx,czyzby/libgdx,kagehak/libgdx,MadcowD/libgdx,tommycli/libgdx,nrallakis/libgdx,alex-dorokhov/libgdx,FredGithub/libgdx,lordjone/libgdx,gdos/libgdx,libgdx/libgdx,billgame/libgdx,ricardorigodon/libgdx,toloudis/libgdx,saltares/libgdx,fwolff/libgdx,toloudis/libgdx,collinsmith/libgdx,fwolff/libgdx,designcrumble/libgdx,309746069/libgdx,JFixby/libgdx,FredGithub/libgdx,bgroenks96/libgdx,fiesensee/libgdx,curtiszimmerman/libgdx,curtiszimmerman/libgdx,jasonwee/libgdx,del-sol/libgdx,gf11speed/libgdx,EsikAntony/libgdx,Xhanim/libgdx,copystudy/libgdx,revo09/libgdx,FyiurAmron/libgdx,billgame/libgdx,saqsun/libgdx,thepullman/libgdx,Arcnor/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,thepullman/libgdx,jberberick/libgdx,EsikAntony/libgdx,alex-dorokhov/libgdx,nooone/libgdx,ya7lelkom/libgdx,Thotep/libgdx,antag99/libgdx,xoppa/libgdx,nave966/libgdx,FredGithub/libgdx,ryoenji/libgdx,samskivert/libgdx,FredGithub/libgdx,Wisienkas/libgdx,hyvas/libgdx,flaiker/libgdx,snovak/libgdx,tommycli/libgdx,tommycli/libgdx,noelsison2/libgdx,Senth/libgdx,yangweigbh/libgdx,zommuter/libgdx,kagehak/libgdx,xoppa/libgdx,toloudis/libgdx,Gliby/libgdx,firefly2442/libgdx,stinsonga/libgdx,codepoke/libgdx,nudelchef/libgdx,basherone/libgdxcn,cypherdare/libgdx,flaiker/libgdx,Gliby/libgdx,andyvand/libgdx,GreenLightning/libgdx,nrallakis/libgdx,SidneyXu/libgdx,ricardorigodon/libgdx,sarkanyi/libgdx,MovingBlocks/libgdx,ThiagoGarciaAlves/libgdx,ninoalma/libgdx,sarkanyi/libgdx,xpenatan/libgdx-LWJGL3,czyzby/libgdx,saltares/libgdx,andyvand/libgdx,Deftwun/libgdx,KrisLee/libgdx,jasonwee/libgdx,samskivert/libgdx,nooone/libgdx,ninoalma/libgdx,nooone/libgdx,stickyd/libgdx,sarkanyi/libgdx,MetSystem/libgdx,MathieuDuponchelle/gdx,josephknight/libgdx,MadcowD/libgdx,tell10glu/libgdx,stickyd/libgdx,fiesensee/libgdx,MathieuDuponchelle/gdx,noelsison2/libgdx,luischavez/libgdx,Zonglin-Li6565/libgdx,MathieuDuponchelle/gdx,Senth/libgdx,kagehak/libgdx,curtiszimmerman/libgdx,noelsison2/libgdx,sjosegarcia/libgdx,billgame/libgdx,toa5/libgdx,fiesensee/libgdx,gouessej/libgdx,nelsonsilva/libgdx,antag99/libgdx,Thotep/libgdx,SidneyXu/libgdx,jberberick/libgdx,flaiker/libgdx,snovak/libgdx,Xhanim/libgdx,UnluckyNinja/libgdx,del-sol/libgdx,toloudis/libgdx,revo09/libgdx,sarkanyi/libgdx,thepullman/libgdx,realitix/libgdx,haedri/libgdx-1,saqsun/libgdx,snovak/libgdx,ricardorigodon/libgdx,kzganesan/libgdx,basherone/libgdxcn,xranby/libgdx,srwonka/libGdx,nelsonsilva/libgdx,lordjone/libgdx,js78/libgdx,hyvas/libgdx,ttencate/libgdx,Deftwun/libgdx,xranby/libgdx,del-sol/libgdx,djom20/libgdx,noelsison2/libgdx,gouessej/libgdx,libgdx/libgdx,katiepino/libgdx,tell10glu/libgdx,kzganesan/libgdx,codepoke/libgdx,ztv/libgdx,Wisienkas/libgdx,JFixby/libgdx,ryoenji/libgdx,davebaol/libgdx,sinistersnare/libgdx,petugez/libgdx,saltares/libgdx,czyzby/libgdx,Zonglin-Li6565/libgdx,Senth/libgdx,alireza-hosseini/libgdx,PedroRomanoBarbosa/libgdx,Deftwun/libgdx,JFixby/libgdx,FyiurAmron/libgdx,ThiagoGarciaAlves/libgdx,andyvand/libgdx,FredGithub/libgdx,firefly2442/libgdx,bsmr-java/libgdx,josephknight/libgdx,luischavez/libgdx,billgame/libgdx,Deftwun/libgdx,JFixby/libgdx,Badazdz/libgdx,GreenLightning/libgdx,gdos/libgdx,hyvas/libgdx,xranby/libgdx,Deftwun/libgdx,collinsmith/libgdx,PedroRomanoBarbosa/libgdx,Gliby/libgdx,katiepino/libgdx,czyzby/libgdx,JDReutt/libgdx,GreenLightning/libgdx,lordjone/libgdx,Xhanim/libgdx,flaiker/libgdx,jberberick/libgdx,codepoke/libgdx,Badazdz/libgdx,Senth/libgdx,katiepino/libgdx,zommuter/libgdx,KrisLee/libgdx,Zonglin-Li6565/libgdx,kotcrab/libgdx,ya7lelkom/libgdx,kotcrab/libgdx,shiweihappy/libgdx
/* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) * * 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.badlogic.gdx.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.badlogic.gdx.Version; public class GdxNativesLoader { static private boolean nativesLoaded = false; static public boolean isWindows = System.getProperty("os.name").contains("Windows"); static public boolean isLinux = System.getProperty("os.name").contains("Linux"); static public boolean isMac = System.getProperty("os.name").contains("Mac"); static public boolean is64Bit = System.getProperty("os.arch").equals("amd64"); static public File nativesDir = new File(System.getProperty("java.io.tmpdir") + "/libgdx/" + Version.VERSION); static public boolean loadLibrary (String nativeFile32, String nativeFile64) { String path = extractLibrary(nativeFile32, nativeFile64); if (path != null) System.load(path); return path != null; } static public String extractLibrary (String native32, String native64) { String nativeFileName = is64Bit ? native64 : native32; try { // Extract native from classpath to temp dir. InputStream input = GdxNativesLoader.class.getResourceAsStream("/" + nativeFileName); if (input == null) return null; nativesDir.mkdirs(); File nativeFile = new File(nativesDir, nativeFileName); FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } input.close(); output.close(); return nativeFile.getAbsolutePath(); } catch (IOException ex) { new GdxRuntimeException("Error extracting native library: " + nativeFileName, ex).printStackTrace(); return null; } } /** * Loads the libgdx native libraries. */ static public void load () { if (nativesLoaded) return; String vm = System.getProperty("java.vm.name"); if (vm == null || !vm.contains("Dalvik")) { if (isWindows) { nativesLoaded = loadLibrary("gdx.dll", "gdx64.dll"); } else if (isMac) { nativesLoaded = loadLibrary("libgdx.dylib", "libgdx.dylib"); } else if (isLinux) { nativesLoaded = loadLibrary("libgdx.so", "libgdx-64.so"); } if (nativesLoaded) return; } String arch = System.getProperty("os.arch"); String os = System.getProperty("os.name"); if (!arch.equals("amd64") || os.contains("Mac")) { System.loadLibrary("gdx"); } else { System.loadLibrary("gdx-64"); } } }
gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java
/* * Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) * * 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.badlogic.gdx.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.badlogic.gdx.Version; public class GdxNativesLoader { static private boolean nativesLoaded = false; static public boolean isWindows = System.getProperty("os.name").contains("Windows"); static public boolean isLinux = System.getProperty("os.name").contains("Linux"); static public boolean isMac = System.getProperty("os.name").contains("Mac"); static public boolean is64Bit = System.getProperty("os.arch").equals("amd64"); static public File nativesDir = new File(System.getProperty("java.io.tmpdir") + "/libgdx/" + Version.VERSION); static public boolean loadLibrary (String nativeFile32, String nativeFile64) { String path = extractLibrary(nativeFile32, nativeFile64); if (path != null) System.load(path); return path != null; } static public String extractLibrary (String native32, String native64) { try { // Extract native from classpath to temp dir. String nativeFileName = is64Bit ? native64 : native32; InputStream input = GdxNativesLoader.class.getResourceAsStream("/" + nativeFileName); if (input == null) return null; nativesDir.mkdirs(); File nativeFile = new File(nativesDir, nativeFileName); FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } input.close(); output.close(); return nativeFile.getAbsolutePath(); } catch (IOException ex) { ex.printStackTrace(); return null; } } /** * Loads the libgdx native libraries. */ static public void load () { if (nativesLoaded) return; String vm = System.getProperty("java.vm.name"); if (vm == null || !vm.contains("Dalvik")) { if (isWindows) { nativesLoaded = loadLibrary("gdx.dll", "gdx64.dll"); } else if (isMac) { nativesLoaded = loadLibrary("libgdx.dylib", "libgdx.dylib"); } else if (isLinux) { nativesLoaded = loadLibrary("libgdx.so", "libgdx-64.so"); } if (nativesLoaded) return; } String arch = System.getProperty("os.arch"); String os = System.getProperty("os.name"); if (!arch.equals("amd64") || os.contains("Mac")) { System.loadLibrary("gdx"); } else { System.loadLibrary("gdx-64"); } } }
Better exception handling for an error extracting natives from classpath.
gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java
Better exception handling for an error extracting natives from classpath.
<ide><path>dx/src/com/badlogic/gdx/utils/GdxNativesLoader.java <ide> } <ide> <ide> static public String extractLibrary (String native32, String native64) { <add> String nativeFileName = is64Bit ? native64 : native32; <ide> try { <ide> // Extract native from classpath to temp dir. <del> String nativeFileName = is64Bit ? native64 : native32; <ide> InputStream input = GdxNativesLoader.class.getResourceAsStream("/" + nativeFileName); <ide> if (input == null) return null; <ide> nativesDir.mkdirs(); <ide> output.close(); <ide> return nativeFile.getAbsolutePath(); <ide> } catch (IOException ex) { <del> ex.printStackTrace(); <add> new GdxRuntimeException("Error extracting native library: " + nativeFileName, ex).printStackTrace(); <ide> return null; <ide> } <ide> }
JavaScript
apache-2.0
5d0425a3e63c17764976d6430dbe2f00c89a993e
0
soajs/soajs.dashboard
/** * Created by nicolas on 10/19/16. */ 'use strict'; var soajsCore = require("soajs"); var Mongo = soajsCore.mongo; var mongoObj = null; var soajsUtils = soajsCore.utils; var servicesCollectionName = 'services'; var daemonsCollectionName = 'daemons'; var groupConfigCollectionName = 'daemon_grpconf'; var environmentCollectionName = 'environment'; var gridfsCollectionName = 'fs.files'; var tenantCollectionName = 'tenants'; var productsCollectionName = 'products'; var hostsCollectionName = 'hosts'; var oauthUracCollectionName = 'oauth_urac'; var oauthTokenCollectionName = 'oauth_token'; var gitAccountsCollectionName = 'git_accounts'; var templatesCollectionName = 'templates'; var resourcesCollection = 'resources'; var customRegCollection = 'custom_registry'; var firstRun = true; var lib = { "initConnection": function (soajs) { function errorLogger(error) { if (error) { return soajs.log.error(error); } } var provision = { name: soajs.registry.coreDB.provision.name, prefix: soajs.registry.coreDB.provision.prefix, servers: soajs.registry.coreDB.provision.servers, credentials: soajs.registry.coreDB.provision.credentials, streaming: soajs.registry.coreDB.provision.streaming, URLParam: soajs.registry.coreDB.provision.URLParam, extraParam: soajs.registry.coreDB.provision.extraParam }; var switchedConnection = lib.switchConnection(soajs); if (switchedConnection && typeof switchedConnection === 'object' && Object.keys(switchedConnection).length > 0) { provision = switchedConnection; if (soajs.log) { soajs.log.debug('Switching to connection to project: ', soajs.inputmaskData.soajs_project); } } else if (switchedConnection === false) { if (soajs.log) { soajs.log.error("Connection refused, project provided in input does not belong to tenant!"); } //error return false; } else { if (soajs.log) { soajs.log.debug("Connecting to core project"); } } soajs.mongoDb = new Mongo(provision); if (firstRun) { soajs.mongoDb.createIndex(servicesCollectionName, { port: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { 'src.owner': 1, 'src.repo': 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { name: 1, port: 1, 'src.owner': 1, 'src.repo': 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { gcId: 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { name: 1, gcId: 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { port: 1, gcId: 1 }, errorLogger); //daemons soajs.mongoDb.createIndex(daemonsCollectionName, { name: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { port: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { name: 1, port: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { 'src.owner': 1, 'src.repo': 1 }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { name: 1, port: 1, 'src.owner': 1, 'src.repo': 1 }, errorLogger); //daemon_grpconf soajs.mongoDb.createIndex(groupConfigCollectionName, { daemon: 1 }, errorLogger); soajs.mongoDb.createIndex(groupConfigCollectionName, { name: 1 }, errorLogger); //environment soajs.mongoDb.createIndex(environmentCollectionName, { locked: 1 }, errorLogger); //fs.files // soajs.mongoDb.createIndex(gridfsCollectionName, {filename: 1}, {unique: true}, errorLogger); soajs.mongoDb.createIndex(gridfsCollectionName, { filename: 1, 'metadata.type': 1 }, errorLogger); soajs.mongoDb.createIndex(gridfsCollectionName, { 'metadata.type': 1 }, errorLogger); soajs.mongoDb.createIndex(gridfsCollectionName, { 'metadata.env': 1 }, errorLogger); //tenants soajs.mongoDb.createIndex(tenantCollectionName, { _id: 1, locked: 1 }, errorLogger); soajs.mongoDb.createIndex(tenantCollectionName, { name: 1 }, errorLogger); soajs.mongoDb.createIndex(tenantCollectionName, { type: 1 }, errorLogger); soajs.mongoDb.createIndex(tenantCollectionName, { 'application.keys.extKeys.env': 1 }, errorLogger); //products soajs.mongoDb.createIndex(productsCollectionName, { code: 1, "packages.code": 1 }, errorLogger); //hosts if (!process.env.SOAJS_DEPLOY_HA) { soajs.mongoDb.createIndex(hostsCollectionName, { _id: 1, locked: 1 }, errorLogger); soajs.mongoDb.createIndex(hostsCollectionName, { env: 1, name: 1, hostname: 1 }, errorLogger); soajs.mongoDb.createIndex(hostsCollectionName, { env: 1, name: 1, ip: 1, hostname: 1 }, errorLogger); soajs.mongoDb.createIndex(hostsCollectionName, { env: 1, type: 1, running: 1 }, errorLogger); } //oauth_urac soajs.mongoDb.createIndex(oauthUracCollectionName, { tId: 1, _id: 1 }, errorLogger); soajs.mongoDb.createIndex(oauthUracCollectionName, { tId: 1, userId: 1, _id: 1 }, errorLogger); soajs.mongoDb.createIndex(oauthTokenCollectionName, { expires: 1 }, { expireAfterSeconds: 0 }, errorLogger); //git_accounts soajs.mongoDb.createIndex(gitAccountsCollectionName, { _id: 1, 'repos.name': 1 }, errorLogger); soajs.mongoDb.createIndex(gitAccountsCollectionName, { 'repos.name': 1 }, errorLogger); soajs.mongoDb.createIndex(gitAccountsCollectionName, { owner: 1, provider: 1 }, errorLogger); //templates soajs.mongoDb.createIndex(templatesCollectionName, { code: 1 }, errorLogger); soajs.mongoDb.createIndex(templatesCollectionName, { type: 1 }, errorLogger); //resources soajs.mongoDb.createIndex(customRegCollection, { name: 1, type: 1, category: 1 }, errorLogger); //compound index, includes {name: 1}, {name: 1, type: 1} soajs.mongoDb.createIndex(resourcesCollection, { created: 1, shared: 1, sharedEnv: 1 }, errorLogger); //compound index, includes {created: 1}, {created: 1, shared: 1} //custom registry soajs.mongoDb.createIndex(customRegCollection, { name: 1, created: 1 }, errorLogger); //compound index, includes {name: 1} soajs.mongoDb.createIndex(customRegCollection, { created: 1, shared: 1, sharedEnv: 1 }, errorLogger); //compound index, includes {created: 1}, {created: 1, shared: 1} firstRun = false; } return true; }, /** * Close the mongo connection * @param {SOAJS Object} soajs */ "closeConnection": function (soajs) { if (soajs.mongoDb) { if (soajs.inputmaskData && soajs.inputmaskData.soajs_project) { soajs.log.debug('Closing connection to client core_provision', soajs.inputmaskData.soajs_project); } else { soajs.log.debug('Closing connection to core_provision'); } soajs.mongoDb.closeDb(); } }, "checkForMongo": function (soajs) { if (!soajs.mongoDb) { lib.initConnection(soajs); } }, "getDb": function (soajs) { lib.checkForMongo(soajs); return soajs.mongoDb; }, "generateId": function (soajs) { lib.checkForMongo(soajs); return new soajs.mongoDb.ObjectId(); }, "validateId": function (soajs, cb) { lib.checkForMongo(soajs); if (!soajs.inputmaskData.id) { soajs.log.error('No id provided'); if (cb) { return cb('no id provided'); } else { return null; } } try { soajs.inputmaskData.id = soajs.mongoDb.ObjectId(soajs.inputmaskData.id); return ((cb) ? cb(null, soajs.inputmaskData.id) : soajs.inputmaskData.id); } catch (e) { if (cb) { return cb(e); } else { soajs.log.error('Exception thrown while trying to get object id for ' + soajs.inputmaskData.id); soajs.log.error(e); return null; } } }, "validateCustomId": function (soajs, id, cb) { lib.checkForMongo(soajs); try { id = soajs.mongoDb.ObjectId(id); return ((cb) ? cb(null, id) : id); } catch (e) { if (cb) { return cb(e); } else { soajs.log.error('Exception thrown while trying to get object id for ' + id); soajs.log.error(e); return null; } } }, "countEntries": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.count(opts.collection, opts.conditions || {}, cb); }, "findEntries": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.find(opts.collection, opts.conditions || {}, opts.fields || null, opts.options || null, cb); }, "findEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.findOne(opts.collection, opts.conditions || {}, opts.fields || null, opts.options || null, cb); }, "saveEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.save(opts.collection, opts.record, opts.versioning || false, cb); }, "insertEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.insert(opts.collection, opts.record, opts.versioning || false, cb); }, "removeEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.remove(opts.collection, opts.conditions, cb); }, "updateEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.update(opts.collection, opts.conditions, opts.fields, opts.options || {}, opts.versioning || false, cb); }, "distinctEntries": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.distinct(opts.collection, opts.fields, opts.conditions, cb); }, "switchConnection": function (soajs) { var provision = true; if (process.env.SOAJS_SAAS) { soajs.log.info(soajs.servicesConfig); } if (process.env.SOAJS_SAAS && !soajs.tenant.locked) { if (soajs.servicesConfig && soajs.servicesConfig.SOAJS_SAAS) { if (soajs.inputmaskData.soajs_project && soajs.servicesConfig.SOAJS_SAAS[soajs.inputmaskData.soajs_project]) { if (soajs.registry.resources.cluster && soajs.registry.resources.cluster[soajs.inputmaskData.soajs_project]) { provision = soajsUtils.cloneObj(soajs.registry.resources.cluster[soajs.inputmaskData.soajs_project].config); provision.name = soajs.registry.coreDB.provision.name; provision.prefix = soajs.inputmaskData.soajs_project + "_"; soajs.log.info('Switch connection'); } else { soajs.log.error('Missing cluster for ', soajs.inputmaskData.soajs_project); return false; } } else { soajs.log.error('Missing project in servicesConfig.', soajs.inputmaskData.soajs_project); return false; } } else { soajs.log.error('Missing project in servicesConfig.', soajs.inputmaskData.soajs_project); return false; } } return provision; } }; module.exports = lib;
models/mongo.js
/** * Created by nicolas on 10/19/16. */ 'use strict'; var soajsCore = require("soajs"); var Mongo = soajsCore.mongo; var mongoObj = null; var soajsUtils = soajsCore.utils; var servicesCollectionName = 'services'; var daemonsCollectionName = 'daemons'; var groupConfigCollectionName = 'daemon_grpconf'; var environmentCollectionName = 'environment'; var gridfsCollectionName = 'fs.files'; var tenantCollectionName = 'tenants'; var productsCollectionName = 'products'; var hostsCollectionName = 'hosts'; var oauthUracCollectionName = 'oauth_urac'; var oauthTokenCollectionName = 'oauth_token'; var gitAccountsCollectionName = 'git_accounts'; var templatesCollectionName = 'templates'; var resourcesCollection = 'resources'; var customRegCollection = 'custom_registry'; var firstRun = true; var lib = { "initConnection": function (soajs) { function errorLogger(error) { if (error) { return soajs.log.error(error); } } var provision = { name: soajs.registry.coreDB.provision.name, prefix: soajs.registry.coreDB.provision.prefix, servers: soajs.registry.coreDB.provision.servers, credentials: soajs.registry.coreDB.provision.credentials, streaming: soajs.registry.coreDB.provision.streaming, URLParam: soajs.registry.coreDB.provision.URLParam, extraParam: soajs.registry.coreDB.provision.extraParam }; var switchedConnection = lib.switchConnection(soajs); if (switchedConnection && typeof switchedConnection === 'object' && Object.keys(switchedConnection).length > 0) { provision = switchedConnection; if (soajs.log) { soajs.log.debug('Switching to connection to project: ', soajs.inputmaskData.soajs_project); } } else if (switchedConnection === false) { if (soajs.log) { soajs.log.error("Connection refused, project provided in input does not belong to tenant!"); } //error return false; } else { if (soajs.log) { soajs.log.debug("Connecting to core project"); } } soajs.mongoDb = new Mongo(provision); if (firstRun) { soajs.mongoDb.createIndex(servicesCollectionName, { port: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { 'src.owner': 1, 'src.repo': 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { name: 1, port: 1, 'src.owner': 1, 'src.repo': 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { gcId: 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { name: 1, gcId: 1 }, errorLogger); soajs.mongoDb.createIndex(servicesCollectionName, { port: 1, gcId: 1 }, errorLogger); //daemons soajs.mongoDb.createIndex(daemonsCollectionName, { name: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { port: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { name: 1, port: 1 }, { unique: true }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { 'src.owner': 1, 'src.repo': 1 }, errorLogger); soajs.mongoDb.createIndex(daemonsCollectionName, { name: 1, port: 1, 'src.owner': 1, 'src.repo': 1 }, errorLogger); //daemon_grpconf soajs.mongoDb.createIndex(groupConfigCollectionName, { daemon: 1 }, errorLogger); soajs.mongoDb.createIndex(groupConfigCollectionName, { name: 1 }, errorLogger); //environment soajs.mongoDb.createIndex(environmentCollectionName, { locked: 1 }, errorLogger); //fs.files // soajs.mongoDb.createIndex(gridfsCollectionName, {filename: 1}, {unique: true}, errorLogger); soajs.mongoDb.createIndex(gridfsCollectionName, { filename: 1, 'metadata.type': 1 }, errorLogger); soajs.mongoDb.createIndex(gridfsCollectionName, { 'metadata.type': 1 }, errorLogger); soajs.mongoDb.createIndex(gridfsCollectionName, { 'metadata.env': 1 }, errorLogger); //tenants soajs.mongoDb.createIndex(tenantCollectionName, { _id: 1, locked: 1 }, errorLogger); soajs.mongoDb.createIndex(tenantCollectionName, { name: 1 }, errorLogger); soajs.mongoDb.createIndex(tenantCollectionName, { type: 1 }, errorLogger); soajs.mongoDb.createIndex(tenantCollectionName, { 'application.keys.extKeys.env': 1 }, errorLogger); //products soajs.mongoDb.createIndex(productsCollectionName, { code: 1, "packages.code": 1 }, errorLogger); //hosts if (!process.env.SOAJS_DEPLOY_HA) { soajs.mongoDb.createIndex(hostsCollectionName, { _id: 1, locked: 1 }, errorLogger); soajs.mongoDb.createIndex(hostsCollectionName, { env: 1, name: 1, hostname: 1 }, errorLogger); soajs.mongoDb.createIndex(hostsCollectionName, { env: 1, name: 1, ip: 1, hostname: 1 }, errorLogger); soajs.mongoDb.createIndex(hostsCollectionName, { env: 1, type: 1, running: 1 }, errorLogger); } //oauth_urac soajs.mongoDb.createIndex(oauthUracCollectionName, { tId: 1, _id: 1 }, errorLogger); soajs.mongoDb.createIndex(oauthUracCollectionName, { tId: 1, userId: 1, _id: 1 }, errorLogger); soajs.mongoDb.createIndex(oauthTokenCollectionName, { expires: 1 }, { expireAfterSeconds: 0 }, errorLogger); //git_accounts soajs.mongoDb.createIndex(gitAccountsCollectionName, { _id: 1, 'repos.name': 1 }, errorLogger); soajs.mongoDb.createIndex(gitAccountsCollectionName, { 'repos.name': 1 }, errorLogger); soajs.mongoDb.createIndex(gitAccountsCollectionName, { owner: 1, provider: 1 }, errorLogger); //templates soajs.mongoDb.createIndex(templatesCollectionName, { code: 1 }, errorLogger); soajs.mongoDb.createIndex(templatesCollectionName, { type: 1 }, errorLogger); //resources soajs.mongoDb.createIndex(customRegCollection, { name: 1, type: 1, category: 1 }, errorLogger); //compound index, includes {name: 1}, {name: 1, type: 1} soajs.mongoDb.createIndex(resourcesCollection, { created: 1, shared: 1, sharedEnv: 1 }, errorLogger); //compound index, includes {created: 1}, {created: 1, shared: 1} //custom registry soajs.mongoDb.createIndex(customRegCollection, { name: 1, created: 1 }, errorLogger); //compound index, includes {name: 1} soajs.mongoDb.createIndex(customRegCollection, { created: 1, shared: 1, sharedEnv: 1 }, errorLogger); //compound index, includes {created: 1}, {created: 1, shared: 1} firstRun = false; } return true; }, /** * Close the mongo connection * @param {SOAJS Object} soajs */ "closeConnection": function (soajs) { if (soajs.mongoDb) { if (soajs.inputmaskData && soajs.inputmaskData.soajs_project) { soajs.log.debug('Closing connection to client core_provision', soajs.inputmaskData.soajs_project); } else { soajs.log.debug('Closing connection to core_provision'); } soajs.mongoDb.closeDb(); } }, "checkForMongo": function (soajs) { if (!soajs.mongoDb) { lib.initConnection(soajs); } }, "getDb": function (soajs) { lib.checkForMongo(soajs); return soajs.mongoDb; }, "generateId": function (soajs) { lib.checkForMongo(soajs); return new soajs.mongoDb.ObjectId(); }, "validateId": function (soajs, cb) { lib.checkForMongo(soajs); if (!soajs.inputmaskData.id) { soajs.log.error('No id provided'); if (cb) { return cb('no id provided'); } else { return null; } } try { soajs.inputmaskData.id = soajs.mongoDb.ObjectId(soajs.inputmaskData.id); return ((cb) ? cb(null, soajs.inputmaskData.id) : soajs.inputmaskData.id); } catch (e) { if (cb) { return cb(e); } else { soajs.log.error('Exception thrown while trying to get object id for ' + soajs.inputmaskData.id); soajs.log.error(e); return null; } } }, "validateCustomId": function (soajs, id, cb) { lib.checkForMongo(soajs); try { id = soajs.mongoDb.ObjectId(id); return ((cb) ? cb(null, id) : id); } catch (e) { if (cb) { return cb(e); } else { soajs.log.error('Exception thrown while trying to get object id for ' + id); soajs.log.error(e); return null; } } }, "countEntries": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.count(opts.collection, opts.conditions || {}, cb); }, "findEntries": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.find(opts.collection, opts.conditions || {}, opts.fields || null, opts.options || null, cb); }, "findEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.findOne(opts.collection, opts.conditions || {}, opts.fields || null, opts.options || null, cb); }, "saveEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.save(opts.collection, opts.record, opts.versioning || false, cb); }, "insertEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.insert(opts.collection, opts.record, opts.versioning || false, cb); }, "removeEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.remove(opts.collection, opts.conditions, cb); }, "updateEntry": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.update(opts.collection, opts.conditions, opts.fields, opts.options || {}, opts.versioning || false, cb); }, "distinctEntries": function (soajs, opts, cb) { lib.checkForMongo(soajs); soajs.mongoDb.distinct(opts.collection, opts.fields, opts.conditions, cb); }, "switchConnection": function (soajs) { var provision = true; if (process.env.SOAJS_SAAS) { soajs.log.info(soajs.servicesConfig); } if (process.env.SOAJS_SAAS && (process.env.SOAJS_SAAS === true) && !soajs.tenant.locked) { if (soajs.servicesConfig && soajs.servicesConfig.SOAJS_SAAS) { if (soajs.inputmaskData.soajs_project && soajs.servicesConfig.SOAJS_SAAS[soajs.inputmaskData.soajs_project]) { if (soajs.registry.resources.cluster && soajs.registry.resources.cluster[soajs.inputmaskData.soajs_project]) { provision = soajsUtils.cloneObj(soajs.registry.resources.cluster[soajs.inputmaskData.soajs_project].config); provision.name = soajs.registry.coreDB.provision.name; provision.prefix = soajs.inputmaskData.soajs_project + "_"; soajs.log.info('Switch connection'); } else { soajs.log.error('Missing cluster for ', soajs.inputmaskData.soajs_project); return false; } } else { soajs.log.error('Missing project in servicesConfig.', soajs.inputmaskData.soajs_project); return false; } } else { soajs.log.error('Missing project in servicesConfig.', soajs.inputmaskData.soajs_project); return false; } } return provision; } }; module.exports = lib;
BUG FIX
models/mongo.js
BUG FIX
<ide><path>odels/mongo.js <ide> if (process.env.SOAJS_SAAS) { <ide> soajs.log.info(soajs.servicesConfig); <ide> } <del> if (process.env.SOAJS_SAAS && (process.env.SOAJS_SAAS === true) && !soajs.tenant.locked) { <add> if (process.env.SOAJS_SAAS && !soajs.tenant.locked) { <ide> if (soajs.servicesConfig && soajs.servicesConfig.SOAJS_SAAS) { <ide> if (soajs.inputmaskData.soajs_project && soajs.servicesConfig.SOAJS_SAAS[soajs.inputmaskData.soajs_project]) { <ide> if (soajs.registry.resources.cluster && soajs.registry.resources.cluster[soajs.inputmaskData.soajs_project]) {
JavaScript
mit
d084a8fe572a65ecadea0132afe4b395cc96c2b3
0
CodeWall-EStudio/XZone,CodeWall-EStudio/XZone,CodeWall-EStudio/XZone
var ObjectID = require('mongodb').ObjectID; var DBRef = require('mongodb').DBRef; var EventProxy = require('eventproxy'); var EventEmitter = require('events').EventEmitter; var us = require('underscore'); var db = require('./db'); var ERR = require('../errorcode'); var U = require('../util'); var Logger = require('../logger'); var mFile = require('./file'); exports.create = function(params, callback){ var groupId = params.groupId; var folder = params.folder; var isOpen = Number(params.isOpen) || 0; var isReadonly = Number(params.isReadonly) || 0; var doc = { name: params.name, creator: DBRef('user', params.creator), mark: params.mark || '', createTime: Date.now(), updateTime: Date.now(), type: 0, parent: null, deletable: ('deletable' in params) ? params.deletable : true, isOpen: isOpen === 1, // 0 非公开, 1 公开 isReadonly: isReadonly === 1, // 0 读写, 1 只读 top: null, hasChild: false }; if(groupId){ doc.group = DBRef('group', groupId); doc.closeTime = Number(params.closeTime) || 0; }else{ doc.prepare = params.prepareId ? DBRef('group', params.prepareId) : null; } if(folder){ doc.parent = DBRef('folder', folder._id); doc.top = folder.top || doc.parent; folder.hasChild = true; db.folder.findAndModify({ _id: folder._id }, [], { $set: { hasChild: true } }, { 'new':true }, function(err){ if(err){ Logger.error('models/folder/create', err); } }); }else{ doc.parent = doc.top = null; } db.folder.insert(doc, function(err, result){ if(err){ return callback(err); } result = result[0]; if(folder){ result.idpath = folder.idpath + ',' + result._id; }else{ result.idpath = result._id.toString(); } db.folder.save(result, function(err){ if(err){ Logger.error('models/folder/create', err); } }); callback(err, result); }); }; exports.getFolder = function(query, callback){ db.folder.findOne(query, callback); }; exports.modify = function(query, doc, callback){ doc.updatetime = Date.now(); db.folder.findAndModify(query, [], { $set: doc }, { 'new':true }, callback); }; function deleteFolderAndFiles(folder, callback){ db.folder.remove({ _id: folder._id }, function(err){ if(err){ Logger.error('>>>folder.delete [folder]', err); callback(err); return; } var options = { groupId: folder.group && folder.group.oid, updateUsed: true }; mFile.batchDelete({ 'folder.$id': folder._id, del: false }, options, function(err, count){ if(err){ Logger.error('>>>folder.delete [file]', err); callback(err); return; } callback(null, 1 + (count || 0)); }); }); } exports.delete = function(params, callback){ var folder = params.folder; var ep = new EventProxy(); ep.fail(callback); if(folder.hasChild){ var query = { idpath: new RegExp('.*\\b' + folder._id + '\\b.*') }; db.folder.find(query, ep.done('findAllChild')); }else{ deleteFolderAndFiles(folder, ep.doneLater('deleteDone')); } ep.on('findAllChild', function(docs){ if(!docs.length){ deleteFolderAndFiles(folder, ep.doneLater('deleteDone')); return; } ep.after('delete', docs.length, function(list){ ep.emit('deleteDone', U.calculate(list)); }); docs.forEach(function(doc){ deleteFolderAndFiles(doc, ep.group('delete')); }); }); ep.on('deleteDone', function(list){ db.folder.count({ 'parent.$id': folder.parent.oid }, function(err, count){ if(!err && !count){ // 没有文件了, 重置标志位 db.folder.update( { _id: folder.parent.oid }, { $set: { hasChild: false } }, function(){}); } callback(null, list); }); }); }; // 废弃, 用 search 代替 (recursive = false) // // exports.list = function(params, callback){ // var folderId = params.folderId; // // var groupId = params.groupId || null; // var isDeref = params.isDeref || false; // var extendQuery = params.extendQuery; // var query = { // 'parent.$id': folderId // }; // if(params.creator){ // query['creator.$id'] = params.creator; // } // if(extendQuery){ // query = us.extend(query, extendQuery); // } // db.search('folder', query, { order: params.order }, function(err, total, docs){ // if(err){ // callback(err); // }else if(total && docs && isDeref){ // db.dereferences(docs, {'creator': ['_id', 'nick']}, function(err, docs){ // if(err){ // callback(err); // }else{ // callback(null, total || 0, docs); // } // }); // }else{ // callback(null, total || 0, docs); // } // }); // }; exports.search = function(params, callback){ var folderId = params.folderId; var groupId = params.groupId || null; var creator = params.creator || null; var keyword = params.keyword || ''; var isDeref = params.isDeref || false; var recursive = params.recursive || false; var extendQuery = params.extendQuery; var query = {}; if(recursive){ query['$or'] = [ { 'parent.$id': folderId }, { idpath: new RegExp('.*\\b' + folderId + '\\b.*') } ]; query['_id'] = { $ne: folderId }; }else{ query['parent.$id'] = folderId; } if(keyword){ query['name'] = new RegExp('.*' + U.encodeRegexp(keyword) + '.*'); } if(creator){ query['creator.$id'] = creator; } if(groupId){ query['group.$id'] = groupId; } if(extendQuery){ query = us.extend(query, extendQuery); } db.search('folder', query, params, function(err, total, docs){ if(err){ callback(err); }else if(total && docs && isDeref){ db.dereferences(docs, {'creator': ['_id', 'nick']}, function(err, docs){ if(err){ callback(err); }else{ callback(null, total || 0, docs); } }); }else{ callback(null, total || 0, docs); } }); }; exports.statistics = function(folderId, options, callback){ var searchParams = { folderId: folderId, recursive: true }; exports.search(searchParams, function(err, total/*, docs*/){ if(err){ return callback(err, total); } callback(null, { total: total }); }); };
server/models/folder.js
var ObjectID = require('mongodb').ObjectID; var DBRef = require('mongodb').DBRef; var EventProxy = require('eventproxy'); var EventEmitter = require('events').EventEmitter; var us = require('underscore'); var db = require('./db'); var ERR = require('../errorcode'); var U = require('../util'); var Logger = require('../logger'); var mFile = require('./file'); exports.create = function(params, callback){ var groupId = params.groupId; var folder = params.folder; var isOpen = Number(params.isOpen) || 0; var isReadonly = Number(params.isReadonly) || 0; var doc = { name: params.name, creator: DBRef('user', params.creator), mark: params.mark || '', createTime: Date.now(), updateTime: Date.now(), type: 0, parent: null, deletable: ('deletable' in params) ? params.deletable : true, isOpen: isOpen === 1, // 0 非公开, 1 公开 isReadonly: isReadonly === 1, // 0 读写, 1 只读 top: null, hasChild: false }; if(groupId){ doc.group = DBRef('group', groupId); doc.closeTime = Number(params.closeTime) || 0; }else{ doc.prepare = params.prepareId ? DBRef('group', params.prepareId) : null; } if(folder){ doc.parent = DBRef('folder', folder._id); doc.top = folder.top || doc.parent; folder.hasChild = true; db.folder.findAndModify({ _id: folder._id }, [], { $set: { hasChild: true } }, { 'new':true }, function(err){ if(err){ Logger.error('models/folder/create', err); } }); }else{ doc.parent = doc.top = null; } db.folder.insert(doc, function(err, result){ if(err){ return callback(err); } result = result[0]; if(folder){ result.idpath = folder.idpath + ',' + result._id; }else{ result.idpath = result._id.toString(); } db.folder.save(result, function(err){ if(err){ Logger.error('models/folder/create', err); } }); callback(err, result); }); }; exports.getFolder = function(query, callback){ db.folder.findOne(query, callback); }; exports.modify = function(query, doc, callback){ doc.updatetime = Date.now(); db.folder.findAndModify(query, [], { $set: doc }, { 'new':true }, callback); }; function deleteFolderAndFiles(folder, callback){ db.folder.remove({ _id: folder._id }, function(err){ if(err){ Logger.error('>>>folder.delete [folder]', err); callback(err); return; } var options = { groupId: folder.group && folder.group.oid, updateUsed: true }; mFile.batchDelete({ 'folder.$id': folder._id }, options, function(err, count){ if(err){ Logger.error('>>>folder.delete [file]', err); callback(err); return; } callback(null, 1 + (count || 0)); }); }); } exports.delete = function(params, callback){ var folder = params.folder; var ep = new EventProxy(); ep.fail(callback); if(folder.hasChild){ var query = { idpath: new RegExp('.*\\b' + folder._id + '\\b.*') }; db.folder.find(query, ep.done('findAllChild')); }else{ deleteFolderAndFiles(folder, ep.doneLater('deleteDone')); } ep.on('findAllChild', function(docs){ if(!docs.length){ deleteFolderAndFiles(folder, ep.doneLater('deleteDone')); return; } ep.after('delete', docs.length, function(list){ ep.emit('deleteDone', U.calculate(list)); }); docs.forEach(function(doc){ deleteFolderAndFiles(doc, ep.group('delete')); }); }); ep.on('deleteDone', function(list){ db.folder.count({ 'parent.$id': folder.parent.oid }, function(err, count){ if(!err && !count){ // 没有文件了, 重置标志位 db.folder.update( { _id: folder.parent.oid }, { $set: { hasChild: false } }, function(){}); } callback(null, list); }); }); }; // 废弃, 用 search 代替 (recursive = false) // // exports.list = function(params, callback){ // var folderId = params.folderId; // // var groupId = params.groupId || null; // var isDeref = params.isDeref || false; // var extendQuery = params.extendQuery; // var query = { // 'parent.$id': folderId // }; // if(params.creator){ // query['creator.$id'] = params.creator; // } // if(extendQuery){ // query = us.extend(query, extendQuery); // } // db.search('folder', query, { order: params.order }, function(err, total, docs){ // if(err){ // callback(err); // }else if(total && docs && isDeref){ // db.dereferences(docs, {'creator': ['_id', 'nick']}, function(err, docs){ // if(err){ // callback(err); // }else{ // callback(null, total || 0, docs); // } // }); // }else{ // callback(null, total || 0, docs); // } // }); // }; exports.search = function(params, callback){ var folderId = params.folderId; var groupId = params.groupId || null; var creator = params.creator || null; var keyword = params.keyword || ''; var isDeref = params.isDeref || false; var recursive = params.recursive || false; var extendQuery = params.extendQuery; var query = {}; if(recursive){ query['$or'] = [ { 'parent.$id': folderId }, { idpath: new RegExp('.*\\b' + folderId + '\\b.*') } ]; query['_id'] = { $ne: folderId }; }else{ query['parent.$id'] = folderId; } if(keyword){ query['name'] = new RegExp('.*' + U.encodeRegexp(keyword) + '.*'); } if(creator){ query['creator.$id'] = creator; } if(groupId){ query['group.$id'] = groupId; } if(extendQuery){ query = us.extend(query, extendQuery); } db.search('folder', query, params, function(err, total, docs){ if(err){ callback(err); }else if(total && docs && isDeref){ db.dereferences(docs, {'creator': ['_id', 'nick']}, function(err, docs){ if(err){ callback(err); }else{ callback(null, total || 0, docs); } }); }else{ callback(null, total || 0, docs); } }); }; exports.statistics = function(folderId, options, callback){ var searchParams = { folderId: folderId, recursive: true }; exports.search(searchParams, function(err, total/*, docs*/){ if(err){ return callback(err, total); } callback(null, { total: total }); }); };
update
server/models/folder.js
update
<ide><path>erver/models/folder.js <ide> updateUsed: true <ide> }; <ide> <del> mFile.batchDelete({ 'folder.$id': folder._id }, options, function(err, count){ <add> mFile.batchDelete({ 'folder.$id': folder._id, del: false }, options, function(err, count){ <ide> <ide> if(err){ <ide> Logger.error('>>>folder.delete [file]', err);
Java
apache-2.0
158ede1c5eee2a6b5f387eb2422b70a810c0c7f2
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * * Copyright 2016, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.spine3.base; import com.google.protobuf.FieldMask; import com.google.protobuf.ProtocolStringList; import org.junit.Test; import org.spine3.client.EntityFilters; import org.spine3.client.EntityId; import org.spine3.client.EntityIdFilter; import org.spine3.client.Query; import org.spine3.client.Target; import org.spine3.protobuf.AnyPacker; import org.spine3.protobuf.TypeUrl; import org.spine3.test.queries.TestEntity; import org.spine3.test.queries.TestEntityId; import java.util.List; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.spine3.test.Tests.hasPrivateUtilityConstructor; /** * @author Alex Tymchenko */ @SuppressWarnings({"LocalVariableNamingConvention", "MagicNumber"}) public class QueriesShould { @Test public void have_private_constructor() { assertTrue(hasPrivateUtilityConstructor(Queries.class)); } @Test public void compose_proper_read_all_query() { final Class<TestEntity> targetEntityClass = TestEntity.class; final Query readAllQuery = Queries.readAll(targetEntityClass); assertNotNull(readAllQuery); // `EntityFilters` must be default as this value was not set. checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllQuery); // `FieldMask` must be default as `paths` were not set. checkFieldMaskEmpty(readAllQuery); } @Test public void compose_proper_read_all_query_with_single_path() { final Class<TestEntity> targetEntityClass = TestEntity.class; final String firstPropertyFieldName = TestEntity.getDescriptor() .getFields() .get(1) .getFullName(); final Query readAllWithPathFilteringQuery = Queries.readAll(targetEntityClass, firstPropertyFieldName); assertNotNull(readAllWithPathFilteringQuery); checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllWithPathFilteringQuery); final FieldMask fieldMask = readAllWithPathFilteringQuery.getFieldMask(); assertEquals(1, fieldMask.getPathsCount()); // as we set the only path value. final String firstPath = fieldMask.getPaths(0); assertEquals(firstPropertyFieldName, firstPath); } @Test public void compose_proper_read_all_query_with_multiple_paths() { final Class<TestEntity> targetEntityClass = TestEntity.class; final String[] paths = {"some", "random", "paths"}; final Query readAllWithPathFilteringQuery = Queries.readAll(targetEntityClass, paths); assertNotNull(readAllWithPathFilteringQuery); checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllWithPathFilteringQuery); final FieldMask fieldMask = readAllWithPathFilteringQuery.getFieldMask(); assertEquals(paths.length, fieldMask.getPathsCount()); final ProtocolStringList pathsList = fieldMask.getPathsList(); for (String expectedPath : paths) { assertTrue(pathsList.contains(expectedPath)); } } @Test public void compose_proper_read_by_ids_query() { final Class<TestEntity> targetEntityClass = TestEntity.class; final Set<TestEntityId> testEntityIds = newHashSet(TestEntityId.newBuilder() .setValue(1) .build(), TestEntityId.newBuilder() .setValue(7) .build(), TestEntityId.newBuilder() .setValue(15) .build() ); final Query readByIdsQuery = Queries.readByIds(targetEntityClass, testEntityIds); assertNotNull(readByIdsQuery); checkFieldMaskEmpty(readByIdsQuery); final Target target = checkTarget(targetEntityClass, readByIdsQuery); final EntityFilters filters = target.getFilters(); assertNotNull(filters); final EntityIdFilter idFilter = filters.getIdFilter(); assertNotNull(idFilter); final List<EntityId> actualListOfIds = idFilter.getIdsList(); for (TestEntityId testEntityId : testEntityIds) { final EntityId expectedEntityId = EntityId.newBuilder() .setId(AnyPacker.pack(testEntityId)) .build(); assertTrue(actualListOfIds.contains(expectedEntityId)); } } private static void checkFieldMaskEmpty(Query query) { final FieldMask fieldMask = query.getFieldMask(); assertNotNull(fieldMask); assertEquals(FieldMask.getDefaultInstance(), fieldMask); } private static void checkTypeCorrectAndFiltersEmpty(Class<TestEntity> expectedTargetClass, Query query) { final Target entityTarget = checkTarget(expectedTargetClass, query); final EntityFilters filters = entityTarget.getFilters(); assertNotNull(filters); assertEquals(EntityFilters.getDefaultInstance(), filters); } private static Target checkTarget(Class<TestEntity> targetEntityClass, Query query) { final Target entityTarget = query.getTarget(); assertNotNull(entityTarget); final String expectedTypeName = TypeUrl.of(targetEntityClass) .getTypeName(); assertEquals(expectedTypeName, entityTarget.getType()); return entityTarget; } }
client/src/test/java/org/spine3/base/QueriesShould.java
/* * * Copyright 2016, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.spine3.base; import com.google.protobuf.FieldMask; import com.google.protobuf.ProtocolStringList; import org.junit.Test; import org.spine3.client.EntityFilters; import org.spine3.client.Query; import org.spine3.client.Target; import org.spine3.protobuf.TypeUrl; import org.spine3.test.queries.TestEntity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.spine3.test.Tests.hasPrivateUtilityConstructor; /** * @author Alex Tymchenko */ @SuppressWarnings("LocalVariableNamingConvention") public class QueriesShould { @Test public void have_private_constructor() { assertTrue(hasPrivateUtilityConstructor(Queries.class)); } @Test public void compose_proper_read_all_query() { final Class<TestEntity> targetEntityClass = TestEntity.class; final Query readAllQuery = Queries.readAll(targetEntityClass); assertNotNull(readAllQuery); checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllQuery); // `FieldMask` must be default as `paths` were not set. final FieldMask fieldMask = readAllQuery.getFieldMask(); assertNotNull(fieldMask); assertEquals(FieldMask.getDefaultInstance(), fieldMask); } @Test public void compose_proper_read_all_query_with_single_path() { final Class<TestEntity> targetEntityClass = TestEntity.class; final String firstPropertyFieldName = TestEntity.getDescriptor() .getFields() .get(1) .getFullName(); final Query readAllWithPathFilteringQuery = Queries.readAll(targetEntityClass, firstPropertyFieldName); assertNotNull(readAllWithPathFilteringQuery); checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllWithPathFilteringQuery); final FieldMask fieldMask = readAllWithPathFilteringQuery.getFieldMask(); assertEquals(1, fieldMask.getPathsCount()); // as we set the only path value. final String firstPath = fieldMask.getPaths(0); assertEquals(firstPropertyFieldName, firstPath); } @Test public void compose_proper_read_all_query_with_multiple_paths() { final Class<TestEntity> targetEntityClass = TestEntity.class; final String[] paths = {"some", "random", "paths"}; final Query readAllWithPathFilteringQuery = Queries.readAll(targetEntityClass, paths); assertNotNull(readAllWithPathFilteringQuery); checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllWithPathFilteringQuery); final FieldMask fieldMask = readAllWithPathFilteringQuery.getFieldMask(); assertEquals(paths.length, fieldMask.getPathsCount()); final ProtocolStringList pathsList = fieldMask.getPathsList(); for (String expectedPath : paths) { assertTrue(pathsList.contains(expectedPath)); } } private static void checkTypeCorrectAndFiltersEmpty(Class<TestEntity> targetEntityClass, Query readAllQuery) { final Target entityTarget = readAllQuery.getTarget(); assertNotNull(entityTarget); final String expectedTypeName = TypeUrl.of(targetEntityClass) .getTypeName(); assertEquals(expectedTypeName, entityTarget.getType()); // `EntityFilters` must be default as this value was not set. final EntityFilters filters = entityTarget.getFilters(); assertNotNull(filters); assertEquals(EntityFilters.getDefaultInstance(), filters); } }
Cover one of `Queries#readByIds()` cases with tests.
client/src/test/java/org/spine3/base/QueriesShould.java
Cover one of `Queries#readByIds()` cases with tests.
<ide><path>lient/src/test/java/org/spine3/base/QueriesShould.java <ide> import com.google.protobuf.ProtocolStringList; <ide> import org.junit.Test; <ide> import org.spine3.client.EntityFilters; <add>import org.spine3.client.EntityId; <add>import org.spine3.client.EntityIdFilter; <ide> import org.spine3.client.Query; <ide> import org.spine3.client.Target; <add>import org.spine3.protobuf.AnyPacker; <ide> import org.spine3.protobuf.TypeUrl; <ide> import org.spine3.test.queries.TestEntity; <add>import org.spine3.test.queries.TestEntityId; <ide> <add>import java.util.List; <add>import java.util.Set; <add> <add>import static com.google.common.collect.Sets.newHashSet; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertNotNull; <ide> import static org.junit.Assert.assertTrue; <ide> /** <ide> * @author Alex Tymchenko <ide> */ <del>@SuppressWarnings("LocalVariableNamingConvention") <add>@SuppressWarnings({"LocalVariableNamingConvention", "MagicNumber"}) <ide> public class QueriesShould { <ide> <ide> @Test <ide> final Query readAllQuery = Queries.readAll(targetEntityClass); <ide> assertNotNull(readAllQuery); <ide> <add> // `EntityFilters` must be default as this value was not set. <ide> checkTypeCorrectAndFiltersEmpty(targetEntityClass, readAllQuery); <ide> <ide> // `FieldMask` must be default as `paths` were not set. <del> final FieldMask fieldMask = readAllQuery.getFieldMask(); <del> assertNotNull(fieldMask); <del> assertEquals(FieldMask.getDefaultInstance(), fieldMask); <add> checkFieldMaskEmpty(readAllQuery); <ide> } <ide> <ide> @Test <ide> } <ide> } <ide> <add> @Test <add> public void compose_proper_read_by_ids_query() { <add> final Class<TestEntity> targetEntityClass = TestEntity.class; <ide> <del> private static void checkTypeCorrectAndFiltersEmpty(Class<TestEntity> targetEntityClass, Query readAllQuery) { <del> final Target entityTarget = readAllQuery.getTarget(); <add> final Set<TestEntityId> testEntityIds = newHashSet(TestEntityId.newBuilder() <add> .setValue(1) <add> .build(), <add> TestEntityId.newBuilder() <add> .setValue(7) <add> .build(), <add> TestEntityId.newBuilder() <add> .setValue(15) <add> .build() <add> ); <add> final Query readByIdsQuery = Queries.readByIds(targetEntityClass, testEntityIds); <add> assertNotNull(readByIdsQuery); <add> <add> checkFieldMaskEmpty(readByIdsQuery); <add> <add> final Target target = checkTarget(targetEntityClass, readByIdsQuery); <add> final EntityFilters filters = target.getFilters(); <add> assertNotNull(filters); <add> final EntityIdFilter idFilter = filters.getIdFilter(); <add> assertNotNull(idFilter); <add> final List<EntityId> actualListOfIds = idFilter.getIdsList(); <add> for (TestEntityId testEntityId : testEntityIds) { <add> final EntityId expectedEntityId = EntityId.newBuilder() <add> .setId(AnyPacker.pack(testEntityId)) <add> .build(); <add> assertTrue(actualListOfIds.contains(expectedEntityId)); <add> } <add> } <add> <add> private static void checkFieldMaskEmpty(Query query) { <add> final FieldMask fieldMask = query.getFieldMask(); <add> assertNotNull(fieldMask); <add> assertEquals(FieldMask.getDefaultInstance(), fieldMask); <add> } <add> <add> private static void checkTypeCorrectAndFiltersEmpty(Class<TestEntity> expectedTargetClass, Query query) { <add> final Target entityTarget = checkTarget(expectedTargetClass, query); <add> <add> final EntityFilters filters = entityTarget.getFilters(); <add> assertNotNull(filters); <add> assertEquals(EntityFilters.getDefaultInstance(), filters); <add> } <add> <add> private static Target checkTarget(Class<TestEntity> targetEntityClass, Query query) { <add> final Target entityTarget = query.getTarget(); <ide> assertNotNull(entityTarget); <ide> <ide> final String expectedTypeName = TypeUrl.of(targetEntityClass) <ide> .getTypeName(); <ide> assertEquals(expectedTypeName, entityTarget.getType()); <del> <del> // `EntityFilters` must be default as this value was not set. <del> final EntityFilters filters = entityTarget.getFilters(); <del> assertNotNull(filters); <del> assertEquals(EntityFilters.getDefaultInstance(), filters); <add> return entityTarget; <ide> } <ide> <ide> }
Java
apache-2.0
674697a12fe5155875349940c3f7ca3a8cea1fdb
0
ProgrammingLife2016/PL4-2016
package application.controllers; import core.graph.Graph; import core.graph.PhylogeneticTree; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.geometry.Rectangle2D; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.MenuBar; import javafx.scene.control.ScrollPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Screen; import java.io.IOException; import java.net.URL; import java.util.Comparator; import java.util.List; import java.util.ResourceBundle; /** * MainController for GUI. */ public class MainController extends Controller<BorderPane> { @FXML ScrollPane screen; @FXML MenuBar menuBar; @FXML FlowPane pane; @FXML ListView list; @FXML TextFlow infoList; @FXML VBox listVBox; Rectangle2D screenSize; /** * Constructor to create MainController based on abstract Controller. */ public MainController() { super(new BorderPane()); loadFXMLfile("/fxml/main.fxml"); } /** * Initialize method for the controller. * * @param location location for relative paths. * @param resources resources to localize the root object. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public final void initialize(URL location, ResourceBundle resources) { screenSize = Screen.getPrimary().getVisualBounds(); createMenu(); createInfoList(); } /** * On the right side of the screen, create a VBox showing: * - A list with all genome strains. * - A box with info on a selected node. */ private void createInfoList() { listVBox = new VBox(); createList(); createNodeInfo(); listVBox.getChildren().addAll(list, infoList); } /** * Create a list on the right side of the screen with all genomes. */ private void createList() { list = new ListView<>(); list.setPlaceholder(new Label("No Genomes Loaded.")); list.setOnMouseClicked(event -> { if (!(list.getSelectionModel().getSelectedItem() == (null))) { fillGraph(list.getSelectionModel().getSelectedItem()); } System.out.println(list.getSelectionModel().getSelectedItem()); }); } /** * Create an info panel to show the information on a node. */ private void createNodeInfo() { infoList = new TextFlow(); //ToDo: add more Text for extra info. Text seq = new Text(); seq.setText("Test"); infoList.getChildren().addAll(seq); } /** * Method to fill the graph. * * @param ref the reference string. */ public void fillGraph(Object ref) { Graph graph = new Graph(); GraphController graphController = new GraphController(graph, ref); screen = graphController.getRoot(); this.getRoot().setCenter(screen); List<String> genomes = graphController.getGenomes(); genomes.sort(Comparator.naturalOrder()); list.setItems(FXCollections.observableArrayList(genomes)); showListVBox(); } /** * Method to fill the phylogenetic tree. */ public void fillTree() { try { PhylogeneticTree pt = new PhylogeneticTree(); pt.setup(); TreeController treeController = new TreeController(pt); screen = treeController.getRoot(); this.getRoot().setCenter(screen); } catch (IOException e) { e.printStackTrace(); } hideListVBox(); } /** * Method to create the menu bar. */ public void createMenu() { MenuFactory menuFactory = new MenuFactory(this); menuBar = menuFactory.createMenu(menuBar); this.getRoot().setTop(menuBar); } /** * Switches the scene to the graph view. */ public void switchScene() { fillGraph(null); } /** * Switches the scene to the phylogenetic tree view. */ public void switchTreeScene() { fillTree(); } /** * Show the info panel. */ private void showListVBox() { this.getRoot().setRight(listVBox); } /** * Hide the info panel. */ private void hideListVBox() { this.getRoot().getChildren().remove(listVBox); } }
src/main/java/application/controllers/MainController.java
package application.controllers; import core.graph.Graph; import core.graph.PhylogeneticTree; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.geometry.Rectangle2D; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.MenuBar; import javafx.scene.control.ScrollPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.Screen; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; /** * MainController for GUI. */ public class MainController extends Controller<BorderPane> { @FXML ScrollPane screen; @FXML MenuBar menuBar; @FXML FlowPane pane; @FXML ListView list; @FXML TextFlow infoList; @FXML VBox listVBox; Rectangle2D screenSize; /** * Constructor to create MainController based on abstract Controller. */ public MainController() { super(new BorderPane()); loadFXMLfile("/fxml/main.fxml"); } /** * Initialize method for the controller. * * @param location location for relative paths. * @param resources resources to localize the root object. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public final void initialize(URL location, ResourceBundle resources) { screenSize = Screen.getPrimary().getVisualBounds(); createMenu(); createInfoList(); //createInfoList(); // this.getRoot().getStylesheets().add("application/css/main.css"); // this.getRoot().getStyleClass().add("root"); } // private void createPane() { // pane = new FlowPane(); // pane.getChildren(); // } // // private void createInfoList() { // infoList = new ListView<String>(); // ObservableList<String> items = FXCollections.observableArrayList( // "Select a Node to show info"); // list.setOnMouseClicked(event -> // System.out.println(list.getSelectionModel().getSelectedItem())); // list.setItems(items); // this.getRoot().setRight(list); // } /** * On the right side of the screen, create a VBox showing: * - A list with all genome strains. * - A box with info on a selected node. */ private void createInfoList() { listVBox = new VBox(); createList(); createNodeInfo(); listVBox.getChildren().addAll(list, infoList); } /** * Create a list on the right side of the screen with all genomes. */ private void createList() { list = new ListView<>(); list.setPlaceholder(new Label("No Genomes Loaded.")); list.setOnMouseClicked(event -> { if(!(list.getSelectionModel().getSelectedItem()==(null))) { fillGraph(list.getSelectionModel().getSelectedItem()); } System.out.println(list.getSelectionModel().getSelectedItem()); }); } /** * Create an info panel to show the information on a node. */ private void createNodeInfo() { infoList = new TextFlow(); //ToDo: add more Text for extra info. Text seq = new Text(); seq.setText("Test"); infoList.getChildren().addAll(seq); } /** * Method to fill the graph. * * @param ref the reference string. */ public void fillGraph(Object ref) { Graph graph = new Graph(); GraphController graphController = new GraphController(graph, ref); screen = graphController.getRoot(); this.getRoot().setCenter(screen); list.setItems(FXCollections.observableArrayList(graphController.getGenomes())); showListVBox(); } /** * Method to fill the phylogenetic tree. */ public void fillTree() { try { PhylogeneticTree pt = new PhylogeneticTree(); pt.setup(); TreeController treeController = new TreeController(pt); screen = treeController.getRoot(); this.getRoot().setCenter(screen); } catch (IOException e) { e.printStackTrace(); } hideListVBox(); } /** * Method to create the menu bar. */ public void createMenu() { MenuFactory menuFactory = new MenuFactory(this); menuBar = menuFactory.createMenu(menuBar); this.getRoot().setTop(menuBar); } /** * Switches the scene to the graph view. */ public void switchScene() { fillGraph(null); } /** * Switches the scene to the phylogenetic tree view. */ public void switchTreeScene() { fillTree(); } /** * Show the info panel. */ private void showListVBox() { this.getRoot().setRight(listVBox); } /** * Hide the info panel. */ private void hideListVBox() { this.getRoot().getChildren().remove(listVBox); } }
Genomes are now in natural order.
src/main/java/application/controllers/MainController.java
Genomes are now in natural order.
<ide><path>rc/main/java/application/controllers/MainController.java <ide> import core.graph.PhylogeneticTree; <ide> import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; <ide> import javafx.collections.FXCollections; <del>import javafx.collections.ObservableList; <ide> import javafx.fxml.FXML; <ide> import javafx.geometry.Rectangle2D; <ide> import javafx.scene.control.Label; <ide> <ide> import java.io.IOException; <ide> import java.net.URL; <add>import java.util.Comparator; <add>import java.util.List; <ide> import java.util.ResourceBundle; <ide> <ide> /** <ide> <ide> createMenu(); <ide> createInfoList(); <del> //createInfoList(); <del> <del>// this.getRoot().getStylesheets().add("application/css/main.css"); <del>// this.getRoot().getStyleClass().add("root"); <ide> } <del> <del>// private void createPane() { <del>// pane = new FlowPane(); <del>// pane.getChildren(); <del>// } <del>// <del>// private void createInfoList() { <del>// infoList = new ListView<String>(); <del>// ObservableList<String> items = FXCollections.observableArrayList( <del>// "Select a Node to show info"); <del>// list.setOnMouseClicked(event -> <del>// System.out.println(list.getSelectionModel().getSelectedItem())); <del>// list.setItems(items); <del>// this.getRoot().setRight(list); <del>// } <ide> <ide> /** <ide> * On the right side of the screen, create a VBox showing: <del> * - A list with all genome strains. <del> * - A box with info on a selected node. <add> * - A list with all genome strains. <add> * - A box with info on a selected node. <ide> */ <ide> private void createInfoList() { <ide> listVBox = new VBox(); <ide> list = new ListView<>(); <ide> list.setPlaceholder(new Label("No Genomes Loaded.")); <ide> list.setOnMouseClicked(event -> { <del> if(!(list.getSelectionModel().getSelectedItem()==(null))) { <add> if (!(list.getSelectionModel().getSelectedItem() == (null))) { <ide> fillGraph(list.getSelectionModel().getSelectedItem()); <ide> } <ide> System.out.println(list.getSelectionModel().getSelectedItem()); <ide> GraphController graphController = new GraphController(graph, ref); <ide> screen = graphController.getRoot(); <ide> this.getRoot().setCenter(screen); <del> list.setItems(FXCollections.observableArrayList(graphController.getGenomes())); <add> List<String> genomes = graphController.getGenomes(); <add> genomes.sort(Comparator.naturalOrder()); <add> list.setItems(FXCollections.observableArrayList(genomes)); <ide> showListVBox(); <ide> } <ide>
Java
apache-2.0
abaac0b29cf93315b75f3b6f6136adc90bd1f6b6
0
wenwei-dev/rest-client,junefun/rest-client,junefun/rest-client,EonHa-Lee/rest-client,snitheesh/rest-client,jmsosa/rest-client,dybdalk/rest-client,abbasmajeed/rest-client,rvkiran/rest-client,cotarola93/rest-client,geub/rest-client,sequethin/rest-client,vit256/rest-client,minafaw/rest-client,truvakitap/rest-client,msezgi/rest-client,pavanreddyboppidi/rest-client,javierfileiv/rest-client,abbasmajeed/rest-client,chinasunysh/rest-client,wenwei-dev/rest-client,snitheesh/rest-client,minafaw/rest-client,cotarola93/rest-client,pavanreddyboppidi/rest-client,daocoder/rest-client,jmsosa/rest-client,komadee/rest-client,ocsbilisim/rest-client,ahnbs82/rest-client,dybdalk/rest-client,vegeth1985/rest-client,viks01/rest-client,ahnbs82/rest-client,ahnbs82/rest-client,javierfileiv/rest-client,komadee/rest-client,vit256/rest-client,erickgugo/rest-client,snitheesh/rest-client,chinasunysh/rest-client,edwincalzada/rest-client,ZacksTsang/rest-client,dybdalk/rest-client,SSYouknowit/rest-client,wiztools/rest-client,geub/rest-client,ZacksTsang/rest-client,yeradis/rest-client,jymsy/rest-client,xxairwolf/xxknightrider-rest-client,yeradis/rest-client,wiztools/rest-client,abhinav118/rest-client,komadee/rest-client,hiro117/rest-client,npsyche/rest-client,vegeth1985/rest-client,viks01/rest-client,ezbreaks/rest-client,SSYouknowit/rest-client,jmsosa/rest-client,daocoder/rest-client,abhinav118/rest-client,rvkiran/rest-client,cotarola93/rest-client,abhinav118/rest-client,abbasmajeed/rest-client,jymsy/rest-client,xxairwolf/xxknightrider-rest-client,erickgugo/rest-client,EonHa-Lee/rest-client,daocoder/rest-client,ZacksTsang/rest-client,mgraffx/rest-client,ahmeddrira/rest-client,seastar-ss/rest-client,edwincalzada/rest-client,edwincalzada/rest-client,javierfileiv/rest-client,seastar-ss/rest-client,ocsbilisim/rest-client,vegeth1985/rest-client,pavanreddyboppidi/rest-client,rcanz/rest-client,rcanz/rest-client,truvakitap/rest-client,minafaw/rest-client,msezgi/rest-client,npsyche/rest-client,hiro117/rest-client,vit256/rest-client,mgraffx/rest-client,ezbreaks/rest-client,ahmeddrira/rest-client,truvakitap/rest-client,EonHa-Lee/rest-client,hiro117/rest-client,Hasimir/rest-client,wenwei-dev/rest-client,Hasimir/rest-client,sequethin/rest-client,erickgugo/rest-client,rcanz/rest-client,rvkiran/rest-client,ocsbilisim/rest-client,ezbreaks/rest-client,junefun/rest-client,SSYouknowit/rest-client,ahmeddrira/rest-client,npsyche/rest-client,msezgi/rest-client,chinasunysh/rest-client,sequethin/rest-client,xxairwolf/xxknightrider-rest-client,seastar-ss/rest-client
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.wiztools.restclient.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import org.wiztools.restclient.RequestBean; import org.wiztools.restclient.ResponseBean; import org.wiztools.restclient.Util; import org.wiztools.restclient.xml.XMLException; import org.wiztools.restclient.xml.XMLUtil; /** * * @author schandran */ public class RESTFrame extends JFrame { private RESTView view; private AboutDialog aboutDialog; // Requests and responses are generally saved in different dirs private JFileChooser jfc_request = new JFileChooser(); private JFileChooser jfc_response = new JFileChooser(); private final RESTFrame me; public RESTFrame(final String title){ super(title); me = this; init(); } private void createMenu(){ JMenuBar jmb = new JMenuBar(); // File menu JMenu jm_file = new JMenu("File"); jm_file.setMnemonic('f'); JMenuItem jmi_open_req = new JMenuItem("Open Request"); jmi_open_req.setMnemonic('o'); jmi_open_req.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_O, ActionEvent.CTRL_MASK)); jmi_open_req.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { jmi_open_reqAction(); } }); jm_file.add(jmi_open_req); jm_file.addSeparator(); JMenuItem jmi_save_req = new JMenuItem("Save Request"); jmi_save_req.setMnemonic('q'); jmi_save_req.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_S, ActionEvent.CTRL_MASK)); jmi_save_req.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { actionSave(true); } }); jm_file.add(jmi_save_req); JMenuItem jmi_save_res = new JMenuItem("Save Response"); jmi_save_res.setMnemonic('s'); jmi_save_res.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { actionSave(false); } }); jm_file.add(jmi_save_res); jm_file.addSeparator(); JMenuItem jmi_exit = new JMenuItem("Exit"); jmi_exit.setMnemonic('x'); jmi_exit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); jmi_exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { shutdownCall(); } }); jm_file.add(jmi_exit); // Help menu JMenu jm_help = new JMenu("Help"); JMenuItem jmi_about = new JMenuItem("About"); jmi_about.setMnemonic('a'); jmi_about.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { SwingUtilities.invokeLater(new Runnable() { public void run() { aboutDialog.setVisible(true); } }); } }); jm_help.add(jmi_about); // Add menus to menu-bar jmb.add(jm_file); jmb.add(jm_help); this.setJMenuBar(jmb); } private void init(){ // Create AboutDialog aboutDialog = new AboutDialog(this); createMenu(); ImageIcon icon = new ImageIcon(this.getClass().getClassLoader() .getResource("org/wiztools/restclient/WizLogo.png")); setIconImage(icon.getImage()); view = new RESTView(this); setContentPane(view); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event){ shutdownCall(); } }); pack(); setLocationRelativeTo(null); setVisible(true); } private void jmi_open_reqAction(){ int status = jfc_request.showOpenDialog(this); if(status == JFileChooser.APPROVE_OPTION){ File f = jfc_request.getSelectedFile(); Exception e = null; try{ RequestBean request = XMLUtil.getRequestFromXMLFile(f); view.setUIFromRequest(request); } catch(IOException ex){ e = ex; } catch(XMLException ex){ e = ex; } if(e != null){ view.doError(Util.getStackTrace(e)); } } } private File getSaveFile(final boolean isRequest){ JFileChooser jfc = null; if(isRequest){ jfc = jfc_request; } else{ jfc = jfc_response; } int status = jfc.showSaveDialog(this); if(status == JFileChooser.APPROVE_OPTION){ File f = jfc.getSelectedFile(); if(f.exists()){ int yesNo = JOptionPane.showConfirmDialog(me, "File exists. Overwrite?", "File exists", JOptionPane.YES_NO_OPTION); if(yesNo == JOptionPane.YES_OPTION){ return f; } else{ JOptionPane.showMessageDialog(me, "File not saved!", "Not saved", JOptionPane.INFORMATION_MESSAGE); } } else{ // If the file is new one return f; } } return null; } private void actionSave(final boolean isRequest){ SwingUtilities.invokeLater(new Runnable() { public void run() { if(isRequest){ RequestBean request = view.getLastRequest(); if(request == null){ JOptionPane.showMessageDialog(view, "No last request available.", "No Request", JOptionPane.ERROR_MESSAGE); return; } File f = getSaveFile(isRequest); if(f != null){ try{ XMLUtil.writeRequestXML(request, f); } catch(IOException ex){ view.doError(Util.getStackTrace(ex)); } catch(XMLException ex){ view.doError(Util.getStackTrace(ex)); } } } else{ // is response ResponseBean response = view.getLastResponse(); if(response == null){ JOptionPane.showMessageDialog(view, "No last response available.", "No Response", JOptionPane.ERROR_MESSAGE); return; } File f = getSaveFile(isRequest); if(f != null){ try{ XMLUtil.writeResponseXML(response, f); } catch(IOException ex){ view.doError(Util.getStackTrace(ex)); } catch(XMLException ex){ view.doError(Util.getStackTrace(ex)); } } } } }); } private void shutdownCall(){ System.out.println("Exiting..."); System.exit(0); } }
src/main/java/org/wiztools/restclient/ui/RESTFrame.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.wiztools.restclient.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import org.wiztools.restclient.RequestBean; import org.wiztools.restclient.ResponseBean; import org.wiztools.restclient.Util; import org.wiztools.restclient.xml.XMLException; import org.wiztools.restclient.xml.XMLUtil; /** * * @author schandran */ public class RESTFrame extends JFrame { private RESTView view; private AboutDialog aboutDialog; // Requests and responses are generally saved in different dirs private JFileChooser jfc_request = new JFileChooser(); private JFileChooser jfc_response = new JFileChooser(); private final RESTFrame me; public RESTFrame(final String title){ super(title); me = this; init(); } private void createMenu(){ JMenuBar jmb = new JMenuBar(); // File menu JMenu jm_file = new JMenu("File"); jm_file.setMnemonic('f'); JMenuItem jmi_open_req = new JMenuItem("Open Request"); jmi_open_req.setMnemonic('o'); jmi_open_req.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_O, ActionEvent.CTRL_MASK)); jmi_open_req.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { jmi_open_reqAction(); } }); jm_file.add(jmi_open_req); jm_file.addSeparator(); JMenuItem jmi_save_req = new JMenuItem("Save Request"); jmi_save_req.setMnemonic('q'); jmi_save_req.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { actionSave(true); } }); jm_file.add(jmi_save_req); JMenuItem jmi_save_res = new JMenuItem("Save Response"); jmi_save_res.setMnemonic('s'); jmi_save_res.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { actionSave(false); } }); jm_file.add(jmi_save_res); jm_file.addSeparator(); JMenuItem jmi_exit = new JMenuItem("Exit"); jmi_exit.setMnemonic('x'); jmi_exit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); jmi_exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { shutdownCall(); } }); jm_file.add(jmi_exit); // Help menu JMenu jm_help = new JMenu("Help"); JMenuItem jmi_about = new JMenuItem("About"); jmi_about.setMnemonic('a'); jmi_about.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { SwingUtilities.invokeLater(new Runnable() { public void run() { aboutDialog.setVisible(true); } }); } }); jm_help.add(jmi_about); // Add menus to menu-bar jmb.add(jm_file); jmb.add(jm_help); this.setJMenuBar(jmb); } private void init(){ // Create AboutDialog aboutDialog = new AboutDialog(this); createMenu(); ImageIcon icon = new ImageIcon(this.getClass().getClassLoader() .getResource("org/wiztools/restclient/WizLogo.png")); setIconImage(icon.getImage()); view = new RESTView(this); setContentPane(view); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event){ shutdownCall(); } }); pack(); setLocationRelativeTo(null); setVisible(true); } private void jmi_open_reqAction(){ int status = jfc_request.showOpenDialog(this); if(status == JFileChooser.APPROVE_OPTION){ File f = jfc_request.getSelectedFile(); Exception e = null; try{ RequestBean request = XMLUtil.getRequestFromXMLFile(f); view.setUIFromRequest(request); } catch(IOException ex){ e = ex; } catch(XMLException ex){ e = ex; } if(e != null){ view.doError(Util.getStackTrace(e)); } } } private File getSaveFile(final boolean isRequest){ JFileChooser jfc = null; if(isRequest){ jfc = jfc_request; } else{ jfc = jfc_response; } int status = jfc.showSaveDialog(this); if(status == JFileChooser.APPROVE_OPTION){ File f = jfc.getSelectedFile(); if(f.exists()){ int yesNo = JOptionPane.showConfirmDialog(me, "File exists. Overwrite?", "File exists", JOptionPane.YES_NO_OPTION); if(yesNo == JOptionPane.YES_OPTION){ return f; } else{ JOptionPane.showMessageDialog(me, "File not saved!", "Not saved", JOptionPane.INFORMATION_MESSAGE); } } else{ // If the file is new one return f; } } return null; } private void actionSave(final boolean isRequest){ SwingUtilities.invokeLater(new Runnable() { public void run() { if(isRequest){ RequestBean request = view.getLastRequest(); if(request == null){ JOptionPane.showMessageDialog(view, "No last request available.", "No Request", JOptionPane.ERROR_MESSAGE); return; } File f = getSaveFile(isRequest); if(f != null){ try{ XMLUtil.writeRequestXML(request, f); } catch(IOException ex){ view.doError(Util.getStackTrace(ex)); } catch(XMLException ex){ view.doError(Util.getStackTrace(ex)); } } } else{ // is response ResponseBean response = view.getLastResponse(); if(response == null){ JOptionPane.showMessageDialog(view, "No last response available.", "No Response", JOptionPane.ERROR_MESSAGE); return; } File f = getSaveFile(isRequest); if(f != null){ try{ XMLUtil.writeResponseXML(response, f); } catch(IOException ex){ view.doError(Util.getStackTrace(ex)); } catch(XMLException ex){ view.doError(Util.getStackTrace(ex)); } } } } }); } private void shutdownCall(){ System.out.println("Exiting..."); System.exit(0); } }
adding key binding Ctrl+S for save request. git-svn-id: bf7e6665a5fa9ed84da90b6cc1bef00f9ffe166f@57 08545216-953f-0410-99bf-93b34cd2520f
src/main/java/org/wiztools/restclient/ui/RESTFrame.java
adding key binding Ctrl+S for save request.
<ide><path>rc/main/java/org/wiztools/restclient/ui/RESTFrame.java <ide> <ide> JMenuItem jmi_save_req = new JMenuItem("Save Request"); <ide> jmi_save_req.setMnemonic('q'); <add> jmi_save_req.setAccelerator(KeyStroke.getKeyStroke( <add> KeyEvent.VK_S, ActionEvent.CTRL_MASK)); <ide> jmi_save_req.addActionListener(new ActionListener() { <ide> public void actionPerformed(ActionEvent arg0) { <ide> actionSave(true);
Java
apache-2.0
482733a382071a60b4fd725d7884bf050784b836
0
allotria/intellij-community,samthor/intellij-community,supersven/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,samthor/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,holmes/intellij-community,kdwink/intellij-community,allotria/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,retomerz/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,nicolargo/intellij-community,da1z/intellij-community,retomerz/intellij-community,slisson/intellij-community,fitermay/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,signed/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,youdonghai/intellij-community,slisson/intellij-community,kdwink/intellij-community,fitermay/intellij-community,adedayo/intellij-community,caot/intellij-community,asedunov/intellij-community,supersven/intellij-community,fnouama/intellij-community,FHannes/intellij-community,asedunov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,semonte/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,xfournet/intellij-community,ibinti/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,hurricup/intellij-community,vladmm/intellij-community,adedayo/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,blademainer/intellij-community,ibinti/intellij-community,kdwink/intellij-community,hurricup/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,kool79/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,supersven/intellij-community,jagguli/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,izonder/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,robovm/robovm-studio,diorcety/intellij-community,kool79/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,semonte/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,petteyg/intellij-community,hurricup/intellij-community,semonte/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,fnouama/intellij-community,slisson/intellij-community,asedunov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,FHannes/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,vladmm/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,fnouama/intellij-community,dslomov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,da1z/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,signed/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,caot/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,hurricup/intellij-community,fnouama/intellij-community,adedayo/intellij-community,robovm/robovm-studio,FHannes/intellij-community,holmes/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,samthor/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,slisson/intellij-community,fitermay/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,fnouama/intellij-community,supersven/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,vladmm/intellij-community,izonder/intellij-community,slisson/intellij-community,suncycheng/intellij-community,supersven/intellij-community,da1z/intellij-community,FHannes/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,slisson/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,da1z/intellij-community,kdwink/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,FHannes/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ibinti/intellij-community,samthor/intellij-community,signed/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ryano144/intellij-community,semonte/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,supersven/intellij-community,caot/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,signed/intellij-community,vvv1559/intellij-community,supersven/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kool79/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ibinti/intellij-community,amith01994/intellij-community,signed/intellij-community,jagguli/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,signed/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,caot/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,izonder/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,allotria/intellij-community,kdwink/intellij-community,xfournet/intellij-community,apixandru/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,kool79/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,samthor/intellij-community,vladmm/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,clumsy/intellij-community,diorcety/intellij-community,kdwink/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,retomerz/intellij-community,semonte/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,petteyg/intellij-community,hurricup/intellij-community,vladmm/intellij-community,xfournet/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,signed/intellij-community,izonder/intellij-community,holmes/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,signed/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,blademainer/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,hurricup/intellij-community,retomerz/intellij-community,amith01994/intellij-community,jagguli/intellij-community,semonte/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,da1z/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,samthor/intellij-community,FHannes/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,jagguli/intellij-community,kool79/intellij-community,vladmm/intellij-community,adedayo/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,fnouama/intellij-community,slisson/intellij-community,adedayo/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,izonder/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,izonder/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,da1z/intellij-community,kool79/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,supersven/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,caot/intellij-community,signed/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,holmes/intellij-community,kool79/intellij-community,da1z/intellij-community,caot/intellij-community,semonte/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,holmes/intellij-community,clumsy/intellij-community,semonte/intellij-community,signed/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,vladmm/intellij-community,allotria/intellij-community,slisson/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,fnouama/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,samthor/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,signed/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.svn.history; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.RootUrlInfo; import org.jetbrains.idea.svn.SvnFileUrlMapping; import org.jetbrains.idea.svn.SvnVcs; import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; import java.util.Map; public class LatestExistentSearcher { private static final Logger LOG = Logger.getInstance(LatestExistentSearcher.class); private long myStartNumber; private boolean myStartExistsKnown; private final SVNURL myUrl; private final SvnVcs myVcs; private long myEndNumber; public LatestExistentSearcher(final SvnVcs vcs, final SVNURL url) { this(0, -1, false, vcs, url); } public LatestExistentSearcher(final long startNumber, final long endNumber, final boolean startExistsKnown, final SvnVcs vcs, final SVNURL url) { myStartNumber = startNumber; myEndNumber = endNumber; myStartExistsKnown = startExistsKnown; myVcs = vcs; myUrl = url; } public long getDeletionRevision() { if (! detectStartRevision()) return -1; final Ref<Long> latest = new Ref<Long>(myStartNumber); SVNRepository repository = null; try { repository = myVcs.createRepository(myUrl.toString()); final SVNURL repRoot = repository.getRepositoryRoot(true); if (repRoot != null) { if (myEndNumber == -1) { myEndNumber = repository.getLatestRevision(); } final SVNURL existingParent = getExistingParent(myUrl, repository, repRoot.toString().length()); if (existingParent == null) { return myStartNumber; } final String urlRelativeString = myUrl.toString().substring(repRoot.toString().length()); final SVNRevision startRevision = SVNRevision.create(myStartNumber); SvnTarget target = SvnTarget.fromURL(existingParent, startRevision); myVcs.getFactory(target).createHistoryClient() .doLog(target, startRevision, SVNRevision.HEAD, false, true, false, 0, null, createHandler(latest, urlRelativeString)); } } catch (SVNException e) { LOG.info(e); } catch (VcsException e) { LOG.info(e); } finally { if (repository != null) { repository.closeSession(); } } return latest.get().longValue(); } @NotNull private static ISVNLogEntryHandler createHandler(@NotNull final Ref<Long> latest, @NotNull final String urlRelativeString) { return new ISVNLogEntryHandler() { public void handleLogEntry(final SVNLogEntry logEntry) throws SVNException { final Map changedPaths = logEntry.getChangedPaths(); for (Object o : changedPaths.values()) { final SVNLogEntryPath path = (SVNLogEntryPath)o; if ((path.getType() == 'D') && (urlRelativeString.equals(path.getPath()))) { latest.set(logEntry.getRevision()); throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE); } } } }; } public long getLatestExistent() { if (! detectStartRevision()) return myStartNumber; SVNRepository repository = null; long latestOk = myStartNumber; try { repository = myVcs.createRepository(myUrl.toString()); final SVNURL repRoot = repository.getRepositoryRoot(true); if (repRoot != null) { if (myEndNumber == -1) { myEndNumber = repository.getLatestRevision(); } final String urlString = myUrl.toString().substring(repRoot.toString().length()); for (long i = myStartNumber + 1; i < myEndNumber; i++) { final SVNNodeKind kind = repository.checkPath(urlString, i); if (SVNNodeKind.DIR.equals(kind) || SVNNodeKind.FILE.equals(kind)) { latestOk = i; } } } } catch (SVNException e) { // } finally { if (repository != null) { repository.closeSession(); } } return latestOk; } private boolean detectStartRevision() { if (! myStartExistsKnown) { final SvnFileUrlMapping mapping = myVcs.getSvnFileUrlMapping(); final RootUrlInfo rootUrlInfo = mapping.getWcRootForUrl(myUrl.toString()); if (rootUrlInfo == null) return true; final VirtualFile vf = rootUrlInfo.getVirtualFile(); if (vf == null) { return true; } final SVNInfo info = myVcs.getInfo(vf); if ((info == null) || (info.getRevision() == null)) { return false; } myStartNumber = info.getRevision().getNumber(); myStartExistsKnown = true; } return true; } @Nullable private SVNURL getExistingParent(final SVNURL url, final SVNRepository repository, final int repoRootLen) throws SVNException { final String urlString = url.toString().substring(repoRootLen); if (urlString.length() == 0) { // === repository url return url; } final SVNNodeKind kind = repository.checkPath(urlString, myEndNumber); if (SVNNodeKind.DIR.equals(kind) || SVNNodeKind.FILE.equals(kind)) { return url; } final SVNURL parentUrl = url.removePathTail(); if (parentUrl == null) { return null; } return getExistingParent(parentUrl, repository, repoRootLen); } }
plugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.svn.history; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.RootUrlInfo; import org.jetbrains.idea.svn.SvnFileUrlMapping; import org.jetbrains.idea.svn.SvnVcs; import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.SVNRevision; import java.util.Map; public class LatestExistentSearcher { private long myStartNumber; private boolean myStartExistsKnown; private final SVNURL myUrl; private final SvnVcs myVcs; private long myEndNumber; public LatestExistentSearcher(final SvnVcs vcs, final SVNURL url) { this(0, -1, false, vcs, url); } public LatestExistentSearcher(final long startNumber, final long endNumber, final boolean startExistsKnown, final SvnVcs vcs, final SVNURL url) { myStartNumber = startNumber; myEndNumber = endNumber; myStartExistsKnown = startExistsKnown; myVcs = vcs; myUrl = url; } public long getDeletionRevision() { if (! detectStartRevision()) return -1; final Ref<Long> latest = new Ref<Long>(myStartNumber); SVNRepository repository = null; try { repository = myVcs.createRepository(myUrl.toString()); final SVNURL repRoot = repository.getRepositoryRoot(true); if (repRoot != null) { if (myEndNumber == -1) { myEndNumber = repository.getLatestRevision(); } final SVNURL existingParent = getExistingParent(myUrl, repository, repRoot.toString().length()); if (existingParent == null) { return myStartNumber; } final String urlRelativeString = myUrl.toString().substring(repRoot.toString().length()); final SVNRevision startRevision = SVNRevision.create(myStartNumber); myVcs.createLogClient().doLog(existingParent, new String[]{""}, startRevision, startRevision, SVNRevision.HEAD, false, true, 0, new ISVNLogEntryHandler() { public void handleLogEntry(final SVNLogEntry logEntry) throws SVNException { final Map changedPaths = logEntry.getChangedPaths(); for (Object o : changedPaths.values()) { final SVNLogEntryPath path = (SVNLogEntryPath) o; if ((path.getType() == 'D') && (urlRelativeString.equals(path.getPath()))) { latest.set(logEntry.getRevision()); throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE); } } } }); } } catch (SVNException e) { // } finally { if (repository != null) { repository.closeSession(); } } return latest.get().longValue(); } public long getLatestExistent() { if (! detectStartRevision()) return myStartNumber; SVNRepository repository = null; long latestOk = myStartNumber; try { repository = myVcs.createRepository(myUrl.toString()); final SVNURL repRoot = repository.getRepositoryRoot(true); if (repRoot != null) { if (myEndNumber == -1) { myEndNumber = repository.getLatestRevision(); } final String urlString = myUrl.toString().substring(repRoot.toString().length()); for (long i = myStartNumber + 1; i < myEndNumber; i++) { final SVNNodeKind kind = repository.checkPath(urlString, i); if (SVNNodeKind.DIR.equals(kind) || SVNNodeKind.FILE.equals(kind)) { latestOk = i; } } } } catch (SVNException e) { // } finally { if (repository != null) { repository.closeSession(); } } return latestOk; } private boolean detectStartRevision() { if (! myStartExistsKnown) { final SvnFileUrlMapping mapping = myVcs.getSvnFileUrlMapping(); final RootUrlInfo rootUrlInfo = mapping.getWcRootForUrl(myUrl.toString()); if (rootUrlInfo == null) return true; final VirtualFile vf = rootUrlInfo.getVirtualFile(); if (vf == null) { return true; } final SVNInfo info = myVcs.getInfo(vf); if ((info == null) || (info.getRevision() == null)) { return false; } myStartNumber = info.getRevision().getNumber(); myStartExistsKnown = true; } return true; } @Nullable private SVNURL getExistingParent(final SVNURL url, final SVNRepository repository, final int repoRootLen) throws SVNException { final String urlString = url.toString().substring(repoRootLen); if (urlString.length() == 0) { // === repository url return url; } final SVNNodeKind kind = repository.checkPath(urlString, myEndNumber); if (SVNNodeKind.DIR.equals(kind) || SVNNodeKind.FILE.equals(kind)) { return url; } final SVNURL parentUrl = url.removePathTail(); if (parentUrl == null) { return null; } return getExistingParent(parentUrl, repository, repoRootLen); } }
svn: Refactored LatestExistentSearcher - use common client factory model (instead of direct SVNLogClient usage)
plugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java
svn: Refactored LatestExistentSearcher - use common client factory model (instead of direct SVNLogClient usage)
<ide><path>lugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java <ide> */ <ide> package org.jetbrains.idea.svn.history; <ide> <add>import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.util.Ref; <add>import com.intellij.openapi.vcs.VcsException; <ide> import com.intellij.openapi.vfs.VirtualFile; <add>import org.jetbrains.annotations.NotNull; <ide> import org.jetbrains.annotations.Nullable; <ide> import org.jetbrains.idea.svn.RootUrlInfo; <ide> import org.jetbrains.idea.svn.SvnFileUrlMapping; <ide> import org.tmatesoft.svn.core.io.SVNRepository; <ide> import org.tmatesoft.svn.core.wc.SVNInfo; <ide> import org.tmatesoft.svn.core.wc.SVNRevision; <add>import org.tmatesoft.svn.core.wc2.SvnTarget; <ide> <ide> import java.util.Map; <ide> <ide> public class LatestExistentSearcher { <add> <add> private static final Logger LOG = Logger.getInstance(LatestExistentSearcher.class); <add> <ide> private long myStartNumber; <ide> private boolean myStartExistsKnown; <ide> private final SVNURL myUrl; <ide> <ide> final String urlRelativeString = myUrl.toString().substring(repRoot.toString().length()); <ide> final SVNRevision startRevision = SVNRevision.create(myStartNumber); <del> myVcs.createLogClient().doLog(existingParent, new String[]{""}, startRevision, startRevision, SVNRevision.HEAD, false, true, 0, <del> new ISVNLogEntryHandler() { <del> public void handleLogEntry(final SVNLogEntry logEntry) throws SVNException { <del> final Map changedPaths = logEntry.getChangedPaths(); <del> for (Object o : changedPaths.values()) { <del> final SVNLogEntryPath path = (SVNLogEntryPath) o; <del> if ((path.getType() == 'D') && (urlRelativeString.equals(path.getPath()))) { <del> latest.set(logEntry.getRevision()); <del> throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE); <del> } <del> } <del> } <del> }); <add> SvnTarget target = SvnTarget.fromURL(existingParent, startRevision); <add> myVcs.getFactory(target).createHistoryClient() <add> .doLog(target, startRevision, SVNRevision.HEAD, false, true, false, 0, null, createHandler(latest, urlRelativeString)); <ide> } <ide> } <ide> catch (SVNException e) { <del> // <del> } finally { <add> LOG.info(e); <add> } <add> catch (VcsException e) { <add> LOG.info(e); <add> } <add> finally { <ide> if (repository != null) { <ide> repository.closeSession(); <ide> } <ide> } <ide> <ide> return latest.get().longValue(); <add> } <add> <add> @NotNull <add> private static ISVNLogEntryHandler createHandler(@NotNull final Ref<Long> latest, @NotNull final String urlRelativeString) { <add> return new ISVNLogEntryHandler() { <add> public void handleLogEntry(final SVNLogEntry logEntry) throws SVNException { <add> final Map changedPaths = logEntry.getChangedPaths(); <add> for (Object o : changedPaths.values()) { <add> final SVNLogEntryPath path = (SVNLogEntryPath)o; <add> if ((path.getType() == 'D') && (urlRelativeString.equals(path.getPath()))) { <add> latest.set(logEntry.getRevision()); <add> throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE); <add> } <add> } <add> } <add> }; <ide> } <ide> <ide> public long getLatestExistent() {
Java
apache-2.0
6b7be7e0868756303785b106461f8ff33dbb888e
0
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
/* * ============================================================================ * (c) Copyright 2004 Nokia * This material, including documentation and any related computer programs, * is protected by copyright controlled by Nokia and its licensors. * All rights are reserved. * * These materials have been contributed to the Open Services Gateway * Initiative (OSGi)as "MEMBER LICENSED MATERIALS" as defined in, and subject * to the terms of, the OSGi Member Agreement specifically including, but not * limited to, the license rights and warranty disclaimers as set forth in * Sections 3.2 and 12.1 thereof, and the applicable Statement of Work. * All company, brand and product names contained within this document may be * trademarks that are the sole property of the respective owners. * The above notice must be included on all copies of this document. * ============================================================================ */ package org.osgi.impl.service.deploymentadmin; import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.eclipse.osgi.service.resolver.VersionRange; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; import org.osgi.service.deploymentadmin.BundleInfo; import org.osgi.service.deploymentadmin.DeploymentAdminPermission; import org.osgi.service.deploymentadmin.DeploymentException; import org.osgi.service.deploymentadmin.DeploymentPackage; import org.osgi.service.deploymentadmin.spi.ResourceProcessor; public class DeploymentPackageImpl implements DeploymentPackage, Serializable { private transient DeploymentPackageCtx dpCtx; private DeploymentPackageResourceBundle dprb; private CaseInsensitiveMap mainSection; private Vector bundleEntries = new Vector(); private Vector resourceEntries = new Vector(); // List of String[]s private List certChains = new Vector(); private Boolean stale = Boolean.FALSE; private DeploymentPackageImpl() { } DeploymentPackageImpl(DeploymentPackageCtx dpCtx, Manifest manifest, List certChains) throws DeploymentException { if (null == dpCtx) throw new IllegalArgumentException("Internal error"); this.dpCtx = dpCtx; if (null == manifest) mainSection = new CaseInsensitiveMap(null, this); else mainSection = new CaseInsensitiveMap(manifest.getMainAttributes(), this); processNameSections(manifest); if (null != certChains) this.certChains = certChains; } /* * Creates an empty DP */ static DeploymentPackageImpl createEmpty(DeploymentPackageCtx dpCtx) { if (null == dpCtx) throw new IllegalArgumentException("Internal error"); DeploymentPackageImpl dp = new DeploymentPackageImpl(); dp.dpCtx = dpCtx; dp.mainSection = new CaseInsensitiveMap(null, dp); dp.mainSection.put(DAConstants.DP_NAME, ""); dp.mainSection.put(DAConstants.DP_VERSION, "0.0.0"); dp.stale = new Boolean(true); return dp; } synchronized void update(DeploymentPackageImpl dp) { this.dprb = dp.dprb; this.mainSection = dp.mainSection; this.bundleEntries = dp.bundleEntries; this.resourceEntries = dp.resourceEntries; this.certChains = dp.certChains; } boolean isEmpty() { return getName().equals(""); } public boolean equals(Object obj) { if (null == obj) return false; if (this == obj) return true; if (!(obj instanceof DeploymentPackage)) return false; DeploymentPackage other = (DeploymentPackage) obj; return getName().equals(other.getName()) && getVersion().equals(other.getVersion()); } boolean equalsIgnoreVersion(DeploymentPackage other) { if (null == other) return false; return getName().equals(other.getName()); } public int hashCode() { return (getName() + getVersion()).hashCode(); } public String toString() { return "[Deployment Package: " + getName() + " " + getVersion() + "]"; } private void processNameSections(Manifest manifest) throws DeploymentException { if (null == manifest) return; Map entries = manifest.getEntries(); for (Iterator iter = entries.keySet().iterator(); iter.hasNext();) { String resPath = (String) iter.next(); Attributes attrs = (Attributes) entries.get(resPath); String bSn = attrs.getValue(DAConstants.BUNDLE_SYMBOLIC_NAME); String bVer = attrs.getValue(DAConstants.BUNDLE_VERSION); String missingStr = attrs.getValue(DAConstants.MISSING); boolean missing = (missingStr != null && "true".equalsIgnoreCase(missingStr.trim())); boolean isBundle = null != bSn && null != bVer; if (isBundle) { // bundle BundleEntry be = new BundleEntry(resPath, bSn, bVer, missing, attrs, this); bundleEntries.add(be); } else { // resource resourceEntries.add(new ResourceEntry(resPath, attrs, this)); } } } public synchronized List getBundleEntries() { return bundleEntries; } boolean contains(BundleEntry be) { return bundleEntries.contains(be); } void add(BundleEntry be) { bundleEntries.add(be); } void remove(BundleEntry be) { bundleEntries.remove(be); } BundleEntry getBundleEntryByBundleId(long id) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getBundleId() == id) return be; } return null; } BundleEntry getBundleEntryByPid(String pid) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (null == be.getPid()) continue; if (be.getPid().equals(pid)) return be; } return null; } BundleEntry getBundleEntryByName(String name) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getResName().equals(name)) return be; } return null; } BundleEntry getBundleEntry(String symbName, Version version) throws DeploymentException { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getSymbName().equals(symbName) && be.getVersion().equals(version)) return be; } return null; } BundleEntry getBundleEntry(String symbName) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getSymbName().equals(symbName)) return be; } return null; } VersionRange getFixPackRange() { String s = (String) mainSection.get(DAConstants.DP_FIXPACK); if (null == s) return null; return new VersionRange(s); } ResourceEntry getResourceEntryByName(String name) { for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry entry = (ResourceEntry) iter.next(); if (entry.getResName().equals(name)) return entry; } return null; } public synchronized List getCertChains() { return certChains; } /** * @see DeploymentPackage#getBundleInfos() */ public synchronized BundleInfo[] getBundleInfos() { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.METADATA); BundleInfo[] ret = new BundleInfo[bundleEntries.size()]; int i = 0; for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); ret[i] = new BundleInfoImpl(be.getSymbName(), be.getVersion()); ++i; } return ret; } private void checkStale() { if (isStale()) throw new IllegalStateException("Deployment package is stale"); } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getResources() */ public synchronized String[] getResources() { checkStale(); String[]ret = new String[resourceEntries.size() + bundleEntries.size()]; int i = 0; for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); ret[i] = be.getResName(); ++i; } for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry re = (ResourceEntry) iter.next(); ret[i] = re.getResName(); ++i; } return ret; } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getResourceHeader(java.lang.String, java.lang.String) */ public synchronized String getResourceHeader(String name, String header) { checkStale(); for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry re = (ResourceEntry) iter.next(); if (re.getResName().equals(name)) return re.getValue(header); } for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getResName().equals(name)) return (String) be.getAttrs().get(header); } return null; } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getHeader(java.lang.String) */ public synchronized String getHeader(String name) { checkStale(); return (String) mainSection.get(name); } public synchronized boolean isStale() { return stale.booleanValue(); } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getName() */ public String getName() { return (String) mainSection.get(DAConstants.DP_NAME); } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getVersion() */ public synchronized Version getVersion() { String s = (String) mainSection.get(DAConstants.DP_VERSION); if (null == s) return null; return new Version(s); } /** * @see DeploymentPackage#getBundle(String) */ public synchronized Bundle getBundle(final String symbName) { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.METADATA); Bundle[] bs = dpCtx.getBundleContext().getBundles(); for (int i = 0; i < bs.length; i++) { final Bundle b = bs[i]; String location = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return b.getLocation(); }}); if (null == location) continue; if (location.equals(DeploymentAdminImpl.location(symbName, null))) return b; } return null; } /** * @param arg0 * @return * @see org.osgi.service.deploymentadmin.DeploymentPackage#getResourceProcessor(java.lang.String) */ public synchronized ServiceReference getResourceProcessor(String resName) { checkStale(); for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry re = (ResourceEntry) iter.next(); if (re.getResName().equals(resName)) { try { ServiceReference[] refs = dpCtx.getBundleContext().getServiceReferences( ResourceProcessor.class.getName(), "(" + Constants.SERVICE_PID + "=" + re.getPid() + ")"); if (null != refs && refs.length != 0) return refs[0]; } catch (InvalidSyntaxException e) { throw new RuntimeException("Internal error"); } } } return null; } /** * @throws DeploymentException * @see org.osgi.service.deploymentadmin.DeploymentPackage#uninstall() */ public void uninstall() throws DeploymentException { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.UNINSTALL); dpCtx.uninstall(this); setStale(); } /** * @return * @throws DeploymentException * @see org.osgi.service.deploymentadmin.DeploymentPackage#uninstallForced() */ public boolean uninstallForced() throws DeploymentException { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.UNINSTALL_FORCED); setStale(); return dpCtx.uninstallForced(this); } void setDeploymentPackageCtx(DeploymentPackageCtx dpCtx) { this.dpCtx = dpCtx; } void setVersion(Version version) { mainSection.put(DAConstants.DP_VERSION, version.toString()); } synchronized void setStale() { stale = Boolean.TRUE; } public synchronized List getResourceEntries() { return resourceEntries; } void remove(ResourceEntry re) { resourceEntries.remove(re); } boolean contains(ResourceEntry re) { return resourceEntries.contains(re); } void setResourceBundle(DeploymentPackageResourceBundle dprb) { this.dprb = dprb; } DeploymentPackageResourceBundle getResourceBundle() { return dprb; } public synchronized CaseInsensitiveMap getMainSection() { return mainSection; } DeploymentPackageCtx getDpCtx() { return dpCtx; } }
org.osgi.impl.service.deploymentadmin/src/org/osgi/impl/service/deploymentadmin/DeploymentPackageImpl.java
/* * ============================================================================ * (c) Copyright 2004 Nokia * This material, including documentation and any related computer programs, * is protected by copyright controlled by Nokia and its licensors. * All rights are reserved. * * These materials have been contributed to the Open Services Gateway * Initiative (OSGi)as "MEMBER LICENSED MATERIALS" as defined in, and subject * to the terms of, the OSGi Member Agreement specifically including, but not * limited to, the license rights and warranty disclaimers as set forth in * Sections 3.2 and 12.1 thereof, and the applicable Statement of Work. * All company, brand and product names contained within this document may be * trademarks that are the sole property of the respective owners. * The above notice must be included on all copies of this document. * ============================================================================ */ package org.osgi.impl.service.deploymentadmin; import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.eclipse.osgi.service.resolver.VersionRange; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.Version; import org.osgi.service.deploymentadmin.BundleInfo; import org.osgi.service.deploymentadmin.DeploymentAdminPermission; import org.osgi.service.deploymentadmin.DeploymentException; import org.osgi.service.deploymentadmin.DeploymentPackage; import org.osgi.service.deploymentadmin.spi.ResourceProcessor; public class DeploymentPackageImpl implements DeploymentPackage, Serializable { private transient DeploymentPackageCtx dpCtx; private DeploymentPackageResourceBundle dprb; private CaseInsensitiveMap mainSection; private Vector bundleEntries = new Vector(); private Vector resourceEntries = new Vector(); // List of String[]s private List certChains = new Vector(); private Boolean stale = Boolean.FALSE; private DeploymentPackageImpl() { } DeploymentPackageImpl(DeploymentPackageCtx dpCtx, Manifest manifest, List certChains) throws DeploymentException { if (null == dpCtx) throw new IllegalArgumentException("Internal error"); this.dpCtx = dpCtx; if (null == manifest) mainSection = new CaseInsensitiveMap(null, this); else mainSection = new CaseInsensitiveMap(manifest.getMainAttributes(), this); processNameSections(manifest); if (null != certChains) this.certChains = certChains; } /* * Creates an empty DP */ static DeploymentPackageImpl createEmpty(DeploymentPackageCtx dpCtx) { if (null == dpCtx) throw new IllegalArgumentException("Internal error"); DeploymentPackageImpl dp = new DeploymentPackageImpl(); dp.dpCtx = dpCtx; dp.mainSection = new CaseInsensitiveMap(null, dp); dp.mainSection.put(DAConstants.DP_NAME, ""); dp.mainSection.put(DAConstants.DP_VERSION, "0.0.0"); return dp; } synchronized void update(DeploymentPackageImpl dp) { this.dprb = dp.dprb; this.mainSection = dp.mainSection; this.bundleEntries = dp.bundleEntries; this.resourceEntries = dp.resourceEntries; this.certChains = dp.certChains; } boolean isEmpty() { return getName().equals(""); } public boolean equals(Object obj) { if (null == obj) return false; if (this == obj) return true; if (!(obj instanceof DeploymentPackage)) return false; DeploymentPackage other = (DeploymentPackage) obj; return getName().equals(other.getName()) && getVersion().equals(other.getVersion()); } boolean equalsIgnoreVersion(DeploymentPackage other) { if (null == other) return false; return getName().equals(other.getName()); } public int hashCode() { return (getName() + getVersion()).hashCode(); } public String toString() { return "[Deployment Package: " + getName() + " " + getVersion() + "]"; } private void processNameSections(Manifest manifest) throws DeploymentException { if (null == manifest) return; Map entries = manifest.getEntries(); for (Iterator iter = entries.keySet().iterator(); iter.hasNext();) { String resPath = (String) iter.next(); Attributes attrs = (Attributes) entries.get(resPath); String bSn = attrs.getValue(DAConstants.BUNDLE_SYMBOLIC_NAME); String bVer = attrs.getValue(DAConstants.BUNDLE_VERSION); String missingStr = attrs.getValue(DAConstants.MISSING); boolean missing = (missingStr != null && "true".equalsIgnoreCase(missingStr.trim())); boolean isBundle = null != bSn && null != bVer; if (isBundle) { // bundle BundleEntry be = new BundleEntry(resPath, bSn, bVer, missing, attrs, this); bundleEntries.add(be); } else { // resource resourceEntries.add(new ResourceEntry(resPath, attrs, this)); } } } public synchronized List getBundleEntries() { return bundleEntries; } boolean contains(BundleEntry be) { return bundleEntries.contains(be); } void add(BundleEntry be) { bundleEntries.add(be); } void remove(BundleEntry be) { bundleEntries.remove(be); } BundleEntry getBundleEntryByBundleId(long id) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getBundleId() == id) return be; } return null; } BundleEntry getBundleEntryByPid(String pid) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (null == be.getPid()) continue; if (be.getPid().equals(pid)) return be; } return null; } BundleEntry getBundleEntryByName(String name) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getResName().equals(name)) return be; } return null; } BundleEntry getBundleEntry(String symbName, Version version) throws DeploymentException { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getSymbName().equals(symbName) && be.getVersion().equals(version)) return be; } return null; } BundleEntry getBundleEntry(String symbName) { for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getSymbName().equals(symbName)) return be; } return null; } VersionRange getFixPackRange() { String s = (String) mainSection.get(DAConstants.DP_FIXPACK); if (null == s) return null; return new VersionRange(s); } ResourceEntry getResourceEntryByName(String name) { for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry entry = (ResourceEntry) iter.next(); if (entry.getResName().equals(name)) return entry; } return null; } public synchronized List getCertChains() { return certChains; } /** * @see DeploymentPackage#getBundleInfos() */ public synchronized BundleInfo[] getBundleInfos() { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.METADATA); BundleInfo[] ret = new BundleInfo[bundleEntries.size()]; int i = 0; for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); ret[i] = new BundleInfoImpl(be.getSymbName(), be.getVersion()); ++i; } return ret; } private void checkStale() { if (isStale()) throw new IllegalStateException("Deployment package is stale"); } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getResources() */ public synchronized String[] getResources() { checkStale(); String[]ret = new String[resourceEntries.size() + bundleEntries.size()]; int i = 0; for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); ret[i] = be.getResName(); ++i; } for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry re = (ResourceEntry) iter.next(); ret[i] = re.getResName(); ++i; } return ret; } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getResourceHeader(java.lang.String, java.lang.String) */ public synchronized String getResourceHeader(String name, String header) { checkStale(); for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry re = (ResourceEntry) iter.next(); if (re.getResName().equals(name)) return re.getValue(header); } for (Iterator iter = bundleEntries.iterator(); iter.hasNext();) { BundleEntry be = (BundleEntry) iter.next(); if (be.getResName().equals(name)) return (String) be.getAttrs().get(header); } return null; } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getHeader(java.lang.String) */ public synchronized String getHeader(String name) { checkStale(); return (String) mainSection.get(name); } public synchronized boolean isStale() { return stale.booleanValue(); } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getName() */ public String getName() { return (String) mainSection.get(DAConstants.DP_NAME); } /** * @see org.osgi.service.deploymentadmin.DeploymentPackage#getVersion() */ public synchronized Version getVersion() { String s = (String) mainSection.get(DAConstants.DP_VERSION); if (null == s) return null; return new Version(s); } /** * @see DeploymentPackage#getBundle(String) */ public synchronized Bundle getBundle(final String symbName) { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.METADATA); Bundle[] bs = dpCtx.getBundleContext().getBundles(); for (int i = 0; i < bs.length; i++) { final Bundle b = bs[i]; String location = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return b.getLocation(); }}); if (null == location) continue; if (location.equals(DeploymentAdminImpl.location(symbName, null))) return b; } return null; } /** * @param arg0 * @return * @see org.osgi.service.deploymentadmin.DeploymentPackage#getResourceProcessor(java.lang.String) */ public synchronized ServiceReference getResourceProcessor(String resName) { checkStale(); for (Iterator iter = resourceEntries.iterator(); iter.hasNext();) { ResourceEntry re = (ResourceEntry) iter.next(); if (re.getResName().equals(resName)) { try { ServiceReference[] refs = dpCtx.getBundleContext().getServiceReferences( ResourceProcessor.class.getName(), "(" + Constants.SERVICE_PID + "=" + re.getPid() + ")"); if (null != refs && refs.length != 0) return refs[0]; } catch (InvalidSyntaxException e) { throw new RuntimeException("Internal error"); } } } return null; } /** * @throws DeploymentException * @see org.osgi.service.deploymentadmin.DeploymentPackage#uninstall() */ public void uninstall() throws DeploymentException { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.UNINSTALL); dpCtx.uninstall(this); setStale(); } /** * @return * @throws DeploymentException * @see org.osgi.service.deploymentadmin.DeploymentPackage#uninstallForced() */ public boolean uninstallForced() throws DeploymentException { checkStale(); dpCtx.checkPermission(this, DeploymentAdminPermission.UNINSTALL_FORCED); setStale(); return dpCtx.uninstallForced(this); } void setDeploymentPackageCtx(DeploymentPackageCtx dpCtx) { this.dpCtx = dpCtx; } void setVersion(Version version) { mainSection.put(DAConstants.DP_VERSION, version.toString()); } synchronized void setStale() { stale = Boolean.TRUE; } public synchronized List getResourceEntries() { return resourceEntries; } void remove(ResourceEntry re) { resourceEntries.remove(re); } boolean contains(ResourceEntry re) { return resourceEntries.contains(re); } void setResourceBundle(DeploymentPackageResourceBundle dprb) { this.dprb = dprb; } DeploymentPackageResourceBundle getResourceBundle() { return dprb; } public synchronized CaseInsensitiveMap getMainSection() { return mainSection; } DeploymentPackageCtx getDpCtx() { return dpCtx; } }
Empty dp is stale
org.osgi.impl.service.deploymentadmin/src/org/osgi/impl/service/deploymentadmin/DeploymentPackageImpl.java
Empty dp is stale
<ide><path>rg.osgi.impl.service.deploymentadmin/src/org/osgi/impl/service/deploymentadmin/DeploymentPackageImpl.java <ide> dp.mainSection = new CaseInsensitiveMap(null, dp); <ide> dp.mainSection.put(DAConstants.DP_NAME, ""); <ide> dp.mainSection.put(DAConstants.DP_VERSION, "0.0.0"); <add> dp.stale = new Boolean(true); <ide> <ide> return dp; <ide> }
Java
apache-2.0
00e0c072cfab5bcb6cde1c6eeae1979dc1bc6e50
0
jmrozanec/cron-utils,meincs/cron-utils
/* * Copyright 2015 jmrozanec * 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.cronutils; import com.cronutils.model.Cron; import com.cronutils.model.CronType; import com.cronutils.model.definition.CronDefinitionBuilder; import com.cronutils.parser.CronParser; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.text.ParseException; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertTrue; /** * Provide an example on how convert a cron expression to ISO8601 */ @Ignore public class Issue367Test { private CronParser parser; @Before public void setUp() { parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)); } @Test public void testCase1() throws ParseException { // set base data final ZoneId zone = ZoneId.of("Europe/Berlin"); final Date date = new Date(); final String cronExpression = "0 0 1 1 1 ?"; // build cron Cron cron = parser.parse(cronExpression); // convert to quartz final org.quartz.CronExpression quartzExpression = new org.quartz.CronExpression(cron.asString()); quartzExpression.setTimeZone(TimeZone.getTimeZone(zone)); // get date and convert to ISO8601 final Date quartzNextTime = quartzExpression.getNextValidTimeAfter(Date.from(date.toInstant()));// 2016-12-24T00:00:00Z ZonedDateTime d = ZonedDateTime.ofInstant(quartzNextTime.toInstant(), zone); String res = DateTimeFormatter.ISO_DATE_TIME.format(d); assertTrue(res.equals("2021-01-01T01:00:00+01:00[Europe/Berlin]")); } }
src/test/java/com/cronutils/Issue367Test.java
/* * Copyright 2015 jmrozanec * 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.cronutils; import com.cronutils.model.Cron; import com.cronutils.model.CronType; import com.cronutils.model.definition.CronDefinitionBuilder; import com.cronutils.parser.CronParser; import org.junit.Before; import org.junit.Test; import java.text.ParseException; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertTrue; /** * Provide an example on how convert a cron expression to ISO8601 */ public class Issue367Test { private CronParser parser; @Before public void setUp() { parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)); } @Test public void testCase1() throws ParseException { // set base data final ZoneId zone = ZoneId.of("Europe/Berlin"); final Date date = new Date(); final String cronExpression = "0 0 1 1 1 ?"; // build cron Cron cron = parser.parse(cronExpression); // convert to quartz final org.quartz.CronExpression quartzExpression = new org.quartz.CronExpression(cron.asString()); quartzExpression.setTimeZone(TimeZone.getTimeZone(zone)); // get date and convert to ISO8601 final Date quartzNextTime = quartzExpression.getNextValidTimeAfter(Date.from(date.toInstant()));// 2016-12-24T00:00:00Z ZonedDateTime d = ZonedDateTime.ofInstant(quartzNextTime.toInstant(), zone); String res = DateTimeFormatter.ISO_DATE_TIME.format(d); assertTrue(res.equals("2021-01-01T01:00:00+01:00[Europe/Berlin]")); } }
Ignore failing test.
src/test/java/com/cronutils/Issue367Test.java
Ignore failing test.
<ide><path>rc/test/java/com/cronutils/Issue367Test.java <ide> import com.cronutils.model.definition.CronDefinitionBuilder; <ide> import com.cronutils.parser.CronParser; <ide> import org.junit.Before; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> import java.text.ParseException; <ide> /** <ide> * Provide an example on how convert a cron expression to ISO8601 <ide> */ <add>@Ignore <ide> public class Issue367Test { <ide> <ide> private CronParser parser;
JavaScript
mit
error: pathspec 'src/utilities/byProgram.js' did not match any file(s) known to git
2c1d4ccdf91661d0841189f1b7ced150f728d667
1
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
const thisStoreUsesPrograms = (settings, database) => { const thisStoresTags = settings.get('ThisStoreTags'); const programs = database.objects('MasterList').filtered('isProgram = $0', true); const hasAProgram = programs.find(program => program.canUseProgram(thisStoresTags)); return !!hasAProgram; }; const getAllPrograms = (settings, database) => { const thisStoresTags = settings.get('ThisStoreTags'); const programs = database.objects('MasterList').filtered('isProgram = $0', true); if (!programs) return null; return programs.filter(program => program.canUseProgram(thisStoresTags)); }; export { thisStoreUsesPrograms, getAllPrograms };
src/utilities/byProgram.js
Add helper byProgram helper methods
src/utilities/byProgram.js
Add helper byProgram helper methods
<ide><path>rc/utilities/byProgram.js <add>const thisStoreUsesPrograms = (settings, database) => { <add> const thisStoresTags = settings.get('ThisStoreTags'); <add> const programs = database.objects('MasterList').filtered('isProgram = $0', true); <add> const hasAProgram = programs.find(program => program.canUseProgram(thisStoresTags)); <add> return !!hasAProgram; <add>}; <add> <add>const getAllPrograms = (settings, database) => { <add> const thisStoresTags = settings.get('ThisStoreTags'); <add> const programs = database.objects('MasterList').filtered('isProgram = $0', true); <add> if (!programs) return null; <add> return programs.filter(program => program.canUseProgram(thisStoresTags)); <add>}; <add> <add>export { thisStoreUsesPrograms, getAllPrograms };
Java
lgpl-2.1
eb338fb4e361b2e6a41e6d09ec411993b2f4fffb
0
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.intermine.web.config; /* * Copyright (C) 2002-2005 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Iterator; import java.util.Set; import java.util.Collections; import org.apache.commons.collections.set.ListOrderedSet; import org.apache.commons.lang.ObjectUtils; /** * Configuration object for displaying a class * * @author Andrew Varley */ public class Type { // if fieldName is null it's ignored and the webapp will use the default renderer private String fieldName; private String className; private ListOrderedSet fieldConfigs = new ListOrderedSet(); private ListOrderedSet longDisplayers = new ListOrderedSet(); private Displayer tableDisplayer; /** * Set the fully-qualified class name for this Type * * @param className the name of the Type */ public void setClassName(String className) { this.className = className; } /** * Get the class name * * @return the name */ public String getClassName() { return this.className; } /** * Add a FieldConfig for this Type * * @param df the FieldConfig to add */ public void addFieldConfig(FieldConfig df) { fieldConfigs.add(df); } /** * Get the List of FieldConfig objects * * @return the List of FieldConfig objects */ public Set getFieldConfigs() { return Collections.unmodifiableSet(this.fieldConfigs); } /** * Add a long displayer for this Type * * @param disp the Displayer to add */ public void addLongDisplayer(Displayer disp) { longDisplayers.add(disp); } /** * Set the table displayer for this Type * * @param disp the Displayer */ public void setTableDisplayer(Displayer disp) { tableDisplayer = disp; } /** * Get the List of long Displayers * * @return the List of long Displayers */ public Set getLongDisplayers() { return Collections.unmodifiableSet(this.longDisplayers); } /** * Get the table Displayer * * @return the table Displayer */ public Displayer getTableDisplayer() { return tableDisplayer; } /** * @see Object#equals * * @param obj the Object to compare with * @return true if this is equal to obj */ public boolean equals(Object obj) { if (!(obj instanceof Type)) { return false; } Type typeObj = (Type) obj; return fieldConfigs.equals(typeObj.fieldConfigs) && longDisplayers.equals(typeObj.longDisplayers) && ObjectUtils.equals(tableDisplayer, typeObj.tableDisplayer); } /** * @see Object#hashCode * * @return the hashCode for this Type object */ public int hashCode() { int hash = fieldConfigs.hashCode() + 3 * longDisplayers.hashCode(); if (tableDisplayer != null) { hash += 5 * tableDisplayer.hashCode(); } return hash; } /** * Return an XML String of this Type object * * @return a String version of this WebConfig object */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<class className=\"" + className + "\""); if (fieldName != null) { sb.append(" fieldName=\"" + fieldName + "\""); } sb.append(">"); sb.append("<fieldconfigs>"); Iterator iter = fieldConfigs.iterator(); while (iter.hasNext()) { sb.append(iter.next().toString()); } sb.append("</fieldconfigs>"); if (tableDisplayer != null) { sb.append(tableDisplayer.toString("tabledisplayer")); } sb.append("<longdisplayers>"); iter = longDisplayers.iterator(); while (iter.hasNext()) { sb.append(iter.next().toString()); } sb.append("</longdisplayers>"); sb.append("</class>"); return sb.toString(); } }
intermine/web/main/src/org/intermine/web/config/Type.java
package org.intermine.web.config; /* * Copyright (C) 2002-2005 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Iterator; import java.util.Set; import java.util.Collections; import org.apache.commons.collections.set.ListOrderedSet; /** * Configuration object for displaying a class * * @author Andrew Varley */ public class Type { // if fieldName is null it's ignored and the webapp will use the default renderer private String fieldName; private String className; private ListOrderedSet fieldConfigs = new ListOrderedSet(); private ListOrderedSet longDisplayers = new ListOrderedSet(); private Displayer tableDisplayer; /** * Set the fully-qualified class name for this Type * * @param className the name of the Type */ public void setClassName(String className) { this.className = className; } /** * Get the class name * * @return the name */ public String getClassName() { return this.className; } /** * Add a FieldConfig for this Type * * @param df the FieldConfig to add */ public void addFieldConfig(FieldConfig df) { fieldConfigs.add(df); } /** * Get the List of FieldConfig objects * * @return the List of FieldConfig objects */ public Set getFieldConfigs() { return Collections.unmodifiableSet(this.fieldConfigs); } /** * Add a long displayer for this Type * * @param disp the Displayer to add */ public void addLongDisplayer(Displayer disp) { longDisplayers.add(disp); } /** * Set the table displayer for this Type * * @param disp the Displayer */ public void setTableDisplayer(Displayer disp) { tableDisplayer = disp; } /** * Get the List of long Displayers * * @return the List of long Displayers */ public Set getLongDisplayers() { return Collections.unmodifiableSet(this.longDisplayers); } /** * Get the table Displayer * * @return the table Displayer */ public Displayer getTableDisplayer() { return tableDisplayer; } /** * @see Object#equals * * @param obj the Object to compare with * @return true if this is equal to obj */ public boolean equals(Object obj) { if (!(obj instanceof Type)) { return false; } Type typeObj = (Type) obj; return fieldConfigs.equals(typeObj.fieldConfigs) && longDisplayers.equals(typeObj.longDisplayers) && tableDisplayer.equals(typeObj.tableDisplayer); } /** * @see Object#hashCode * * @return the hashCode for this Type object */ public int hashCode() { return fieldConfigs.hashCode() + 3 * longDisplayers.hashCode() + 5 * tableDisplayer.hashCode(); } /** * Return an XML String of this Type object * * @return a String version of this WebConfig object */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<class className=\"" + className + "\""); if (fieldName != null) { sb.append(" fieldName=\"" + fieldName + "\""); } sb.append(">"); sb.append("<fieldconfigs>"); Iterator iter = fieldConfigs.iterator(); while (iter.hasNext()) { sb.append(iter.next().toString()); } sb.append("</fieldconfigs>"); if (tableDisplayer != null) { sb.append(tableDisplayer.toString("tabledisplayer")); } sb.append("<longdisplayers>"); iter = longDisplayers.iterator(); while (iter.hasNext()) { sb.append(iter.next().toString()); } sb.append("</longdisplayers>"); sb.append("</class>"); return sb.toString(); } }
fixing NPE in equals and hashCode Former-commit-id: a780a526ead3a45d6fcd1d065deb317c2e5646fc
intermine/web/main/src/org/intermine/web/config/Type.java
fixing NPE in equals and hashCode
<ide><path>ntermine/web/main/src/org/intermine/web/config/Type.java <ide> import java.util.Collections; <ide> <ide> import org.apache.commons.collections.set.ListOrderedSet; <add>import org.apache.commons.lang.ObjectUtils; <ide> <ide> /** <ide> * Configuration object for displaying a class <ide> <ide> return fieldConfigs.equals(typeObj.fieldConfigs) <ide> && longDisplayers.equals(typeObj.longDisplayers) <del> && tableDisplayer.equals(typeObj.tableDisplayer); <add> && ObjectUtils.equals(tableDisplayer, typeObj.tableDisplayer); <ide> } <ide> <ide> /** <ide> * @return the hashCode for this Type object <ide> */ <ide> public int hashCode() { <del> return fieldConfigs.hashCode() + 3 * longDisplayers.hashCode() + 5 * tableDisplayer.hashCode(); <add> int hash = fieldConfigs.hashCode() + 3 * longDisplayers.hashCode(); <add> if (tableDisplayer != null) { <add> hash += 5 * tableDisplayer.hashCode(); <add> } <add> return hash; <ide> } <ide> <ide> /**
Java
mit
b8baabf5ca5ca61640b169b5aed8da59f73a2cc8
0
noogotte/DiamondRush
package fr.aumgn.diamondrush.game; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.bukkit.ChatColor; import fr.aumgn.bukkitutils.util.Util; public enum TeamColor { BLUE (ChatColor.BLUE, 11, "Bleu" ), RED (ChatColor.DARK_RED, 14, "Rouge" ), GREEN (ChatColor.DARK_GREEN, 13, "Vert" ), ORANGE (ChatColor.GOLD, 1, "Orange" ), DARK_PURPLE (ChatColor.DARK_PURPLE, 10, "Mauve" ), WHITE (ChatColor.WHITE, 0, "Blanc" ), GRAY (ChatColor.DARK_GRAY, 8, "Gris" ), AQUA (ChatColor.AQUA, 3, "Turquoise" ), LIGHT_GREEN (ChatColor.GREEN, 5, "Vert clair" ), BLACK (ChatColor.BLACK, 15, "Noir" ), YELLOW (ChatColor.YELLOW, 4, "Jaune" ); private final ChatColor chat; private final byte wool; private final String name; private TeamColor(ChatColor chat, int wool, String name) { this.chat = chat; this.wool = (byte) wool; this.name = name; } public ChatColor getChatColor() { return chat; } public byte getWoolColor() { return wool; } public String getColorName() { return name; } public static List<TeamColor> getRandomColors(int count) { List<TeamColor> list = new ArrayList<TeamColor>(count); TeamColor[] colors = values(); for (int i = 0; i < count; i++) { list.add(colors[i]); } Collections.shuffle(list, Util.getRandom()); return list; } }
src/main/java/fr/aumgn/diamondrush/game/TeamColor.java
package fr.aumgn.diamondrush.game; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.bukkit.ChatColor; import fr.aumgn.bukkitutils.util.Util; public enum TeamColor { BLUE (ChatColor.BLUE, 11, "Bleue" ), RED (ChatColor.DARK_RED, 14, "Rouge" ), GREEN (ChatColor.DARK_GREEN, 13, "Verte" ), ORANGE (ChatColor.GOLD, 1, "Orange" ), DARK_PURPLE (ChatColor.DARK_PURPLE, 10, "Mauve" ), WHITE (ChatColor.WHITE, 0, "Blanche" ), GRAY (ChatColor.DARK_GRAY, 8, "Grise" ), AQUA (ChatColor.AQUA, 3, "Turquoise" ), LIGHT_GREEN (ChatColor.GREEN, 5, "Vert clair" ), BLACK (ChatColor.BLACK, 15, "Noire" ), YELLOW (ChatColor.YELLOW, 4, "Jaune" ); private final ChatColor chat; private final byte wool; private final String name; private TeamColor(ChatColor chat, int wool, String name) { this.chat = chat; this.wool = (byte) wool; this.name = name; } public ChatColor getChatColor() { return chat; } public byte getWoolColor() { return wool; } public String getColorName() { return name; } public static List<TeamColor> getRandomColors(int count) { List<TeamColor> list = new ArrayList<TeamColor>(count); TeamColor[] colors = values(); for (int i = 0; i < count; i++) { list.add(colors[i]); } Collections.shuffle(list, Util.getRandom()); return list; } }
Update colors (again)
src/main/java/fr/aumgn/diamondrush/game/TeamColor.java
Update colors (again)
<ide><path>rc/main/java/fr/aumgn/diamondrush/game/TeamColor.java <ide> <ide> public enum TeamColor { <ide> <del> BLUE (ChatColor.BLUE, 11, "Bleue" ), <add> BLUE (ChatColor.BLUE, 11, "Bleu" ), <ide> RED (ChatColor.DARK_RED, 14, "Rouge" ), <del> GREEN (ChatColor.DARK_GREEN, 13, "Verte" ), <add> GREEN (ChatColor.DARK_GREEN, 13, "Vert" ), <ide> ORANGE (ChatColor.GOLD, 1, "Orange" ), <ide> DARK_PURPLE (ChatColor.DARK_PURPLE, 10, "Mauve" ), <del> WHITE (ChatColor.WHITE, 0, "Blanche" ), <del> GRAY (ChatColor.DARK_GRAY, 8, "Grise" ), <add> WHITE (ChatColor.WHITE, 0, "Blanc" ), <add> GRAY (ChatColor.DARK_GRAY, 8, "Gris" ), <ide> AQUA (ChatColor.AQUA, 3, "Turquoise" ), <ide> LIGHT_GREEN (ChatColor.GREEN, 5, "Vert clair" ), <del> BLACK (ChatColor.BLACK, 15, "Noire" ), <add> BLACK (ChatColor.BLACK, 15, "Noir" ), <ide> YELLOW (ChatColor.YELLOW, 4, "Jaune" ); <ide> <ide> private final ChatColor chat;
Java
apache-2.0
b3ac122e9e52818c124924c627a6d4f0f58b649d
0
andrewpw/surferpedia,andrewpw/surferpedia
import java.util.Date; import models.Surfer; import models.SurferDB; import models.UserInfoDB; import play.Application; import play.GlobalSettings; import play.Play; import views.formdata.SurferFormData; public class Global extends GlobalSettings { public void onStart(Application app) { String adminEmail = Play.application().configuration().getString("digits.admin.email"); String adminPassword = Play.application().configuration().getString("digits.admin.password"); UserInfoDB.defineAdmin("Andrew", adminEmail, adminPassword); if (SurferDB.getSurferList().isEmpty()) { Surfer surfer21 = new Surfer( "Pauline Ado", "Anglet, France", "http://cdn.surf.transworld.net/files/2009/01/06/paulineadof_l.jpg", "http://www.freaksurfmag.com/Images/oakley-pro-junior-girls/pauline-ado.jpg", "As the 2009 ASP World Junior Champion, Pauline Ado is one of Europe’s most promising young faces. " + "Reserved yet competitively driven, the diminutive blonde was raised in the wave-rich Basque Country " + "before moving to Biarritz, where she's refined her surfing at some of the best beachbreaks in Europe. " + "Now, having finished high school, she'll be devoting herself fully to the WQS, and judging from what " + "we've seen so far, she may just be joining countryman Lee Ann Curren in the upper echelons of women's " + "surfing in years to come.", "https://pbs.twimg.com/profile_images/3136992645/ac7850df00bb561fee245b86b2545ef9.jpeg", "Ado", "Female", "Regular"); Surfer surfer20 = new Surfer( "Bianca Buitendag", "Victoria Bay, South Africa", "", "http://ugc4.mporatrons.com/thumbs/AA691UAqcGc_1280x720_0005.jpg", "Bianca grew up in a Surfing family with two brothers, surfing from age 7. " + "She learned to surf in the beach breaks of the Strand as well as at the Jongensfontein point break. " + "The family then moved to Victoria Bay when she was age 11. It was here that Bianca started focusing " + "more on competitive surfing. Bianca soon stood out at a young age winning the Billabong u/20 girls " + "finals at age 13 as well as coming 9th at Mr Price WQS at age 14. By the year 2009 Bianca won every " + "single contest she entered in South Africa.", "http://sphotos-b.xx.fbcdn.net/hphotos-ash3/s720x720/555242_461808770502092_1679674257_n.jpg", "Bianca", "Female", "Goofy"); Surfer surfer19 = new Surfer( "Lakey Peterson", "Santa Barbara, California USA", "3rd place at US Open of Surfing, 1st place, ASP North American Champ", "http://img.bnqt.com/CMS/bnqt/network/bnqt.com/media/editor/girls/0001-9f368307-516ecc72-d13d-efe63410.jpg", "In 2000, when Lakey was just 5 years old, her parents, David and Sue, rounded up their youngest child and " + "her two older siblings —Whitney, then 13, and Parker, 10 — and set out on a year-long, around-the-world " + "adventure. It was during this trip that Lakey learned to surf. For three months, the Petersons set up " + "shop in Manly Beach, Australia, where their littlest member instantly earned the nickname \"Lakey " + "Legend\" from the locals for effortlessly catching wave after wave on her boogie board.", "http://img246.imageshack.us/img246/4176/img9612.jpg", "Lakey", "Female", "Regular"); Surfer surfer18 = new Surfer( "Coco Ho", "Sunset Beach, Hawaii, USA", "2007 Triple Crown Rookie of the year\n" + "2009 ASP Rookie of the year", "http://a3.espncdn.com/photo/2012/1112/as_realsurf_coco_ho.jpg", "When she was just seven years old, Coco Ho learned to surf in a spirited effort to impress her older " + "brother. \"My brother's one of the most innovative surfers around, and I wanted to be just like him,\" " + "says Coco, now 21, of professional surfer Mason Ho. \"My first memory surfing was going before school " + "on a new board I got for my birthday, and coming to class with wet hair and telling everyone I went " + "surfing before school,\" she adds. \"I thought I was so cool.\" But while her family also includes " + "surf legends Michael Ho (her dad) and Derek Ho (her uncle), Coco soon became an idol in her own right. " + "Qualifying for the Association of Surfing Professionals Women's World Tour at age 17—and repeatedly " + "voted a top three fan favorite in Surfer magazine's Surfer Poll—Coco now seeks to build on her " + "award-studded surf career while inspiring other girls to break through barriers and pursue their " + "passions.", "http://bikinibird.com/wp-content/uploads/2012/12/BB_TSD_Vco_Coco_Quinsey_0291_f.jpg", "Coco", "Female", "Regular"); Surfer surfer17 = new Surfer( "Stephanie Gilmore", "Tweed Heads, New South Wales, Australia", "Five-time world champion on the Women's ASP World Tour (2007, 2008, 2009, 2010, 2012)", "http://a.espncdn.com/photo/2012/1127/as_surf_steph_reo_servais_2048.jpg", "Gilmore's life as a surfer began at age 10 when she stood on a bodyboard. By age 17 she was entering world" + " tour events as a wild card competitor, which paid off with a victory at the 2005 Roxy Pro Gold Coast. " + "In her next season she won another wild card event, the 2006 Havaianas Beachley Classic. Gilmore's " + "success on the WQS (World Qualifying Series) tour qualified her for the 2007 Women's ASP World Tour and" + " she did not disappoint. She won four of the eight events and claimed the 2007 World Title. " + "She would repeat her success in 2008, 2009 and 2010", "http://upload.wikimedia.org/wikipedia/commons/thumb/5/52/" + "Stephanie_Gilmore.jpg/419px-Stephanie_Gilmore.jpg", "Gilmore", "Female", "Regular"); Surfer surfer16 = new Surfer( "Courtney Conlogue", "Santa Ana, California", "", "http://a1.espncdn.com/photo/2013/0709/espnw_g_conlogue1_800.jpg", "Courtney Conlogue is the kind of California kid who was good at almost every sport she tried. She could " + "have pursued track or soccer, but her heart was in surfing from the moment her father put her on a " + "board at age 4.\nNow the 20-year-old is a three-year veteran of the Association of Surfing " + "Professionals," + " ranked fourth on the list of elite pros and set to compete for the Roxy Pro title in Biarritz, France. " + "She won an event in New Zealand in April, and is in the hunt for her first title as ASP women's world " + "champion. It's a challenge she relishes.", "http://media.outsideonline.com/images/364*488/WCMDEV_151673_03_courtney_100.jpg", "Conlogue", "Female", "Regular"); Surfer surfer15 = new Surfer( "Sally Fitzgibbons", "Gerroa, New South Wales, Australia", "", "http://cdn.bleacherreport.net/images_root/slides/photos/002/097/417/sally_fitzgibbons_display_" + "image.jpg?1333545704", "Surfing superstar Sally Fitzgibbons is one of the top ranked female surfers in the world. In March, 2012, " + "Fitzgibbons won her second straight ASP 6-Star win in a row at Newcastle's Surfest.", "https://pbs.twimg.com/profile_images/710644548/Sally2.jpg", "Fitzgibbons", "Female", "Regular"); Surfer surfer14 = new Surfer( "Tyler Wright", "Lennox Head, New South Wales, Australia", "ASP Rookie of the year", "http://images.smh.com.au/2012/02/11/3030926/art-353-tyler-wright-200x0.jpg", "Born into a dedicated surfing family, Tyler is making her mark in the surfing world having already " + "defeated some of the top 17 female surfers on the planet and earned the critics’ praise as one to " + "watch in coming years.\n" + "Tyler attracted the surfing world’s attention after she received a wildcard entry into the Beachley " + "Classic after winning the Oakley trails in 2008. She went on and defeated some of the world’s leading " + "surfers including Brazil’s Silvana Lima and ASP Women’s World Champion Stephanie Gilmore, and claimed " + "the biggest prize purse on the ASP World Women’s Tour. At only 14 years-old, Tyler broke a record for " + "being the youngest winner of a CT event, both male and female.", "http://www.aspworldtour.com/wp-content/uploads/2011/01/wright_t4080pipe10cestari_l1.jpg", "Tyler", "Female", "Regular"); Surfer surfer13 = new Surfer( "Carissa Moore", "Honolulu, Hawaii, USA", "2011 and 2013 ASP Women's World Tour Champion", "http://www.lat34.org/quick_hits/wp-content/uploads/2008/11/moore_c1985reefpro08rowland_m.jpg", "Back in her NSSA days, Carissa Moore stunned the world with her skill. Everyone who watched her surf " + "swore that she would be queen one day.\n" + "Sure enough, Carissa already has two ASP World Championship titles to her name. On top of that, " + "she regularly produces clips that redefine women’s surfing. She’s got the power of a moose and the " + "finesse of a leopard. She’ll do the biggest hack you’ve ever seen and follow it up with an air-reverse. " + "And, most importantly, she does it all with a smile.", "http://cdn.surf.transworld.net/wp-content/blogs.dir/443/files/carissa-moore-" + "hottest-girls-in-pro-surfing/carissa_photobrent006.JPG", "Carissa", "Female", "Regular"); Surfer surfer12 = new Surfer( "Nat Young", "Sydney, New South Wales", "2 times World Surfing Champion 1996, 1970.", "http://www.surfline.com/surfaz/images/young_nat/grannis_natyoung2.jpg", "Born in Sydney, New South Wales, Young grew up in the small coastal suburb of Collaroy. " + "In 1964, he was runner-up in the Australian junior championship at Manly, and two years later was named " + "world surfing champion in 1966. He won the title again (then called the Smirnoff World Pro/Am) in 1970. " + "Young won three Australian titles in 1966, 1967 and 1969, and won the Bells Beach Surf Classic a record " + "four times. Young featured in a number of important surf films of '60s and '70s including the classic " + "1973 surf movie Crystal Voyager and he also had a featured role as surfer Nick Naylor in the 1979 " + "Australian drama film Palm Beach", "http://cdn2.coresites.mpora.com/surfeurope_new/wp-content/uploads/2013/09/lg_Nat_Young_Albert_Falzon.jpg", "Nat", "Male", "Goofy"); Surfer surfer11 = new Surfer( "Josh Kerr", "Gold Coast, QLD Australia", "2 times airshow winner", "http://cdn.surf.transworld.net/files/2011/01/tj-kerr.jpg", "He of the Kerr-upt flip. He of the Kerr-azy times. Josh Kerr was christened on a bodyboard but graduated " + "to a surfboard at age eleven and was winning airshows by 16. Stomping tweaked reverse slobs. " + "(He won two airshow titles. One in 2001 and the other in 2003). Yet he is no one trick pony. " + "Josh Kerr competed on the Dream Tour stage in both 2007 and 2009", "http://www.rusty.com/files/Profiles/josh_kerr_mugshot.jpg", "Kerr", "Male", "Regular"); Surfer surfer10 = new Surfer( "Julian Wilson", "Coolum Beach, QLD Australia", "2010 Triple Crown Rookie of the Year", "http://b.vimeocdn.com/ts/430/185/430185000_640.jpg", "Julian Wilson (born November 8, 1988) is an Australian professional surfer who competes on the " + "Association of Surfing Professionals Men's World Tour. " + "He is an ambassador for the National Breast Cancer Foundation. Julian's mother is a breast cancer " + "survivor and he was inspired to ride a pink board by close family friend and international cricketer " + "Matt Hayden that plays with a pink bat for the same cause", "http://blog.stylesight.com/wp-content/uploads/2011/08/" + "Nike_US_Open_of_Surfing_Julian_Wilson_Interview6.jpg", "Julian", "Male", "Regular"); Surfer surfer9 = new Surfer( "Kai Otton", "Queenscliff, Sydney, NSW, Australia", "2 times ASP World Champion 2007, 2009.", "http://cdn.surf.transworld.net/wp-content/blogs.dir/443/files/2011/08/kai-otton.jpg", "Kai Otton embraced all sports as a skinny grom from football to riding dirt bikes. Now a staple on the " + "ASP World Tour, he simply didn’t have a junior career. Originally hailing from the off-the-radar town " + "country town of Tathra, Australia, he drove to Australia’s more high profile spots, surfing events " + "without a seed, and living out of his car. He surfed on his own and worked in surf shops and surf " + "factories", "http://iamwok.com/wp-content/uploads/2013/01/kai_otton_m.jpg", "Kai", "Male", "Goofy"); Surfer surfer8 = new Surfer( "Taj Burrow", "Yallingup, WA Australia", "ASP World Tour Runner Up 1999, 2007" + "ASP Rookie of the Year 1998" + "Australian Male Surfer of the Year 1997", "http://costaricasurfing.org/wp-content/uploads/2013/07/Taj-Burrow.jpg", "In 1998 he qualified for the ASP World Tour at 18-years-old, becoming the youngest surfer to do so at " + "the time. Burrow had already earned a place on the world tour a year earlier, but he turned it down " + "stating that, as a 17-year-old, he was \"too young to do the tour full-on\". After his first year on " + "tour in 1998, Burrow claimed the ASP World Tour Rookie of the Year award after finishing 12th place " + "in the rankings", "http://www.lat34.com/_/Photo/200xNone/taj_burrow_2.jpg", "Taj", "Male", "Regular"); Surfer surfer7 = new Surfer( "Jordy Smith", "Cape Town, South Africa", "2 times ASP World Champion 2007, 2009.", "http://cdn.actionrecon.com/wp-content/uploads/2011/06/jordy-smith-flip-starter.jpg", "Jordan Michael \"Jordy\" Smith (born 11 February 1988) is a professional surfer from South Africa, " + "competing on the World Championship Tour (WCT). In 2007 Smith won surfing's World Qualifying Series," + " the second-tier tour which leads to qualification for the WCT.\nJordy Smith won both the 2010 and " + "2011 Billabong J-Bay competitions in South Africa, which is part of the WCT Dream Tour, " + "making him the no. 1 ranked surfer in the world.\nSmith grew up in Durban and started surfing at age 6. " + "He attended a local Durban high school, Glenwood High School.\nSmith is known for the manoeuvres " + "\"rodeo flip\" and full rotation \"alley-oops\" and he has been sponsored by O'Neill since 2007.", "http://cdn.business.transworld.net/files/2008/06/10/jordy_smith_vestal.jpg", "Jordy", "Male", "Regular"); Surfer surfer6 = new Surfer( "Joel Parkinson", "Tweed Heads, New South Wales, Australia", "2 times ASP World Champion 2007, 2009.", "http://resources2.news.com.au/images/2010/03/02/1225835/987586-joel-parkinson.jpg", "Joel Parkinson is an Australian surfer who competes on the ASP (Association Of Surfing Professionals) " + "World Tour. After twelve years competing at the elite level on the ASP World Championship Tour, " + "a stretch that saw him win eleven elite ASP World Title Events, plus nine additional ASP tour events, " + "and achieve runner-up second place to the ASP World Title four times, Parkinson won his only " + "ASP World Championship Tour Surfing Title on 14 December 2012 in Hawaii at the Banzai Pipeline during " + "the ASP World Tours' final event for 2012–the Billabong Pipeline Masters", "http://www.lat34.com/_/Photo/200xNone/joel_parkinson_2.jpg", "Parkinson", "Male", "Regular"); Surfer surfer5 = new Surfer( "Kelly Slater", "Cocoa Beach, Florida", "11 time ASP World Champion", "http://costaricasurfing.org/wp-content/uploads/2013/07/Kelly-Slater-1.jpg", "Robert Kelly Slater (born February 11, 1972, Cocoa Beach, Florida, US) is an American professional surfer " + "known for his competitive prowess and style. He has been crowned ASP World Tour Champion " + "a record 11 times, including 5 consecutive titles from 1994–98. He is the youngest (at age 20) " + "and the oldest (at age 39) to win the title. Upon winning his 5th world title in 1997, " + "Slater passed Australian surfer Mark Richards to become the most successful champion in the history of " + "the sport. In 2007 he also became the all-time leader in career event wins by winning " + "the Boost Mobile Pro event at Lower Trestles near San Clemente, California. " + "The previous record was held by Slater's childhood hero, 3-time world champion Tom Curren", "http://www.athletepromotions.com/blog/wp-content/uploads/2013/08/kelly-slater.jpg", "Kelly", "Male", "Regular"); Surfer surfer4 = new Surfer( "Mick Fanning", "Tweed Heads, New South Wales, Australia", "2 times ASP World Champion 2007, 2009." + "6 times Australian Male Surfer of the Year 2002, 2004, 2007, 2008, 2010, 2011.", "http://www.smh.com.au/ffximage/2005/04/11/mickfanning_wideweb__430x350.jpg", "He was born in Penrith, New South Wales, Australia on 13 June 1981 to Irish parents. " + "Fanning learned to surf at the age of 5 in coastal South Australia at a town called Mt Gambier, " + "but did not go full on until his family moved to Tweed Heads when he was twelve. " + "He grew up with fellow professional surfer, Joel Parkinson and fellow ripper Nat West. " + "On the edge of the Queensland border, Fanning had access to epic surf north and south " + "and he began to make a name for himself. In 1996 he established himself as one the very best surfers " + "to rule the Queensland points by placing in the top three at the Australian National Titles.", "http://upload.wikimedia.org/wikipedia/commons/b/b2/Mick_Fanning.jpg", "Mick", "Male", "Regular"); Surfer surfer3 = new Surfer( "Adriano de Souza", "Sao Paulo, Brazil", "Ranked #1 on the 2013 ASP World Tour", "http://epikoo.com/sites/default/files/adriano_de_souza_2.jpg", "Adriano De Souza rode his first wave at eight " + "years old and eight years later the surf world would take notice of this young, talented surfer at the " + "Billabong ASP World Junior Championships. At the 2004 event, he defeated opponents four years his senior" + " and was named the youngest ASP World Junior Champion ever at 16.", "http://thumbs.dreamstime.com/z/adriano-de-souza-quicksilver-pro-18699912.jpg", "Adriano", "Male", "Regular"); Surfer surfer2 = new Surfer( "Jake Marshall", "San Diego, California", "", "http://www.surfingamerica.org/wp-content/uploads/2011/01/JakeMarshall2-3.jpg", "Many young surfers have the " + "potential to make an impact on our sport, but none look more poised to do so than Jake Marshall. " + "Raised on the rippable beachbreaks and reefs of San Diego's North County, Jake has developed a " + "solid base of smooth rail work as well as the kind of flair that few 14-year-old surfers can match.", "http://www.nssa.org/photogallery/gallery/2010-11_Season/JakeMarshallPOWweb.jpg", "Jake", "Grom", "Regular"); Surfer surfer = new Surfer( "Bethany Hamilton", "Kauai, Hawaii", "Wahine O Ke Kai (Woman of the Sea) Award at the " + "SIM AWaterman’s Ball (2004)", "http://cdn3.dogonews.com/pictures/7220/content/Bethany-Hamilton.jpg?1302472752", "Bethany Hamilton has become " + "a source of inspiration to millions through her story of faith, determination, and hope. Born into a " + "family of surfers on February 8, 1990, on the island of Kauai, Hawaii, Bethany began surfing at a " + "young age. At the age of eight, Bethany entered her first surf competition, " + "the Rell Sun Menehune event on Oahu, where she won both the short and long board divisions. " + "This sparked a love for surf competition within her spirit.", "http://www.bellaonline.com/review/issues/fall2012/images/PubPortrait_Cr_bethanyHamilton.jpg", "Bethany", "Female", "Regular"); SurferDB.add(surfer.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer2.getSlug(), new SurferFormData(surfer2)); SurferDB.add(surfer3.getSlug(), new SurferFormData(surfer3)); SurferDB.add(surfer4.getSlug(), new SurferFormData(surfer4)); SurferDB.add(surfer5.getSlug(), new SurferFormData(surfer5)); SurferDB.add(surfer6.getSlug(), new SurferFormData(surfer6)); SurferDB.add(surfer7.getSlug(), new SurferFormData(surfer7)); SurferDB.add(surfer8.getSlug(), new SurferFormData(surfer8)); SurferDB.add(surfer9.getSlug(), new SurferFormData(surfer9)); SurferDB.add(surfer10.getSlug(), new SurferFormData(surfer10)); SurferDB.add(surfer11.getSlug(), new SurferFormData(surfer11)); SurferDB.add(surfer12.getSlug(), new SurferFormData(surfer12)); SurferDB.add(surfer13.getSlug(), new SurferFormData(surfer13)); SurferDB.add(surfer14.getSlug(), new SurferFormData(surfer14)); SurferDB.add(surfer15.getSlug(), new SurferFormData(surfer15)); SurferDB.add(surfer16.getSlug(), new SurferFormData(surfer16)); SurferDB.add(surfer17.getSlug(), new SurferFormData(surfer17)); SurferDB.add(surfer18.getSlug(), new SurferFormData(surfer18)); SurferDB.add(surfer19.getSlug(), new SurferFormData(surfer19)); SurferDB.add(surfer20.getSlug(), new SurferFormData(surfer20)); SurferDB.add(surfer21.getSlug(), new SurferFormData(surfer21)); } } }
app/Global.java
import java.util.Date; import models.Surfer; import models.SurferDB; import models.UserInfoDB; import play.Application; import play.GlobalSettings; import play.Play; import views.formdata.SurferFormData; public class Global extends GlobalSettings { public void onStart(Application app) { String adminEmail = Play.application().configuration().getString("digits.admin.email"); String adminPassword = Play.application().configuration().getString("digits.admin.password"); UserInfoDB.defineAdmin("Andrew", adminEmail, adminPassword); Surfer surfer21 = new Surfer( "Pauline Ado", "Anglet, France", "http://cdn.surf.transworld.net/files/2009/01/06/paulineadof_l.jpg", "http://www.freaksurfmag.com/Images/oakley-pro-junior-girls/pauline-ado.jpg", "As the 2009 ASP World Junior Champion, Pauline Ado is one of Europe’s most promising young faces. " + "Reserved yet competitively driven, the diminutive blonde was raised in the wave-rich Basque Country " + "before moving to Biarritz, where she's refined her surfing at some of the best beachbreaks in Europe. " + "Now, having finished high school, she'll be devoting herself fully to the WQS, and judging from what " + "we've seen so far, she may just be joining countryman Lee Ann Curren in the upper echelons of women's " + "surfing in years to come.", "https://pbs.twimg.com/profile_images/3136992645/ac7850df00bb561fee245b86b2545ef9.jpeg", "Ado", "Female", "Regular"); Surfer surfer20 = new Surfer( "Bianca Buitendag", "Victoria Bay, South Africa", "", "http://ugc4.mporatrons.com/thumbs/AA691UAqcGc_1280x720_0005.jpg", "Bianca grew up in a Surfing family with two brothers, surfing from age 7. " + "She learned to surf in the beach breaks of the Strand as well as at the Jongensfontein point break. " + "The family then moved to Victoria Bay when she was age 11. It was here that Bianca started focusing " + "more on competitive surfing. Bianca soon stood out at a young age winning the Billabong u/20 girls " + "finals at age 13 as well as coming 9th at Mr Price WQS at age 14. By the year 2009 Bianca won every " + "single contest she entered in South Africa.", "http://sphotos-b.xx.fbcdn.net/hphotos-ash3/s720x720/555242_461808770502092_1679674257_n.jpg", "Bianca", "Female", "Goofy"); Surfer surfer19 = new Surfer( "Lakey Peterson", "Santa Barbara, California USA", "3rd place at US Open of Surfing, 1st place, ASP North American Champ", "http://img.bnqt.com/CMS/bnqt/network/bnqt.com/media/editor/girls/0001-9f368307-516ecc72-d13d-efe63410.jpg", "In 2000, when Lakey was just 5 years old, her parents, David and Sue, rounded up their youngest child and " + "her two older siblings —Whitney, then 13, and Parker, 10 — and set out on a year-long, around-the-world " + "adventure. It was during this trip that Lakey learned to surf. For three months, the Petersons set up " + "shop in Manly Beach, Australia, where their littlest member instantly earned the nickname \"Lakey " + "Legend\" from the locals for effortlessly catching wave after wave on her boogie board.", "http://img246.imageshack.us/img246/4176/img9612.jpg", "Lakey", "Female", "Regular"); Surfer surfer18 = new Surfer( "Coco Ho", "Sunset Beach, Hawaii, USA", "2007 Triple Crown Rookie of the year\n" + "2009 ASP Rookie of the year", "http://a3.espncdn.com/photo/2012/1112/as_realsurf_coco_ho.jpg", "When she was just seven years old, Coco Ho learned to surf in a spirited effort to impress her older " + "brother. \"My brother's one of the most innovative surfers around, and I wanted to be just like him,\" " + "says Coco, now 21, of professional surfer Mason Ho. \"My first memory surfing was going before school " + "on a new board I got for my birthday, and coming to class with wet hair and telling everyone I went " + "surfing before school,\" she adds. \"I thought I was so cool.\" But while her family also includes " + "surf legends Michael Ho (her dad) and Derek Ho (her uncle), Coco soon became an idol in her own right. " + "Qualifying for the Association of Surfing Professionals Women's World Tour at age 17—and repeatedly " + "voted a top three fan favorite in Surfer magazine's Surfer Poll—Coco now seeks to build on her " + "award-studded surf career while inspiring other girls to break through barriers and pursue their passions.", "http://bikinibird.com/wp-content/uploads/2012/12/BB_TSD_Vco_Coco_Quinsey_0291_f.jpg", "Coco", "Female", "Regular"); Surfer surfer17 = new Surfer( "Stephanie Gilmore", "Tweed Heads, New South Wales, Australia", "Five-time world champion on the Women's ASP World Tour (2007, 2008, 2009, 2010, 2012)", "http://a.espncdn.com/photo/2012/1127/as_surf_steph_reo_servais_2048.jpg", "Gilmore's life as a surfer began at age 10 when she stood on a bodyboard. By age 17 she was entering world" + " tour events as a wild card competitor, which paid off with a victory at the 2005 Roxy Pro Gold Coast. " + "In her next season she won another wild card event, the 2006 Havaianas Beachley Classic. Gilmore's " + "success on the WQS (World Qualifying Series) tour qualified her for the 2007 Women's ASP World Tour and" + " she did not disappoint. She won four of the eight events and claimed the 2007 World Title. " + "She would repeat her success in 2008, 2009 and 2010", "http://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Stephanie_Gilmore.jpg/419px-Stephanie_Gilmore.jpg", "Gilmore", "Female", "Regular"); Surfer surfer16 = new Surfer( "Courtney Conlogue", "Santa Ana, California", "", "http://a1.espncdn.com/photo/2013/0709/espnw_g_conlogue1_800.jpg", "Courtney Conlogue is the kind of California kid who was good at almost every sport she tried. She could " + "have pursued track or soccer, but her heart was in surfing from the moment her father put her on a " + "board at age 4.\nNow the 20-year-old is a three-year veteran of the Association of Surfing Professionals," + " ranked fourth on the list of elite pros and set to compete for the Roxy Pro title in Biarritz, France. " + "She won an event in New Zealand in April, and is in the hunt for her first title as ASP women's world " + "champion. It's a challenge she relishes.", "http://media.outsideonline.com/images/364*488/WCMDEV_151673_03_courtney_100.jpg", "Conlogue", "Female", "Regular"); Surfer surfer15 = new Surfer( "Sally Fitzgibbons", "Gerroa, New South Wales, Australia", "", "http://cdn.bleacherreport.net/images_root/slides/photos/002/097/417/sally_fitzgibbons_display_" + "image.jpg?1333545704", "Surfing superstar Sally Fitzgibbons is one of the top ranked female surfers in the world. In March, 2012, " + "Fitzgibbons won her second straight ASP 6-Star win in a row at Newcastle's Surfest.", "https://pbs.twimg.com/profile_images/710644548/Sally2.jpg", "Fitzgibbons", "Female", "Regular"); Surfer surfer14 = new Surfer( "Tyler Wright", "Lennox Head, New South Wales, Australia", "ASP Rookie of the year", "http://images.smh.com.au/2012/02/11/3030926/art-353-tyler-wright-200x0.jpg", "Born into a dedicated surfing family, Tyler is making her mark in the surfing world having already " + "defeated some of the top 17 female surfers on the planet and earned the critics’ praise as one to " + "watch in coming years.\n" + "Tyler attracted the surfing world’s attention after she received a wildcard entry into the Beachley " + "Classic after winning the Oakley trails in 2008. She went on and defeated some of the world’s leading " + "surfers including Brazil’s Silvana Lima and ASP Women’s World Champion Stephanie Gilmore, and claimed " + "the biggest prize purse on the ASP World Women’s Tour. At only 14 years-old, Tyler broke a record for " + "being the youngest winner of a CT event, both male and female.", "http://www.aspworldtour.com/wp-content/uploads/2011/01/wright_t4080pipe10cestari_l1.jpg", "Tyler", "Female", "Regular"); Surfer surfer13 = new Surfer( "Carissa Moore", "Honolulu, Hawaii, USA", "2011 and 2013 ASP Women's World Tour Champion", "http://www.lat34.org/quick_hits/wp-content/uploads/2008/11/moore_c1985reefpro08rowland_m.jpg", "Back in her NSSA days, Carissa Moore stunned the world with her skill. Everyone who watched her surf " + "swore that she would be queen one day.\n" + "Sure enough, Carissa already has two ASP World Championship titles to her name. On top of that, " + "she regularly produces clips that redefine women’s surfing. She’s got the power of a moose and the " + "finesse of a leopard. She’ll do the biggest hack you’ve ever seen and follow it up with an air-reverse. " + "And, most importantly, she does it all with a smile.", "http://cdn.surf.transworld.net/wp-content/blogs.dir/443/files/carissa-moore-" + "hottest-girls-in-pro-surfing/carissa_photobrent006.JPG", "Carissa", "Female", "Regular"); Surfer surfer12 = new Surfer( "Nat Young", "Sydney, New South Wales", "2 times World Surfing Champion 1996, 1970.", "http://www.surfline.com/surfaz/images/young_nat/grannis_natyoung2.jpg", "Born in Sydney, New South Wales, Young grew up in the small coastal suburb of Collaroy. " + "In 1964, he was runner-up in the Australian junior championship at Manly, and two years later was named " + "world surfing champion in 1966. He won the title again (then called the Smirnoff World Pro/Am) in 1970. " + "Young won three Australian titles in 1966, 1967 and 1969, and won the Bells Beach Surf Classic a record " + "four times. Young featured in a number of important surf films of '60s and '70s including the classic " + "1973 surf movie Crystal Voyager and he also had a featured role as surfer Nick Naylor in the 1979 " + "Australian drama film Palm Beach", "http://cdn2.coresites.mpora.com/surfeurope_new/wp-content/uploads/2013/09/lg_Nat_Young_Albert_Falzon.jpg", "Nat", "Male", "Goofy"); Surfer surfer11 = new Surfer( "Josh Kerr", "Gold Coast, QLD Australia", "2 times airshow winner", "http://cdn.surf.transworld.net/files/2011/01/tj-kerr.jpg", "He of the Kerr-upt flip. He of the Kerr-azy times. Josh Kerr was christened on a bodyboard but graduated " + "to a surfboard at age eleven and was winning airshows by 16. Stomping tweaked reverse slobs. " + "(He won two airshow titles. One in 2001 and the other in 2003). Yet he is no one trick pony. " + "Josh Kerr competed on the Dream Tour stage in both 2007 and 2009", "http://www.rusty.com/files/Profiles/josh_kerr_mugshot.jpg", "Kerr", "Male", "Regular"); Surfer surfer10 = new Surfer( "Julian Wilson", "Coolum Beach, QLD Australia", "2010 Triple Crown Rookie of the Year", "http://b.vimeocdn.com/ts/430/185/430185000_640.jpg", "Julian Wilson (born November 8, 1988) is an Australian professional surfer who competes on the " + "Association of Surfing Professionals Men's World Tour. " + "He is an ambassador for the National Breast Cancer Foundation. Julian's mother is a breast cancer " + "survivor and he was inspired to ride a pink board by close family friend and international cricketer " + "Matt Hayden that plays with a pink bat for the same cause", "http://blog.stylesight.com/wp-content/uploads/2011/08/Nike_US_Open_of_Surfing_Julian_Wilson_Interview6.jpg", "Julian", "Male", "Regular"); Surfer surfer9 = new Surfer( "Kai Otton", "Queenscliff, Sydney, NSW, Australia", "2 times ASP World Champion 2007, 2009.", "http://cdn.surf.transworld.net/wp-content/blogs.dir/443/files/2011/08/kai-otton.jpg", "Kai Otton embraced all sports as a skinny grom from football to riding dirt bikes. Now a staple on the " + "ASP World Tour, he simply didn’t have a junior career. Originally hailing from the off-the-radar town " + "country town of Tathra, Australia, he drove to Australia’s more high profile spots, surfing events " + "without a seed, and living out of his car. He surfed on his own and worked in surf shops and surf " + "factories", "http://iamwok.com/wp-content/uploads/2013/01/kai_otton_m.jpg", "Kai", "Male", "Goofy"); Surfer surfer8 = new Surfer( "Taj Burrow", "Yallingup, WA Australia", "ASP World Tour Runner Up 1999, 2007" + "ASP Rookie of the Year 1998" + "Australian Male Surfer of the Year 1997", "http://costaricasurfing.org/wp-content/uploads/2013/07/Taj-Burrow.jpg", "In 1998 he qualified for the ASP World Tour at 18-years-old, becoming the youngest surfer to do so at " + "the time. Burrow had already earned a place on the world tour a year earlier, but he turned it down " + "stating that, as a 17-year-old, he was \"too young to do the tour full-on\". After his first year on " + "tour in 1998, Burrow claimed the ASP World Tour Rookie of the Year award after finishing 12th place " + "in the rankings", "http://www.lat34.com/_/Photo/200xNone/taj_burrow_2.jpg", "Taj", "Male", "Regular"); Surfer surfer7 = new Surfer( "Jordy Smith", "Cape Town, South Africa", "2 times ASP World Champion 2007, 2009.", "http://cdn.actionrecon.com/wp-content/uploads/2011/06/jordy-smith-flip-starter.jpg", "Jordan Michael \"Jordy\" Smith (born 11 February 1988) is a professional surfer from South Africa, " + "competing on the World Championship Tour (WCT). In 2007 Smith won surfing's World Qualifying Series," + " the second-tier tour which leads to qualification for the WCT.\nJordy Smith won both the 2010 and " + "2011 Billabong J-Bay competitions in South Africa, which is part of the WCT Dream Tour, " + "making him the no. 1 ranked surfer in the world.\nSmith grew up in Durban and started surfing at age 6. " + "He attended a local Durban high school, Glenwood High School.\nSmith is known for the manoeuvres " + "\"rodeo flip\" and full rotation \"alley-oops\" and he has been sponsored by O'Neill since 2007.", "http://cdn.business.transworld.net/files/2008/06/10/jordy_smith_vestal.jpg", "Jordy", "Male", "Regular"); Surfer surfer6 = new Surfer( "Joel Parkinson", "Tweed Heads, New South Wales, Australia", "2 times ASP World Champion 2007, 2009.", "http://resources2.news.com.au/images/2010/03/02/1225835/987586-joel-parkinson.jpg", "Joel Parkinson is an Australian surfer who competes on the ASP (Association Of Surfing Professionals) " + "World Tour. After twelve years competing at the elite level on the ASP World Championship Tour, " + "a stretch that saw him win eleven elite ASP World Title Events, plus nine additional ASP tour events, " + "and achieve runner-up second place to the ASP World Title four times, Parkinson won his only " + "ASP World Championship Tour Surfing Title on 14 December 2012 in Hawaii at the Banzai Pipeline during " + "the ASP World Tours' final event for 2012–the Billabong Pipeline Masters", "http://www.lat34.com/_/Photo/200xNone/joel_parkinson_2.jpg", "Parkinson", "Male", "Regular"); Surfer surfer5 = new Surfer( "Kelly Slater", "Cocoa Beach, Florida", "11 time ASP World Champion", "http://costaricasurfing.org/wp-content/uploads/2013/07/Kelly-Slater-1.jpg", "Robert Kelly Slater (born February 11, 1972, Cocoa Beach, Florida, US) is an American professional surfer " + "known for his competitive prowess and style. He has been crowned ASP World Tour Champion " + "a record 11 times, including 5 consecutive titles from 1994–98. He is the youngest (at age 20) " + "and the oldest (at age 39) to win the title. Upon winning his 5th world title in 1997, " + "Slater passed Australian surfer Mark Richards to become the most successful champion in the history of " + "the sport. In 2007 he also became the all-time leader in career event wins by winning " + "the Boost Mobile Pro event at Lower Trestles near San Clemente, California. " + "The previous record was held by Slater's childhood hero, 3-time world champion Tom Curren", "http://www.athletepromotions.com/blog/wp-content/uploads/2013/08/kelly-slater.jpg", "Kelly", "Male", "Regular"); Surfer surfer4 = new Surfer( "Mick Fanning", "Tweed Heads, New South Wales, Australia", "2 times ASP World Champion 2007, 2009." + "6 times Australian Male Surfer of the Year 2002, 2004, 2007, 2008, 2010, 2011.", "http://www.smh.com.au/ffximage/2005/04/11/mickfanning_wideweb__430x350.jpg", "He was born in Penrith, New South Wales, Australia on 13 June 1981 to Irish parents. " + "Fanning learned to surf at the age of 5 in coastal South Australia at a town called Mt Gambier, " + "but did not go full on until his family moved to Tweed Heads when he was twelve. " + "He grew up with fellow professional surfer, Joel Parkinson and fellow ripper Nat West. " + "On the edge of the Queensland border, Fanning had access to epic surf north and south " + "and he began to make a name for himself. In 1996 he established himself as one the very best surfers " + "to rule the Queensland points by placing in the top three at the Australian National Titles.", "http://upload.wikimedia.org/wikipedia/commons/b/b2/Mick_Fanning.jpg", "Mick", "Male", "Regular"); Surfer surfer3 = new Surfer( "Adriano de Souza", "Sao Paulo, Brazil", "Ranked #1 on the 2013 ASP World Tour", "http://epikoo.com/sites/default/files/adriano_de_souza_2.jpg", "Adriano De Souza rode his first wave at eight " + "years old and eight years later the surf world would take notice of this young, talented surfer at the " + "Billabong ASP World Junior Championships. At the 2004 event, he defeated opponents four years his senior" + " and was named the youngest ASP World Junior Champion ever at 16.", "http://thumbs.dreamstime.com/z/adriano-de-souza-quicksilver-pro-18699912.jpg", "Adriano", "Male", "Regular"); Surfer surfer2 = new Surfer( "Jake Marshall", "San Diego, California", "", "http://www.surfingamerica.org/wp-content/uploads/2011/01/JakeMarshall2-3.jpg", "Many young surfers have the " + "potential to make an impact on our sport, but none look more poised to do so than Jake Marshall. " + "Raised on the rippable beachbreaks and reefs of San Diego's North County, Jake has developed a " + "solid base of smooth rail work as well as the kind of flair that few 14-year-old surfers can match.", "http://www.nssa.org/photogallery/gallery/2010-11_Season/JakeMarshallPOWweb.jpg", "Jake", "Grom", "Regular"); Surfer surfer = new Surfer( "Bethany Hamilton", "Kauai, Hawaii", "Wahine O Ke Kai (Woman of the Sea) Award at the " + "SIM AWaterman’s Ball (2004)", "http://cdn3.dogonews.com/pictures/7220/content/Bethany-Hamilton.jpg?1302472752", "Bethany Hamilton has become " + "a source of inspiration to millions through her story of faith, determination, and hope. Born into a " + "family of surfers on February 8, 1990, on the island of Kauai, Hawaii, Bethany began surfing at a " + "young age. At the age of eight, Bethany entered her first surf competition, " + "the Rell Sun Menehune event on Oahu, where she won both the short and long board divisions. " + "This sparked a love for surf competition within her spirit.", "http://www.bellaonline.com/review/issues/fall2012/images/PubPortrait_Cr_bethanyHamilton.jpg", "Bethany", "Female", "Regular"); SurferDB.add(surfer.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer2.getSlug(), new SurferFormData(surfer2)); SurferDB.add(surfer3.getSlug(), new SurferFormData(surfer3)); SurferDB.add(surfer4.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer5.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer6.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer7.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer8.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer9.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer10.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer11.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer12.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer13.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer14.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer15.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer16.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer17.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer18.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer19.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer20.getSlug(), new SurferFormData(surfer)); SurferDB.add(surfer21.getSlug(), new SurferFormData(surfer)); } }
Fixed Global.java. Fixed error in which Surfer3 was added multiple times. Also added isEmpty() clause to stop same Surfer's being added upon startup.
app/Global.java
Fixed Global.java.
<ide><path>pp/Global.java <ide> String adminEmail = Play.application().configuration().getString("digits.admin.email"); <ide> String adminPassword = Play.application().configuration().getString("digits.admin.password"); <ide> UserInfoDB.defineAdmin("Andrew", adminEmail, adminPassword); <add> <add> if (SurferDB.getSurferList().isEmpty()) { <ide> Surfer surfer21 = <ide> new Surfer( <ide> "Pauline Ado", <ide> + "more on competitive surfing. Bianca soon stood out at a young age winning the Billabong u/20 girls " <ide> + "finals at age 13 as well as coming 9th at Mr Price WQS at age 14. By the year 2009 Bianca won every " <ide> + "single contest she entered in South Africa.", <del> "http://sphotos-b.xx.fbcdn.net/hphotos-ash3/s720x720/555242_461808770502092_1679674257_n.jpg", "Bianca", "Female", "Goofy"); <add> "http://sphotos-b.xx.fbcdn.net/hphotos-ash3/s720x720/555242_461808770502092_1679674257_n.jpg", "Bianca", <add> "Female", "Goofy"); <ide> Surfer surfer19 = <ide> new Surfer( <ide> "Lakey Peterson", <ide> + "surf legends Michael Ho (her dad) and Derek Ho (her uncle), Coco soon became an idol in her own right. " <ide> + "Qualifying for the Association of Surfing Professionals Women's World Tour at age 17—and repeatedly " <ide> + "voted a top three fan favorite in Surfer magazine's Surfer Poll—Coco now seeks to build on her " <del> + "award-studded surf career while inspiring other girls to break through barriers and pursue their passions.", <add> + "award-studded surf career while inspiring other girls to break through barriers and pursue their " <add> + "passions.", <ide> "http://bikinibird.com/wp-content/uploads/2012/12/BB_TSD_Vco_Coco_Quinsey_0291_f.jpg", <ide> "Coco", "Female", "Regular"); <ide> Surfer surfer17 = <ide> + "success on the WQS (World Qualifying Series) tour qualified her for the 2007 Women's ASP World Tour and" <ide> + " she did not disappoint. She won four of the eight events and claimed the 2007 World Title. " <ide> + "She would repeat her success in 2008, 2009 and 2010", <del> "http://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Stephanie_Gilmore.jpg/419px-Stephanie_Gilmore.jpg", <add> "http://upload.wikimedia.org/wikipedia/commons/thumb/5/52/" <add> + "Stephanie_Gilmore.jpg/419px-Stephanie_Gilmore.jpg", <ide> "Gilmore", "Female", "Regular"); <ide> Surfer surfer16 = <ide> new Surfer( <ide> "http://a1.espncdn.com/photo/2013/0709/espnw_g_conlogue1_800.jpg", <ide> "Courtney Conlogue is the kind of California kid who was good at almost every sport she tried. She could " <ide> + "have pursued track or soccer, but her heart was in surfing from the moment her father put her on a " <del> + "board at age 4.\nNow the 20-year-old is a three-year veteran of the Association of Surfing Professionals," <add> + "board at age 4.\nNow the 20-year-old is a three-year veteran of the Association of Surfing " <add> + "Professionals," <ide> + " ranked fourth on the list of elite pros and set to compete for the Roxy Pro title in Biarritz, France. " <ide> + "She won an event in New Zealand in April, and is in the hunt for her first title as ASP women's world " <ide> + "champion. It's a challenge she relishes.", <del> "http://media.outsideonline.com/images/364*488/WCMDEV_151673_03_courtney_100.jpg", "Conlogue", "Female", "Regular"); <add> "http://media.outsideonline.com/images/364*488/WCMDEV_151673_03_courtney_100.jpg", "Conlogue", "Female", <add> "Regular"); <ide> Surfer surfer15 = <ide> new Surfer( <ide> "Sally Fitzgibbons", <ide> + "four times. Young featured in a number of important surf films of '60s and '70s including the classic " <ide> + "1973 surf movie Crystal Voyager and he also had a featured role as surfer Nick Naylor in the 1979 " <ide> + "Australian drama film Palm Beach", <del> "http://cdn2.coresites.mpora.com/surfeurope_new/wp-content/uploads/2013/09/lg_Nat_Young_Albert_Falzon.jpg", "Nat", "Male", "Goofy"); <add> "http://cdn2.coresites.mpora.com/surfeurope_new/wp-content/uploads/2013/09/lg_Nat_Young_Albert_Falzon.jpg", <add> "Nat", "Male", "Goofy"); <ide> Surfer surfer11 = <ide> new Surfer( <ide> "Josh Kerr", <ide> + "He is an ambassador for the National Breast Cancer Foundation. Julian's mother is a breast cancer " <ide> + "survivor and he was inspired to ride a pink board by close family friend and international cricketer " <ide> + "Matt Hayden that plays with a pink bat for the same cause", <del> "http://blog.stylesight.com/wp-content/uploads/2011/08/Nike_US_Open_of_Surfing_Julian_Wilson_Interview6.jpg", <del> "Julian", "Male", "Regular"); <add> "http://blog.stylesight.com/wp-content/uploads/2011/08/" <add> + "Nike_US_Open_of_Surfing_Julian_Wilson_Interview6.jpg", "Julian", "Male", "Regular"); <ide> Surfer surfer9 = <ide> new Surfer( <ide> "Kai Otton", <ide> + "the sport. In 2007 he also became the all-time leader in career event wins by winning " <ide> + "the Boost Mobile Pro event at Lower Trestles near San Clemente, California. " <ide> + "The previous record was held by Slater's childhood hero, 3-time world champion Tom Curren", <del> "http://www.athletepromotions.com/blog/wp-content/uploads/2013/08/kelly-slater.jpg", "Kelly", "Male", "Regular"); <add> "http://www.athletepromotions.com/blog/wp-content/uploads/2013/08/kelly-slater.jpg", "Kelly", "Male", <add> "Regular"); <ide> Surfer surfer4 = <ide> new Surfer( <ide> "Mick Fanning", <ide> SurferDB.add(surfer.getSlug(), new SurferFormData(surfer)); <ide> SurferDB.add(surfer2.getSlug(), new SurferFormData(surfer2)); <ide> SurferDB.add(surfer3.getSlug(), new SurferFormData(surfer3)); <del> SurferDB.add(surfer4.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer5.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer6.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer7.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer8.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer9.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer10.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer11.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer12.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer13.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer14.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer15.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer16.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer17.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer18.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer19.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer20.getSlug(), new SurferFormData(surfer)); <del> SurferDB.add(surfer21.getSlug(), new SurferFormData(surfer)); <add> SurferDB.add(surfer4.getSlug(), new SurferFormData(surfer4)); <add> SurferDB.add(surfer5.getSlug(), new SurferFormData(surfer5)); <add> SurferDB.add(surfer6.getSlug(), new SurferFormData(surfer6)); <add> SurferDB.add(surfer7.getSlug(), new SurferFormData(surfer7)); <add> SurferDB.add(surfer8.getSlug(), new SurferFormData(surfer8)); <add> SurferDB.add(surfer9.getSlug(), new SurferFormData(surfer9)); <add> SurferDB.add(surfer10.getSlug(), new SurferFormData(surfer10)); <add> SurferDB.add(surfer11.getSlug(), new SurferFormData(surfer11)); <add> SurferDB.add(surfer12.getSlug(), new SurferFormData(surfer12)); <add> SurferDB.add(surfer13.getSlug(), new SurferFormData(surfer13)); <add> SurferDB.add(surfer14.getSlug(), new SurferFormData(surfer14)); <add> SurferDB.add(surfer15.getSlug(), new SurferFormData(surfer15)); <add> SurferDB.add(surfer16.getSlug(), new SurferFormData(surfer16)); <add> SurferDB.add(surfer17.getSlug(), new SurferFormData(surfer17)); <add> SurferDB.add(surfer18.getSlug(), new SurferFormData(surfer18)); <add> SurferDB.add(surfer19.getSlug(), new SurferFormData(surfer19)); <add> SurferDB.add(surfer20.getSlug(), new SurferFormData(surfer20)); <add> SurferDB.add(surfer21.getSlug(), new SurferFormData(surfer21)); <add> } <ide> } <ide> <ide> }
Java
apache-2.0
error: pathspec 'languages/Natlab/src/natlab/toolkits/DependenceAnalysis/Profiler.java' did not match any file(s) known to git
e584516eccd373d5390a5a61acfcc244722ba341
1
bpilania/Comp621Project,bpilania/Comp621Project,bpilania/Comp621Project,bpilania/Comp621Project,bpilania/Comp621Project,bpilania/Comp621Project,bpilania/Comp621Project
package natlab.toolkits.DependenceAnalysis; import natlab.ast.ForStmt; import natlab.ast.Program; import natlab.ast.AssignStmt; import natlab.ast.*; import natlab.ast.ASTNode; import natlab.toolkits.analysis.ForVisitor; /* * Author:Amina Aslam * Date:11 Sep,2009 * Profiler class does the following. * 1.Changes the AST of input file to add additional code * 1.1.Open a .txt file. * 1.2.Extract features and their values and writes it to .txt file. * 1.3.Closes the file. */ public class Profiler { private Program prog; private ForStmt forNode; private NameExpr fidNameExpr; public Profiler() { fidNameExpr=new NameExpr(); } public Program getProg() { return prog; } public void setProg(Program prog) { this.prog = prog; } public ForStmt getForNode() { return forNode; } public void setForNode(ForStmt forNode) { this.forNode = forNode; } public void changeAST() { System.out.println(prog.dumpTreeAll()); /*AssignStmt fOpenAStmt=new AssignStmt(); //this is for opening up a file. fid=fopen('test.txt', 'a+'); Name fidName=new Name(); fidName.setID("fid"); fidNameExpr.setName(fidName); fOpenAStmt.setLHS(fidNameExpr);//this set the LHS of AssignStmt. ParameterizedExpr fOpenParaExpr=new ParameterizedExpr(); NameExpr fOpenNameExpr=new NameExpr(); Name fOpenName=new Name(); fOpenName.setID("fopen"); fOpenNameExpr.setName(fOpenName); fOpenParaExpr.setTarget(fOpenNameExpr); List fOpenList=new List(); StringLiteralExpr sExpr1=new StringLiteralExpr(); sExpr1.setValue("test.txt"); StringLiteralExpr sExpr2=new StringLiteralExpr(); sExpr2.setValue("a+"); fOpenList.insertChild(sExpr1, 0); fOpenList.insertChild(sExpr2, 1); fOpenParaExpr.setArgList(fOpenList); fOpenAStmt.setRHS(fOpenParaExpr); fOpenAStmt.setParent(prog.getChild(1)); //System.out.println(prog.getChild(1).getChild(0)); prog.getChild(1).insertChild(fOpenAStmt, 0); //System.out.println(prog.dumpTreeAll()); //System.out.println(prog.getPrettyPrinted()); traverseProgramNode(); //insert file closing node.This should be the last node in the program.. //fclose(fid) ExprStmt fCloseEStmt= new ExprStmt(); ParameterizedExpr fCloseParaExpr=new ParameterizedExpr(); NameExpr fCloseNameExpr=new NameExpr(); Name fCloseName=new Name(); fCloseName.setID("fclose"); fCloseNameExpr.setName(fCloseName); fCloseParaExpr.setTarget(fCloseNameExpr); List fCloseList=new List(); fCloseList.insertChild(fidNameExpr, 0); fCloseParaExpr.setArgList(fCloseList); fCloseEStmt.setExpr(fCloseParaExpr); //System.out.println(fCloseEStmt.dumpTreeAll());*/ } /* * This function traverses the program node and looks for ForLoop. */ private void traverseProgramNode() { int nNode=prog.getChild(1).getNumChild(); System.out.println(nNode); System.out.println(prog.dumpTreeAll()); for(int i=0;i<nNode;i++) { ASTNode node=prog.getChild(1).getChild(i); if(node instanceof ForStmt) { forNode=(ForStmt)node; insertFileWriteNode(i); }//end of if }//end of for System.out.println(prog.getPrettyPrinted()); }//end of function /* * This function insert a node which adds write to file functionality to MATLAB progam. */ private void insertFileWriteNode(int nodeNumber) { //ForVisitor forVisitor = new ForVisitor(); //prog.apply(forVisitor); //insert file writing node after the loop node. int sECount=0; int nECount=0; AssignStmt fPrintfAStmt=new AssignStmt(); //this is for inserting this code count=fprintf(fid,'%d',n,m); NameExpr count=new NameExpr(); Name n1=new Name(); n1.setID("count"); count.setName(n1); fPrintfAStmt.setLHS(count);//this set the LHS of AssignStmt. ParameterizedExpr fPrintfParaExpr=new ParameterizedExpr(); NameExpr fPrintfNameExpr=new NameExpr(); Name fPrintfName=new Name(); fPrintfName.setID("fprintf"); fPrintfNameExpr.setName(fPrintfName); fPrintfParaExpr.setTarget(fPrintfNameExpr); List fPrintfList=new List(); StringLiteralExpr sE1=new StringLiteralExpr(); sE1.setValue("%s%d\n"); sECount++; StringLiteralExpr sE2=new StringLiteralExpr(); sE2.setValue("LoopNumber"); sECount++; NameExpr lNoNameExpr=new NameExpr(); Name lNoName=new Name(); lNoName.setID(new Integer(nodeNumber).toString()); //writing loop no to file nECount++; NameExpr lBoundNameExpr=new NameExpr(); //writing lower bound of loop to file Name lBoundName=new Name(); lBoundName.setID(new Integer(((IntLiteralExpr)((RangeExpr)forNode.getAssignStmt().getLHS()).getLower()).getValue().getValue().intValue()).toString());//writing lower bound to file //lBoundName.setID("m"); nECount++; NameExpr uBoundNameExpr=new NameExpr();//writing upper bound of loop to file Name uBoundName=new Name(); uBoundName.setID(new Integer(((IntLiteralExpr)((RangeExpr)forNode.getAssignStmt().getLHS()).getUpper()).getValue().getValue().intValue()).toString());//writing upper bound to file //uBoundName.setID("n"); nECount++; fPrintfList.insertChild(fidNameExpr, 0); for(int i=0;i<sECount;i++) { fPrintfList.insertChild(sE1, i); fPrintfList.insertChild(sE2, i); } fPrintfList.insertChild(lBoundNameExpr, 1); fPrintfList.insertChild(uBoundNameExpr, 2); fPrintfParaExpr.setArgList(fPrintfList); fPrintfAStmt.setRHS(fPrintfParaExpr); //insert the node in the AST fPrintfAStmt.setParent(prog.getChild(1).getChild(nodeNumber)); //System.out.println(prog.getChild(1).getChild(0)); prog.getChild(1).insertChild(fPrintfAStmt, nodeNumber+1); System.out.println(fPrintfAStmt.dumpTreeAll()); } }
languages/Natlab/src/natlab/toolkits/DependenceAnalysis/Profiler.java
Added profiler code git-svn-id: a2312d33856acf09907bc700940b4d7cc158d4b3@1442 89b902b4-d83f-0410-b942-89f7a419ffdb
languages/Natlab/src/natlab/toolkits/DependenceAnalysis/Profiler.java
Added profiler code
<ide><path>anguages/Natlab/src/natlab/toolkits/DependenceAnalysis/Profiler.java <add>package natlab.toolkits.DependenceAnalysis; <add>import natlab.ast.ForStmt; <add>import natlab.ast.Program; <add>import natlab.ast.AssignStmt; <add>import natlab.ast.*; <add>import natlab.ast.ASTNode; <add>import natlab.toolkits.analysis.ForVisitor; <add> <add>/* <add> * Author:Amina Aslam <add> * Date:11 Sep,2009 <add> * Profiler class does the following. <add> * 1.Changes the AST of input file to add additional code <add> * 1.1.Open a .txt file. <add> * 1.2.Extract features and their values and writes it to .txt file. <add> * 1.3.Closes the file. <add> */ <add> <add>public class Profiler { <add> private Program prog; <add> private ForStmt forNode; <add> private NameExpr fidNameExpr; <add> public Profiler() <add> { <add> fidNameExpr=new NameExpr(); <add> } <add> public Program getProg() { <add> return prog; <add> } <add> public void setProg(Program prog) { <add> this.prog = prog; <add> } <add> public ForStmt getForNode() { <add> return forNode; <add> } <add> public void setForNode(ForStmt forNode) { <add> this.forNode = forNode; <add> } <add> public void changeAST() <add> { <add> System.out.println(prog.dumpTreeAll()); <add> /*AssignStmt fOpenAStmt=new AssignStmt(); //this is for opening up a file. fid=fopen('test.txt', 'a+'); <add> <add> Name fidName=new Name(); <add> fidName.setID("fid"); <add> fidNameExpr.setName(fidName); <add> fOpenAStmt.setLHS(fidNameExpr);//this set the LHS of AssignStmt. <add> ParameterizedExpr fOpenParaExpr=new ParameterizedExpr(); <add> NameExpr fOpenNameExpr=new NameExpr(); <add> Name fOpenName=new Name(); <add> fOpenName.setID("fopen"); <add> fOpenNameExpr.setName(fOpenName); <add> fOpenParaExpr.setTarget(fOpenNameExpr); <add> List fOpenList=new List(); <add> StringLiteralExpr sExpr1=new StringLiteralExpr(); <add> sExpr1.setValue("test.txt"); <add> StringLiteralExpr sExpr2=new StringLiteralExpr(); <add> sExpr2.setValue("a+"); <add> fOpenList.insertChild(sExpr1, 0); <add> fOpenList.insertChild(sExpr2, 1); <add> fOpenParaExpr.setArgList(fOpenList); <add> fOpenAStmt.setRHS(fOpenParaExpr); <add> <add> fOpenAStmt.setParent(prog.getChild(1)); <add> //System.out.println(prog.getChild(1).getChild(0)); <add> prog.getChild(1).insertChild(fOpenAStmt, 0); <add> //System.out.println(prog.dumpTreeAll()); <add> //System.out.println(prog.getPrettyPrinted()); <add> <add> traverseProgramNode(); <add> //insert file closing node.This should be the last node in the program.. //fclose(fid) <add> ExprStmt fCloseEStmt= new ExprStmt(); <add> ParameterizedExpr fCloseParaExpr=new ParameterizedExpr(); <add> NameExpr fCloseNameExpr=new NameExpr(); <add> Name fCloseName=new Name(); <add> fCloseName.setID("fclose"); <add> fCloseNameExpr.setName(fCloseName); <add> fCloseParaExpr.setTarget(fCloseNameExpr); <add> List fCloseList=new List(); <add> fCloseList.insertChild(fidNameExpr, 0); <add> fCloseParaExpr.setArgList(fCloseList); <add> fCloseEStmt.setExpr(fCloseParaExpr); <add> //System.out.println(fCloseEStmt.dumpTreeAll());*/ <add> } <add> <add> /* <add> * This function traverses the program node and looks for ForLoop. <add> */ <add> private void traverseProgramNode() <add> { <add> int nNode=prog.getChild(1).getNumChild(); <add> System.out.println(nNode); <add> System.out.println(prog.dumpTreeAll()); <add> for(int i=0;i<nNode;i++) <add> { <add> ASTNode node=prog.getChild(1).getChild(i); <add> if(node instanceof ForStmt) <add> { <add> forNode=(ForStmt)node; <add> insertFileWriteNode(i); <add> }//end of if <add> }//end of for <add> System.out.println(prog.getPrettyPrinted()); <add> }//end of function <add> <add> <add> /* <add> * This function insert a node which adds write to file functionality to MATLAB progam. <add> */ <add> private void insertFileWriteNode(int nodeNumber) <add> { <add> //ForVisitor forVisitor = new ForVisitor(); <add> //prog.apply(forVisitor); <add> //insert file writing node after the loop node. <add> int sECount=0; <add> int nECount=0; <add> AssignStmt fPrintfAStmt=new AssignStmt(); //this is for inserting this code count=fprintf(fid,'%d',n,m); <add> NameExpr count=new NameExpr(); <add> Name n1=new Name(); <add> n1.setID("count"); <add> count.setName(n1); <add> fPrintfAStmt.setLHS(count);//this set the LHS of AssignStmt. <add> <add> ParameterizedExpr fPrintfParaExpr=new ParameterizedExpr(); <add> NameExpr fPrintfNameExpr=new NameExpr(); <add> Name fPrintfName=new Name(); <add> fPrintfName.setID("fprintf"); <add> fPrintfNameExpr.setName(fPrintfName); <add> fPrintfParaExpr.setTarget(fPrintfNameExpr); <add> List fPrintfList=new List(); <add> StringLiteralExpr sE1=new StringLiteralExpr(); <add> sE1.setValue("%s%d\n"); <add> sECount++; <add> StringLiteralExpr sE2=new StringLiteralExpr(); <add> sE2.setValue("LoopNumber"); <add> sECount++; <add> <add> NameExpr lNoNameExpr=new NameExpr(); <add> Name lNoName=new Name(); <add> lNoName.setID(new Integer(nodeNumber).toString()); //writing loop no to file <add> nECount++; <add> <add> NameExpr lBoundNameExpr=new NameExpr(); //writing lower bound of loop to file <add> Name lBoundName=new Name(); <add> lBoundName.setID(new Integer(((IntLiteralExpr)((RangeExpr)forNode.getAssignStmt().getLHS()).getLower()).getValue().getValue().intValue()).toString());//writing lower bound to file <add> //lBoundName.setID("m"); <add> nECount++; <add> <add> NameExpr uBoundNameExpr=new NameExpr();//writing upper bound of loop to file <add> Name uBoundName=new Name(); <add> uBoundName.setID(new Integer(((IntLiteralExpr)((RangeExpr)forNode.getAssignStmt().getLHS()).getUpper()).getValue().getValue().intValue()).toString());//writing upper bound to file <add> //uBoundName.setID("n"); <add> nECount++; <add> <add> fPrintfList.insertChild(fidNameExpr, 0); <add> for(int i=0;i<sECount;i++) <add> { <add> fPrintfList.insertChild(sE1, i); <add> fPrintfList.insertChild(sE2, i); <add> } <add> fPrintfList.insertChild(lBoundNameExpr, 1); <add> fPrintfList.insertChild(uBoundNameExpr, 2); <add> fPrintfParaExpr.setArgList(fPrintfList); <add> fPrintfAStmt.setRHS(fPrintfParaExpr); <add> //insert the node in the AST <add> fPrintfAStmt.setParent(prog.getChild(1).getChild(nodeNumber)); <add> //System.out.println(prog.getChild(1).getChild(0)); <add> prog.getChild(1).insertChild(fPrintfAStmt, nodeNumber+1); <add> <add> System.out.println(fPrintfAStmt.dumpTreeAll()); <add> <add> <add> } <add> <add>}
Java
mit
a83f8ae280c37ba3e2512089697583c2d10bfbed
0
student-capture/student-capture
package studentcapture.submission; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Class: SubmissionResource * <p> * Author: Erik Moström * cs-user: erikm * Date: 5/17/16 */ @RestController @RequestMapping(value = "assignments/{assignmentID}/submissions/") public class SubmissionResource { @Autowired SubmissionDAO DAO; @RequestMapping(value = "{studentID}", method = RequestMethod.GET) public Submission getSubmission(@PathVariable("assignmentID") String assignment, @PathVariable("studentID") String studentID){ //TODO fix unity in DAO API return DAO.getSubmission(Integer.parseInt(assignment), Integer.parseInt(studentID)).get(); } @RequestMapping(method = RequestMethod.GET) public List<Submission> getAllSubmissions(@PathVariable("assignmentID") String assignment){ return DAO.getAllSubmissions(assignment).get(); } }
src/main/java/studentcapture/submission/SubmissionResource.java
package studentcapture.submission; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Class: SubmissionResource * <p> * Author: Erik Moström * cs-user: erikm * Date: 5/17/16 */ @RestController @RequestMapping(value = "assignments/{assignmentID}/submissions/") public class SubmissionResource { @Autowired SubmissionDAO DAO; @RequestMapping(value = "{submissionID}", method = RequestMethod.GET) public Submission getSubmission(@PathVariable("assignmentID") String assignment, @PathVariable("submissionID") String submission){ //TODO fix unity in DAO API return DAO.getSubmission(Integer.parseInt(assignment), Integer.parseInt(submission)).get(); } @RequestMapping(method = RequestMethod.GET) public List<Submission> getAllSubmissions(@PathVariable("assignmentID") String assignment){ return DAO.getAllSubmissions(assignment).get(); } }
Changes variablenames
src/main/java/studentcapture/submission/SubmissionResource.java
Changes variablenames
<ide><path>rc/main/java/studentcapture/submission/SubmissionResource.java <ide> @Autowired <ide> SubmissionDAO DAO; <ide> <del> @RequestMapping(value = "{submissionID}", method = RequestMethod.GET) <add> @RequestMapping(value = "{studentID}", method = RequestMethod.GET) <ide> public Submission getSubmission(@PathVariable("assignmentID") String assignment, <del> @PathVariable("submissionID") String submission){ <add> @PathVariable("studentID") String studentID){ <ide> //TODO fix unity in DAO API <del> return DAO.getSubmission(Integer.parseInt(assignment), Integer.parseInt(submission)).get(); <add> return DAO.getSubmission(Integer.parseInt(assignment), Integer.parseInt(studentID)).get(); <ide> } <ide> <ide> @RequestMapping(method = RequestMethod.GET)
JavaScript
agpl-3.0
f6ed98f255c9b8c52e25378fed22cf3095764f7f
0
adunning/zotero,rmzelle/zotero,gracile-fr/zotero,retorquere/zotero,rmzelle/zotero,fbennett/zotero,robamler/zotero,robamler/zotero,hoehnp/zotero,sendecomp/zotero,LinuxMercedes/zotero,egh/zotero,retorquere/zotero,retorquere/zotero,aurimasv/zotero,LinuxMercedes/zotero,gracile-fr/zotero,sendecomp/zotero,egh/zotero,robamler/zotero,LinuxMercedes/zotero,adunning/zotero,gracile-fr/zotero,hoehnp/zotero,egh/zotero,sendecomp/zotero,hoehnp/zotero,rmzelle/zotero,adunning/zotero
var items = {}; var selectArray = {}; // builds a list of DOIs function getDOIs(doc) { // TODO Detect DOIs more correctly. // The actual rules for DOIs are very lax-- but we're more strict. // Specifically, we should allow space characters, and all Unicode // characters except for control characters. Here, we're cheating // by not allowing ampersands, to fix an issue with getting DOIs // out of URLs. // Description at: http://www.doi.org/handbook_2000/appendix_1.html#A1-4 const DOIre = /\b(10\.[\w.]+\/[^\s&]+)\.?\b/igm; const DOIXPath = "//text()[contains(., '10.')]"; DOIre.lastMatch = 0; var DOIs = []; var node, m; var results = doc.evaluate(DOIXPath, doc, null, XPathResult.ANY_TYPE, null); while(node = results.iterateNext()) { while(m = DOIre.exec(node.nodeValue)) { var DOI = m[1]; if(DOI.substr(-1) == ")" && DOI.indexOf("(") == -1) { DOI = DOI.substr(0, DOI.length-1); } // only add new DOIs if(DOIs.indexOf(DOI) == -1) { DOIs.push(DOI); } } } return DOIs; } function detectWeb(doc, url) { const blacklistRe = /^https?:\/\/[^/]*google\.com/i; if(!blacklistRe.test(url)) { var DOIs = getDOIs(doc); if(DOIs.length) { return DOIs.length == 1 ? "journalArticle" : "multiple"; } } return false; } function retrieveNextDOI(DOIs, doc) { if(DOIs.length) { // retrieve DOI var DOI = DOIs.shift(); var translate = Zotero.loadTranslator("search"); translate.setTranslator("11645bd1-0420-45c1-badb-53fb41eeb753"); var item = {"itemType":"journalArticle", "DOI":DOI}; translate.setSearch(item); // don't save when item is done translate.setHandler("itemDone", function(translate, item) { item.repository = "CrossRef"; items[DOI] = item; selectArray[DOI] = item.title; }); translate.setHandler("done", function(translate) { retrieveNextDOI(DOIs, doc); }); translate.translate(); } else { // all DOIs retrieved now // check to see if there is more than one DOI var numDOIs = 0; for(var DOI in selectArray) { numDOIs++; if(numDOIs == 2) break; } if(numDOIs == 0) { throw "DOI Translator: could not find DOI"; } else if(numDOIs == 1) { // do we want to add URL of the page? items[DOI].url = doc.location.href; items[DOI].attachments = [{document:doc}]; items[DOI].complete(); } else { selectArray = Zotero.selectItems(selectArray); for(var DOI in selectArray) { items[DOI].complete(); } } Zotero.done(); } } function doWeb(doc, url) { var DOIs = getDOIs(doc); // retrieve full items asynchronously Zotero.wait(); retrieveNextDOI(DOIs, doc); } /** BEGIN TEST CASES **/ var testCases = [ { "type": "web", "url": "http://www.crossref.org/help/Content/01_About_DOIs/What_is_a_DOI.htm", "items": [ { "itemType": "journalArticle", "creators": [ { "creatorType": "author", "firstName": "J", "lastName": "Mou" } ], "notes": [], "tags": [], "seeAlso": [], "attachments": [ { "document": false } ], "publicationTitle": "Journal of Molecular Biology", "volume": "248", "ISSN": "00222836", "date": "1995-5-5", "pages": "507-512", "DOI": "10.1006/jmbi.1995.0238", "url": "http://www.crossref.org/help/Content/01_About_DOIs/What_is_a_DOI.htm", "title": "Atomic Force Microscopy of Cholera Toxin B-oligomers Bound to Bilayers of Biologically Relevant Lipids", "libraryCatalog": "CrossRef" } ] }, { "type": "web", "url": "http://blog.apastyle.org/apastyle/digital-object-identifier-doi/", "items": "multiple" } ] /** END TEST CASES **/
translators/DOI.js
{ "translatorID":"c159dcfe-8a53-4301-a499-30f6549c340d", "translatorType":4, "label":"DOI", "creator":"Simon Kornblith", "target":null, "minVersion":"1.0.10", "maxVersion":"", "priority":300, "browserSupport":"gcs", "inRepository":true, "lastUpdated":"2011-06-23 08:58:22" } var items = {}; var selectArray = {}; // builds a list of DOIs function getDOIs(doc) { // TODO Detect DOIs more correctly. // The actual rules for DOIs are very lax-- but we're more strict. // Specifically, we should allow space characters, and all Unicode // characters except for control characters. Here, we're cheating // by not allowing ampersands, to fix an issue with getting DOIs // out of URLs. // Description at: http://www.doi.org/handbook_2000/appendix_1.html#A1-4 const DOIre = /\b(10\.[\w.]+\/[^\s&]+)\.?\b/igm; const DOIXPath = "//text()[contains(., '10.')]"; DOIre.lastMatch = 0; var DOIs = []; var node, m; var results = doc.evaluate(DOIXPath, doc, null, XPathResult.ANY_TYPE, null); while(node = results.iterateNext()) { while(m = DOIre.exec(node.nodeValue)) { var DOI = m[1]; if(DOI.substr(-1) == ")" && DOI.indexOf("(") == -1) { DOI = DOI.substr(0, DOI.length-1); } // only add new DOIs if(DOIs.indexOf(DOI) == -1) { DOIs.push(DOI); } } } return DOIs; } function detectWeb(doc, url) { const blacklistRe = /^https?:\/\/[^/]*google\.com/i; if(!blacklistRe.test(url)) { var DOIs = getDOIs(doc); if(DOIs.length) { return DOIs.length == 1 ? "journalArticle" : "multiple"; } } return false; } function retrieveNextDOI(DOIs, doc) { if(DOIs.length) { // retrieve DOI var DOI = DOIs.shift(); var translate = Zotero.loadTranslator("search"); translate.setTranslator("11645bd1-0420-45c1-badb-53fb41eeb753"); var item = {"itemType":"journalArticle", "DOI":DOI}; translate.setSearch(item); // don't save when item is done translate.setHandler("itemDone", function(translate, item) { item.repository = "CrossRef"; items[DOI] = item; selectArray[DOI] = item.title; }); translate.setHandler("done", function(translate) { retrieveNextDOI(DOIs, doc); }); translate.translate(); } else { // all DOIs retrieved now // check to see if there is more than one DOI var numDOIs = 0; for(var DOI in selectArray) { numDOIs++; if(numDOIs == 2) break; } if(numDOIs == 0) { throw "DOI Translator: could not find DOI"; } else if(numDOIs == 1) { // do we want to add URL of the page? items[DOI].url = doc.location.href; items[DOI].attachments = [{document:doc}]; items[DOI].complete(); } else { selectArray = Zotero.selectItems(selectArray); for(var DOI in selectArray) { items[DOI].complete(); } } Zotero.done(); } } function doWeb(doc, url) { var DOIs = getDOIs(doc); // retrieve full items asynchronously Zotero.wait(); retrieveNextDOI(DOIs, doc); }
Also add tests to DOI translator
translators/DOI.js
Also add tests to DOI translator
<ide><path>ranslators/DOI.js <del>{ <del> "translatorID":"c159dcfe-8a53-4301-a499-30f6549c340d", <del> "translatorType":4, <del> "label":"DOI", <del> "creator":"Simon Kornblith", <del> "target":null, <del> "minVersion":"1.0.10", <del> "maxVersion":"", <del> "priority":300, <del> "browserSupport":"gcs", <del> "inRepository":true, <del> "lastUpdated":"2011-06-23 08:58:22" <del>} <del> <ide> var items = {}; <ide> var selectArray = {}; <ide> <ide> Zotero.wait(); <ide> retrieveNextDOI(DOIs, doc); <ide> } <add> <add> <add>/** BEGIN TEST CASES **/ <add>var testCases = [ <add> { <add> "type": "web", <add> "url": "http://www.crossref.org/help/Content/01_About_DOIs/What_is_a_DOI.htm", <add> "items": [ <add> { <add> "itemType": "journalArticle", <add> "creators": [ <add> { <add> "creatorType": "author", <add> "firstName": "J", <add> "lastName": "Mou" <add> } <add> ], <add> "notes": [], <add> "tags": [], <add> "seeAlso": [], <add> "attachments": [ <add> { <add> "document": false <add> } <add> ], <add> "publicationTitle": "Journal of Molecular Biology", <add> "volume": "248", <add> "ISSN": "00222836", <add> "date": "1995-5-5", <add> "pages": "507-512", <add> "DOI": "10.1006/jmbi.1995.0238", <add> "url": "http://www.crossref.org/help/Content/01_About_DOIs/What_is_a_DOI.htm", <add> "title": "Atomic Force Microscopy of Cholera Toxin B-oligomers Bound to Bilayers of Biologically Relevant Lipids", <add> "libraryCatalog": "CrossRef" <add> } <add> ] <add> }, <add> { <add> "type": "web", <add> "url": "http://blog.apastyle.org/apastyle/digital-object-identifier-doi/", <add> "items": "multiple" <add> } <add>] <add>/** END TEST CASES **/
JavaScript
mit
0075f19b176ed6963ad9b664374b0805b025bb5f
0
ArthurSeaton/Quink,ArthurSeaton/Quink,ArthurSeaton/Quink,ArthurSeaton/Quink
/** * Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland. * * See the file license.txt for copying permission. */ define([ 'Underscore', 'jquery', 'ui/Mask', 'util/Event', 'util/Env', 'util/ViewportRelative' ], function (_, $, Mask, Event, Env, ViewportRelative) { 'use strict'; var menuTpl; var PopupMenu = function (menuDef, callback, isMultiSelect) { this.menuDef = menuDef; this.callback = callback; this.isMultiSelect = isMultiSelect; this.hiddenCss = isMultiSelect ? 'qk_invisible' : 'qk_hidden'; this.addCloseDef(this.menuDef, this.isMultiSelect); }; PopupMenu.prototype.MENU_ITEM_SELECTOR = '.qk_popup_menu_item'; PopupMenu.prototype.addCloseDef = function (menuDef, isMultiSelect) { menuDef.push({ label: isMultiSelect ? 'close' : 'cancel', value: 'close' }); }; PopupMenu.prototype.updateState = function (markup, state) { markup.find('.qk_popup_menu_item[id="' + state + '"] .qk_popup_menu_item_state').toggleClass(this.hiddenCss); }; PopupMenu.prototype.onSelect = function (event) { var menuItem = $(event.target).closest(this.MENU_ITEM_SELECTOR), id = menuItem.attr('id'), selectedDef = _.find(this.menuDef, function (def) { return def.value === id; }); event.preventDefault(); // stops the menu being focused if (this.isMultiSelect && selectedDef.value !== 'close') { this.updateState(this.menu, selectedDef.value); } this.callback(selectedDef, this); if (!this.isMultiSelect || selectedDef.value === 'close') { this.hide(); } }; // PopupMenu.prototype.downloadTpl = function () { // $.get(Env.resource('menu.tpl')).done(function (tpl) { // this.menuTpl = _.template(tpl); // }.bind(this)); // }; PopupMenu.prototype.applyState = function (markup, menuState) { var hiddenCss = this.hiddenCss; markup.find('.qk_popup_menu_item').each(function () { var itemEl = $(this), stateEl = itemEl.find('.qk_popup_menu_item_state'), id = itemEl.attr('id'), func = menuState.indexOf(id) >= 0 ? stateEl.removeClass : stateEl.addClass; func.call(stateEl, hiddenCss); }); }; PopupMenu.prototype.createMenu = function (def) { var markup = $(menuTpl({options: def})); markup.on(Event.eventName('start'), this.MENU_ITEM_SELECTOR, this.onSelect.bind(this)); markup.find('.qk_popup_menu_item_state').addClass(this.hiddenCss); return markup; }; PopupMenu.prototype.show = function (x, y, menuState) { var menu = this.menu, created; if (!menu) { this.menu = this.createMenu(this.menuDef); menu = this.menu; this.mask = Mask.create(this.hide.bind(this), 0); menu.appendTo('body'); this.vpMenu = ViewportRelative.create(menu, { top: y }); created = true; } if (this.isMultiSelect) { this.applyState(menu, menuState); } this.mask.show(); menu.css({ top: y, left: x }); this.vpMenu.adjust(); menu.removeClass('qk_hidden'); }; PopupMenu.prototype.hide = function () { this.menu.addClass('qk_hidden'); this.mask.hide(); }; function create(menuDef, callback, isMultiSelect) { return new PopupMenu(menuDef, callback, isMultiSelect); } function init() { return $.get(Env.resource('menu.tpl')).done(function (tpl) { menuTpl = _.template(tpl); }); } return { create: create, init: init }; });
quink/js/ui/PopupMenu.js
/** * Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland. * * See the file license.txt for copying permission. */ define([ 'Underscore', 'jquery', 'ui/Mask', 'util/Event', 'util/Env', 'util/ViewportRelative' ], function (_, $, Mask, Event, Env, ViewportRelative) { 'use strict'; var menuTpl; var PopupMenu = function (menuDef, callback, isMultiSelect) { this.menuDef = menuDef; this.callback = callback; this.isMultiSelect = isMultiSelect; this.hiddenCss = isMultiSelect ? 'qk_invisible' : 'qk_hidden'; }; PopupMenu.prototype.MENU_ITEM_SELECTOR = '.qk_popup_menu_item'; PopupMenu.prototype.updateState = function (markup, state) { markup.find('.qk_popup_menu_item[id="' + state + '"] .qk_popup_menu_item_state').toggleClass(this.hiddenCss); }; PopupMenu.prototype.onSelect = function (event) { var menuItem = $(event.target).closest(this.MENU_ITEM_SELECTOR), id = menuItem.attr('id'), selectedDef = _.find(this.menuDef, function (def) { return def.value === id; }); event.preventDefault(); // stops the menu being focused if (this.isMultiSelect && selectedDef.value !== 'close') { this.updateState(this.menu, selectedDef.value); } this.callback(selectedDef, this); if (!this.isMultiSelect || selectedDef.value === 'close') { this.hide(); } }; // PopupMenu.prototype.downloadTpl = function () { // $.get(Env.resource('menu.tpl')).done(function (tpl) { // this.menuTpl = _.template(tpl); // }.bind(this)); // }; PopupMenu.prototype.applyState = function (markup, menuState) { var hiddenCss = this.hiddenCss; markup.find('.qk_popup_menu_item').each(function () { var itemEl = $(this), stateEl = itemEl.find('.qk_popup_menu_item_state'), id = itemEl.attr('id'), func = menuState.indexOf(id) >= 0 ? stateEl.removeClass : stateEl.addClass; func.call(stateEl, hiddenCss); }); }; PopupMenu.prototype.createMenu = function (def) { var markup = $(menuTpl({options: def})); markup.on(Event.eventName('start'), this.MENU_ITEM_SELECTOR, this.onSelect.bind(this)); markup.find('.qk_popup_menu_item_state').addClass(this.hiddenCss); return markup; }; PopupMenu.prototype.show = function (x, y, menuState) { var menu = this.menu, created; if (!menu) { this.menu = this.createMenu(this.menuDef); menu = this.menu; this.mask = Mask.create(this.hide.bind(this), 0); menu.appendTo('body'); this.vpMenu = ViewportRelative.create(menu, { top: y }); created = true; } if (this.isMultiSelect) { this.applyState(menu, menuState); } this.mask.show(); menu.css({ top: y, left: x }); this.vpMenu.adjust(); menu.removeClass('qk_hidden'); }; PopupMenu.prototype.hide = function () { this.menu.addClass('qk_hidden'); this.mask.hide(); }; function create(menuDef, callback, isMultiSelect) { return new PopupMenu(menuDef, callback, isMultiSelect); } function init() { return $.get(Env.resource('menu.tpl')).done(function (tpl) { menuTpl = _.template(tpl); }); } return { create: create, init: init }; });
Make the menu add the close option.
quink/js/ui/PopupMenu.js
Make the menu add the close option.
<ide><path>uink/js/ui/PopupMenu.js <ide> this.callback = callback; <ide> this.isMultiSelect = isMultiSelect; <ide> this.hiddenCss = isMultiSelect ? 'qk_invisible' : 'qk_hidden'; <add> this.addCloseDef(this.menuDef, this.isMultiSelect); <ide> }; <ide> <ide> PopupMenu.prototype.MENU_ITEM_SELECTOR = '.qk_popup_menu_item'; <add> <add> PopupMenu.prototype.addCloseDef = function (menuDef, isMultiSelect) { <add> menuDef.push({ <add> label: isMultiSelect ? 'close' : 'cancel', <add> value: 'close' <add> }); <add> }; <ide> <ide> PopupMenu.prototype.updateState = function (markup, state) { <ide> markup.find('.qk_popup_menu_item[id="' + state + '"] .qk_popup_menu_item_state').toggleClass(this.hiddenCss);
Java
apache-2.0
dc4c18abec02e8f4b3295c4c8e4bfd07a8ce7123
0
realityforge/gwt-websockets,realityforge/gwt-websockets
package org.realityforge.gwt.websockets.client; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.typedarrays.shared.ArrayBuffer; import com.google.gwt.typedarrays.shared.ArrayBufferView; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * The browser-based WebSocket implementation. */ final class Html5WebSocket extends WebSocket { public static native boolean isSupported() /*-{ return !!$wnd.WebSocket || !!$wnd.MozWebSocket; }-*/; private WebSocketImpl _webSocket; static class Factory implements WebSocket.Factory { @Override public WebSocket newWebSocket() { return new Html5WebSocket(); } } /** * {@inheritDoc} */ @Override public void close() throws IllegalStateException { checkConnected(); _webSocket.close(); socketClosed(); } /** * {@inheritDoc} */ @Override public void close( final short code, @Nullable final String reason ) throws IllegalStateException { checkConnected(); _webSocket.close( code, reason ); socketClosed(); } private void socketClosed() { _webSocket = null; } /** * {@inheritDoc} */ @Override public void connect( @Nonnull final String server, @Nonnull final String... protocols ) throws IllegalStateException { if ( null != _webSocket ) { throw new IllegalStateException( "WebSocket already connected" ); } _webSocket = WebSocketImpl.create( this, server, protocols ); setBinaryType( BinaryType.ARRAYBUFFER ); } /** * {@inheritDoc} */ @Override public boolean isConnected() throws IllegalStateException { return null != _webSocket; } /** * {@inheritDoc} */ @Override public final int getBufferedAmount() throws IllegalStateException { checkConnected(); return _webSocket.getBufferedAmount(); } /** * {@inheritDoc} */ @Override public String getProtocol() throws IllegalStateException { checkConnected(); return _webSocket.getProtocol(); } /** * {@inheritDoc} */ @Override public String getURL() throws IllegalStateException { checkConnected(); return _webSocket.getURL(); } /** * {@inheritDoc} */ @Override public String getExtensions() throws IllegalStateException { checkConnected(); return _webSocket.getExtensions(); } /** * {@inheritDoc} */ @Override public final void send( @Nonnull String data ) throws IllegalStateException { checkConnected(); _webSocket.send( data ); } /** * {@inheritDoc} */ @Override public void send( @Nonnull final ArrayBufferView data ) throws IllegalStateException { checkConnected(); _webSocket.send( data ); } /** * {@inheritDoc} */ @Override public void send( @Nonnull final ArrayBuffer data ) throws IllegalStateException { checkConnected(); _webSocket.send( data ); } /** * {@inheritDoc} */ @Override public final ReadyState getReadyState() { if ( null == _webSocket ) { return ReadyState.CLOSED; } else { return ReadyState.values()[ _webSocket.getReadyState() ]; } } /** * {@inheritDoc} */ @Override public void setBinaryType( @Nonnull final BinaryType binaryType ) throws IllegalStateException { checkConnected(); _webSocket.setBinaryType( binaryType.name().toLowerCase() ); } /** * {@inheritDoc} */ @Override public BinaryType getBinaryType() throws IllegalStateException { checkConnected(); return BinaryType.valueOf( _webSocket.getBinaryType().toUpperCase() ); } /** * Make sure the implementation is present and if not raise an IllegalStateException. */ private void checkConnected() throws IllegalStateException { if ( null == _webSocket ) { throw new IllegalStateException( "WebSocket not connected" ); } } /** * The underlying WebSocket implementation. */ private final static class WebSocketImpl extends JavaScriptObject { static native WebSocketImpl create( WebSocket client, String server, String... protocols ) /*-{ var ws = (!!$wnd.WebSocket) ? new $wnd.WebSocket( server, protocols ) : $wnd.MozWebSocket( server, protocols ); ws.onopen = $entry( function () { [email protected]::onOpen()(); } ); ws.onerror = $entry( function () { [email protected]::onError()(); } ); ws.onmessage = $entry( function ( response ) { if ( typeof(response.data) === 'string' ) { [email protected]::onMessage(Ljava/lang/String;)( response.data ); } else { [email protected]::onMessage(Lcom/google/gwt/typedarrays/shared/ArrayBuffer;)( response.data ); } } ); ws.onclose = $entry( function ( event ) { [email protected]::onClose(ZILjava/lang/String;)( event.wasClean, event.code, event.reason ); [email protected]::socketClosed()(); } ); return ws; }-*/; protected WebSocketImpl() { } native int getBufferedAmount() /*-{ return this.bufferedAmount; }-*/; native int getReadyState() /*-{ return this.readyState; }-*/; native void close() /*-{ this.close(); }-*/; native void close( int code, String reason ) /*-{ this.close( code, reason ); }-*/; native void send( String data ) /*-{ this.send( data ); }-*/; native void send( ArrayBuffer data ) /*-{ this.send( data ); }-*/; native void send( ArrayBufferView data ) /*-{ this.send( data ); }-*/; native String getBinaryType() /*-{ return this.binaryType; }-*/; native void setBinaryType( String binaryType ) /*-{ this.binaryType = binaryType; }-*/; native String getURL() /*-{ return this.url; }-*/; native String getExtensions() /*-{ return this.extensions; }-*/; native String getProtocol() /*-{ return this.protocol; }-*/; } }
src/main/java/org/realityforge/gwt/websockets/client/Html5WebSocket.java
package org.realityforge.gwt.websockets.client; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.typedarrays.shared.ArrayBuffer; import com.google.gwt.typedarrays.shared.ArrayBufferView; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * The browser-based WebSocket implementation. */ final class Html5WebSocket extends WebSocket { public static native boolean isSupported() /*-{ return !!$wnd.WebSocket || !!$wnd.MozWebSocket; }-*/; private WebSocketImpl _webSocket; static class Factory implements WebSocket.Factory { @Override public WebSocket newWebSocket() { return new Html5WebSocket(); } } /** * {@inheritDoc} */ @Override public void close() throws IllegalStateException { checkConnected(); _webSocket.close(); socketClosed(); } /** * {@inheritDoc} */ @Override public void close( final short code, @Nullable final String reason ) throws IllegalStateException { checkConnected(); _webSocket.close( code, reason ); socketClosed(); } private void socketClosed() { _webSocket = null; } /** * {@inheritDoc} */ @Override public void connect( @Nonnull final String server, @Nonnull final String... protocols ) throws IllegalStateException { if ( null != _webSocket ) { throw new IllegalStateException( "WebSocket already connected" ); } _webSocket = WebSocketImpl.create( this, server, protocols ); setBinaryType( BinaryType.ARRAYBUFFER ); } /** * {@inheritDoc} */ @Override public boolean isConnected() throws IllegalStateException { return null != _webSocket; } /** * {@inheritDoc} */ @Override public final int getBufferedAmount() throws IllegalStateException { checkConnected(); return _webSocket.getBufferedAmount(); } /** * {@inheritDoc} */ @Override public String getProtocol() throws IllegalStateException { checkConnected(); return _webSocket.getProtocol(); } /** * {@inheritDoc} */ @Override public String getURL() throws IllegalStateException { checkConnected(); return _webSocket.getURL(); } /** * {@inheritDoc} */ @Override public String getExtensions() throws IllegalStateException { checkConnected(); return _webSocket.getExtensions(); } /** * {@inheritDoc} */ @Override public final void send( @Nonnull String data ) throws IllegalStateException { checkConnected(); _webSocket.send( data ); } /** * {@inheritDoc} */ @Override public void send( @Nonnull final ArrayBufferView data ) throws IllegalStateException { checkConnected(); _webSocket.send( data ); } /** * {@inheritDoc} */ @Override public void send( @Nonnull final ArrayBuffer data ) throws IllegalStateException { checkConnected(); _webSocket.send( data ); } /** * {@inheritDoc} */ @Override public final ReadyState getReadyState() { if ( null == _webSocket ) { return ReadyState.CLOSED; } else { return ReadyState.values()[ _webSocket.getReadyState() ]; } } /** * {@inheritDoc} */ @Override public void setBinaryType( @Nonnull final BinaryType binaryType ) throws IllegalStateException { checkConnected(); _webSocket.setBinaryType( binaryType.name().toLowerCase() ); } /** * {@inheritDoc} */ @Override public BinaryType getBinaryType() throws IllegalStateException { checkConnected(); return BinaryType.valueOf( _webSocket.getBinaryType().toUpperCase() ); } /** * Make sure the implementation is present and if not raise an IllegalStateException. */ private void checkConnected() throws IllegalStateException { if ( null == _webSocket ) { throw new IllegalStateException( "WebSocket not connected" ); } } /** * The underlying WebSocket implementation. */ private final static class WebSocketImpl extends JavaScriptObject { static native WebSocketImpl create( WebSocket client, String server, String... protocols ) /*-{ var ws = (!!$wnd.WebSocket) ? new $wnd.WebSocket( server, protocols ) : $wnd.MozWebSocket( server, protocols ); ws.onopen = $entry( function () { [email protected]::onOpen()(); } ); ws.onerror = $entry( function () { [email protected]::onError()(); } ); ws.onmessage = $entry( function ( response ) { if ( typeof(response.data) == 'string' ) { [email protected]::onMessage(Ljava/lang/String;)( response.data ); } else { [email protected]::onMessage(Lcom/google/gwt/typedarrays/shared/ArrayBuffer;)( response.data ); } } ); ws.onclose = $entry( function ( event ) { [email protected]::onClose(ZILjava/lang/String;)( event.wasClean, event.code, event.reason ); [email protected]::socketClosed()(); } ); return ws; }-*/; protected WebSocketImpl() { } native int getBufferedAmount() /*-{ return this.bufferedAmount; }-*/; native int getReadyState() /*-{ return this.readyState; }-*/; native void close() /*-{ this.close(); }-*/; native void close( int code, String reason ) /*-{ this.close( code, reason ); }-*/; native void send( String data ) /*-{ this.send( data ); }-*/; native void send( ArrayBuffer data ) /*-{ this.send( data ); }-*/; native void send( ArrayBufferView data ) /*-{ this.send( data ); }-*/; native String getBinaryType() /*-{ return this.binaryType; }-*/; native void setBinaryType( String binaryType ) /*-{ this.binaryType = binaryType; }-*/; native String getURL() /*-{ return this.url; }-*/; native String getExtensions() /*-{ return this.extensions; }-*/; native String getProtocol() /*-{ return this.protocol; }-*/; } }
Avoid potential type coercion problem
src/main/java/org/realityforge/gwt/websockets/client/Html5WebSocket.java
Avoid potential type coercion problem
<ide><path>rc/main/java/org/realityforge/gwt/websockets/client/Html5WebSocket.java <ide> } ); <ide> ws.onmessage = $entry( function ( response ) <ide> { <del> if ( typeof(response.data) == 'string' ) <add> if ( typeof(response.data) === 'string' ) <ide> { <ide> [email protected]::onMessage(Ljava/lang/String;)( response.data ); <ide> }
Java
mit
d51992f4698fdb4d9d2df33857e6cb85741bceb9
0
sake/bouncycastle-java
package org.bouncycastle.bcpg; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * reader for PGP objects */ public class BCPGInputStream extends InputStream implements PacketTags { InputStream in; boolean next = false; int nextB; public BCPGInputStream( InputStream in) { this.in = in; } public int available() throws IOException { return in.available(); } public int read() throws IOException { if (next) { next = false; return nextB; } else { return in.read(); } } public int read( byte[] buf, int off, int len) throws IOException { if (len == 0) { return 0; } if (!next) { return in.read(buf, off, len); } // We have next byte waiting, so return it if (nextB < 0) { return -1; // EOF } buf[off] = (byte)nextB; // May throw NullPointerException... next = false; // ...so only set this afterwards return 1; } public void readFully( byte[] buf, int off, int len) throws IOException { // // make sure we pick up nextB if set. // if (len > 0) { int b = this.read(); if (b < 0) { throw new EOFException(); } buf[off] = (byte)b; off++; len--; } while (len > 0) { int l = in.read(buf, off, len); if (l < 0) { throw new EOFException(); } off += l; len -= l; } } public void readFully( byte[] buf) throws IOException { readFully(buf, 0, buf.length); } /** * returns the next packet tag in the stream. * * @return the tag number. * * @throws IOException */ public int nextPacketTag() throws IOException { if (!next) { try { nextB = in.read(); } catch (EOFException e) { nextB = -1; } } next = true; if (nextB >= 0) { if ((nextB & 0x40) != 0) // new { return (nextB & 0x3f); } else // old { return ((nextB & 0x3f) >> 2); } } return nextB; } public Packet readPacket() throws IOException { int hdr = this.read(); if (hdr < 0) { return null; } if ((hdr & 0x80) == 0) { throw new IOException("invalid header encountered"); } boolean newPacket = (hdr & 0x40) != 0; int tag = 0; int bodyLen = 0; boolean partial = false; if (newPacket) { tag = hdr & 0x3f; int l = this.read(); if (l < 192) { bodyLen = l; } else if (l <= 223) { int b = in.read(); bodyLen = ((l - 192) << 8) + (b) + 192; } else if (l == 255) { bodyLen = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); } else { partial = true; bodyLen = 1 << (l & 0x1f); } } else { int lengthType = hdr & 0x3; tag = (hdr & 0x3f) >> 2; switch (lengthType) { case 0: bodyLen = this.read(); break; case 1: bodyLen = (this.read() << 8) | this.read(); break; case 2: bodyLen = (this.read() << 24) | (this.read() << 16) | (this.read() << 8) | this.read(); break; case 3: partial = true; break; default: throw new IOException("unknown length type encountered"); } } BCPGInputStream objStream; if (bodyLen == 0 && partial) { objStream = this; } else { objStream = new BCPGInputStream(new PartialInputStream(this, partial, bodyLen)); } switch (tag) { case RESERVED: return new InputStreamPacket(objStream); case PUBLIC_KEY_ENC_SESSION: return new PublicKeyEncSessionPacket(objStream); case SIGNATURE: return new SignaturePacket(objStream); case SYMMETRIC_KEY_ENC_SESSION: return new SymmetricKeyEncSessionPacket(objStream); case ONE_PASS_SIGNATURE: return new OnePassSignaturePacket(objStream); case SECRET_KEY: return new SecretKeyPacket(objStream); case PUBLIC_KEY: return new PublicKeyPacket(objStream); case SECRET_SUBKEY: return new SecretSubkeyPacket(objStream); case COMPRESSED_DATA: return new CompressedDataPacket(objStream); case SYMMETRIC_KEY_ENC: return new SymmetricEncDataPacket(objStream); case MARKER: return new MarkerPacket(objStream); case LITERAL_DATA: return new LiteralDataPacket(objStream); case TRUST: return new TrustPacket(objStream); case USER_ID: return new UserIDPacket(objStream); case USER_ATTRIBUTE: return new UserAttributePacket(objStream); case PUBLIC_SUBKEY: return new PublicSubkeyPacket(objStream); case SYM_ENC_INTEGRITY_PRO: return new SymmetricEncIntegrityPacket(objStream); case MOD_DETECTION_CODE: return new ModDetectionCodePacket(objStream); case EXPERIMENTAL_1: case EXPERIMENTAL_2: case EXPERIMENTAL_3: case EXPERIMENTAL_4: return new ExperimentalPacket(tag, objStream); default: throw new IOException("unknown packet type encountered: " + tag); } } public void close() throws IOException { in.close(); } /** * a stream that overlays our input stream, allowing the user to only read a segment of it. * * NB: dataLength will be zero if the segment length is in the upper range above 2**31. */ private static class PartialInputStream extends InputStream { private BCPGInputStream in; private boolean partial; private int dataLength; PartialInputStream( BCPGInputStream in, boolean partial, int dataLength) { this.in = in; this.partial = partial; this.dataLength = dataLength; } public int available() throws IOException { int avail = in.available(); if (avail <= dataLength || dataLength < 0) { return avail; } else { if (partial && dataLength == 0) { return 1; } return dataLength; } } private int loadDataLength() throws IOException { int l = in.read(); if (l < 0) { return -1; } partial = false; if (l < 192) { dataLength = l; } else if (l <= 223) { dataLength = ((l - 192) << 8) + (in.read()) + 192; } else if (l == 255) { dataLength = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); } else { partial = true; dataLength = 1 << (l & 0x1f); } return dataLength; } public int read(byte[] buf, int offset, int len) throws IOException { if (dataLength != 0) { int readLen = (dataLength > len || dataLength < 0) ? len : dataLength; readLen = in.read(buf, offset, readLen); dataLength -= readLen; return readLen; } else if (partial) { if (loadDataLength() < 0) { return -1; } return this.read(buf, offset, len); } return -1; } public int read() throws IOException { if (dataLength != 0) { dataLength--; return in.read(); } else if (partial) { if (loadDataLength() < 0) { return -1; } return this.read(); } return -1; } } }
src/org/bouncycastle/bcpg/BCPGInputStream.java
package org.bouncycastle.bcpg; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * reader for PGP objects */ public class BCPGInputStream extends InputStream implements PacketTags { InputStream in; boolean next = false; int nextB; public BCPGInputStream( InputStream in) { this.in = in; } public int available() throws IOException { return in.available(); } public int read() throws IOException { if (next) { next = false; return nextB; } else { return in.read(); } } public int read( byte[] buf, int off, int len) throws IOException { if (len == 0) { return 0; } if (!next) { return in.read(buf, off, len); } // We have next byte waiting, so return it if (nextB < 0) { return -1; // EOF } buf[off] = (byte)nextB; // May throw NullPointerException... next = false; // ...so only set this afterwards return 1; } public void readFully( byte[] buf, int off, int len) throws IOException { // // make sure we pick up nextB if set. // if (len > 0) { int b = this.read(); if (b < 0) { throw new EOFException(); } buf[off] = (byte)b; off++; len--; } while (len > 0) { int l = in.read(buf, off, len); if (l < 0) { throw new EOFException(); } off += l; len -= l; } } public void readFully( byte[] buf) throws IOException { readFully(buf, 0, buf.length); } /** * returns the next packet tag in the stream. * * @return the tag number. * * @throws IOException */ public int nextPacketTag() throws IOException { if (!next) { try { nextB = in.read(); } catch (EOFException e) { nextB = -1; } } next = true; if (nextB >= 0) { if ((nextB & 0x40) != 0) // new { return (nextB & 0x3f); } else // old { return ((nextB & 0x3f) >> 2); } } return nextB; } public Packet readPacket() throws IOException { int hdr = this.read(); if (hdr < 0) { return null; } if ((hdr & 0x80) == 0) { throw new IOException("invalid header encountered"); } boolean newPacket = (hdr & 0x40) != 0; int tag = 0; int bodyLen = 0; boolean partial = false; if (newPacket) { tag = hdr & 0x3f; int l = this.read(); if (l < 192) { bodyLen = l; } else if (l <= 223) { int b = in.read(); bodyLen = ((l - 192) << 8) + (b) + 192; } else if (l == 255) { bodyLen = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); } else { partial = true; bodyLen = 1 << (l & 0x1f); } } else { int lengthType = hdr & 0x3; tag = (hdr & 0x3f) >> 2; switch (lengthType) { case 0: bodyLen = this.read(); break; case 1: bodyLen = (this.read() << 8) | this.read(); break; case 2: bodyLen = (this.read() << 24) | (this.read() << 16) | (this.read() << 8) | this.read(); break; case 3: partial = true; break; default: throw new IOException("unknown length type encountered"); } } BCPGInputStream objStream; if (bodyLen == 0 && partial) { objStream = this; } else { objStream = new BCPGInputStream(new PartialInputStream(this, partial, bodyLen)); } switch (tag) { case RESERVED: return new InputStreamPacket(objStream); case PUBLIC_KEY_ENC_SESSION: return new PublicKeyEncSessionPacket(objStream); case SIGNATURE: return new SignaturePacket(objStream); case SYMMETRIC_KEY_ENC_SESSION: return new SymmetricKeyEncSessionPacket(objStream); case ONE_PASS_SIGNATURE: return new OnePassSignaturePacket(objStream); case SECRET_KEY: return new SecretKeyPacket(objStream); case PUBLIC_KEY: return new PublicKeyPacket(objStream); case SECRET_SUBKEY: return new SecretSubkeyPacket(objStream); case COMPRESSED_DATA: return new CompressedDataPacket(objStream); case SYMMETRIC_KEY_ENC: return new SymmetricEncDataPacket(objStream); case MARKER: return new MarkerPacket(objStream); case LITERAL_DATA: return new LiteralDataPacket(objStream); case TRUST: return new TrustPacket(objStream); case USER_ID: return new UserIDPacket(objStream); case USER_ATTRIBUTE: return new UserAttributePacket(objStream); case PUBLIC_SUBKEY: return new PublicSubkeyPacket(objStream); case SYM_ENC_INTEGRITY_PRO: return new SymmetricEncIntegrityPacket(objStream); case MOD_DETECTION_CODE: return new ModDetectionCodePacket(objStream); case EXPERIMENTAL_1: case EXPERIMENTAL_2: case EXPERIMENTAL_3: case EXPERIMENTAL_4: return new ExperimentalPacket(tag, objStream); default: throw new IOException("unknown packet type encountered: " + tag); } } public void close() throws IOException { in.close(); } /** * a stream that overlays our input stream, allowing the user to only read a segment of it. */ private static class PartialInputStream extends InputStream { private BCPGInputStream in; private boolean partial; private int dataLength; PartialInputStream( BCPGInputStream in, boolean partial, int dataLength) { this.in = in; this.partial = partial; this.dataLength = dataLength; } public int available() throws IOException { int avail = in.available(); if (avail <= dataLength || dataLength < 0) { return avail; } else { if (partial && dataLength == 0) { return 1; } return dataLength; } } private int loadDataLength() throws IOException { int l = in.read(); if (l < 0) { return -1; } partial = false; if (l < 192) { dataLength = l; } else if (l <= 223) { dataLength = ((l - 192) << 8) + (in.read()) + 192; } else if (l == 255) { dataLength = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read(); } else { partial = true; dataLength = 1 << (l & 0x1f); } return dataLength; } public int read(byte[] buf, int offset, int len) throws IOException { if (dataLength != 0) { int readLen = (dataLength > len || dataLength < 0) ? len : dataLength; readLen = in.read(buf, offset, readLen); dataLength -= readLen; return readLen; } else if (partial) { if (loadDataLength() < 0) { return -1; } return this.read(buf, offset, len); } return -1; } public int read() throws IOException { if (dataLength != 0) { dataLength--; return in.read(); } else if (partial) { if (loadDataLength() < 0) { return -1; } return this.read(); } return -1; } } }
javadoc
src/org/bouncycastle/bcpg/BCPGInputStream.java
javadoc
<ide><path>rc/org/bouncycastle/bcpg/BCPGInputStream.java <ide> <ide> /** <ide> * a stream that overlays our input stream, allowing the user to only read a segment of it. <add> * <add> * NB: dataLength will be zero if the segment length is in the upper range above 2**31. <ide> */ <ide> private static class PartialInputStream <ide> extends InputStream
Java
epl-1.0
error: pathspec 'opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SerializationUtilsTest.java' did not match any file(s) known to git
0acee4f257eeb2ef1d07fbf37d3f1e2bcc313829
1
opendaylight/controller
/* * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.datastore.node.utils.stream; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import javax.xml.transform.dom.DOMSource; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; import org.junit.Assert; import org.junit.Test; import org.opendaylight.yangtools.util.xml.UntrustedXML; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode; import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode; import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.MapNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode; import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.w3c.dom.Document; public class SerializationUtilsTest { private static final QName CONTAINER_Q_NAME = QName.create("ns-1", "2017-03-17", "container1"); @Test public void testSerializeDeserializeNodes() throws Exception { final NormalizedNode<?, ?> normalizedNode = createNormalizedNode(); final byte[] bytes = SerializationUtils.serializeNormalizedNode(normalizedNode); Assert.assertEquals(normalizedNode, SerializationUtils.deserializeNormalizedNode(bytes)); } @Test public void testSerializeDeserializeAnyXmlNode() throws Exception { final ByteArrayInputStream is = new ByteArrayInputStream("<xml><data/></xml>".getBytes(Charset.defaultCharset())); final Document parse = UntrustedXML.newDocumentBuilder().parse(is); final AnyXmlNode anyXmlNode = Builders.anyXmlBuilder() .withNodeIdentifier(id("anyXmlNode")) .withValue(new DOMSource(parse)) .build(); final byte[] bytes = SerializationUtils.serializeNormalizedNode(anyXmlNode); final NormalizedNode<?, ?> deserialized = SerializationUtils.deserializeNormalizedNode(bytes); final DOMSource value = (DOMSource) deserialized.getValue(); final Diff diff = XMLUnit.compareXML((Document) anyXmlNode.getValue().getNode(), value.getNode().getOwnerDocument()); Assert.assertTrue(diff.toString(), diff.similar()); } @Test public void testSerializeDeserializePath() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DataOutput out = new DataOutputStream(bos); final YangInstanceIdentifier path = YangInstanceIdentifier.builder() .node(id("container1")) .node(autmentationId("list1", "list2")) .node(listId("list1", "keyName1", "keyValue1")) .node(leafSetId("leafSer1", "leafSetValue1")) .build(); SerializationUtils.serializePath(path, out); final YangInstanceIdentifier deserialized = SerializationUtils.deserializePath(new DataInputStream(new ByteArrayInputStream(bos.toByteArray()))); Assert.assertEquals(path, deserialized); } @Test public void testSerializeDeserializePathAndNode() throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DataOutput out = new DataOutputStream(bos); final NormalizedNode<?, ?> node = createNormalizedNode(); final YangInstanceIdentifier path = YangInstanceIdentifier.create(id("container1")); SerializationUtils.serializePathAndNode(path, node, out); final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bos.toByteArray())); final AtomicBoolean applierCalled = new AtomicBoolean(false); SerializationUtils.deserializePathAndNode(in, applierCalled, (instance, deserializedPath, deserializedNode) -> { Assert.assertEquals(path, deserializedPath); Assert.assertEquals(node, deserializedNode); applierCalled.set(true); }); Assert.assertTrue(applierCalled.get()); } private static NormalizedNode<?, ?> createNormalizedNode() { final LeafSetNode<Object> leafSetNode = Builders.leafSetBuilder() .withNodeIdentifier(id("leafSetNode")) .withChild(createLeafSetEntry("leafSetNode", "leafSetValue1")) .withChild(createLeafSetEntry("leafSetNode", "leafSetValue2")) .build(); final LeafSetNode<Object> orderedLeafSetNode = Builders.orderedLeafSetBuilder() .withNodeIdentifier(id("orderedLeafSetNode")) .withChild(createLeafSetEntry("orderedLeafSetNode", "value1")) .withChild(createLeafSetEntry("orderedLeafSetNode", "value2")) .build(); final LeafNode<Boolean> booleanLeaf = createLeaf("booleanLeaf", true); final LeafNode<Byte> byteLeaf = createLeaf("byteLeaf", (byte) 0); final LeafNode<Short> shortLeaf = createLeaf("shortLeaf", (short) 55); final LeafNode<Integer> intLeaf = createLeaf("intLeaf", 11); final LeafNode<Long> longLeaf = createLeaf("longLeaf", 151515L); final LeafNode<String> stringLeaf = createLeaf("stringLeaf", "stringValue"); final LeafNode<String> longStringLeaf = createLeaf("longStringLeaf", getLongString()); final LeafNode<QName> qNameLeaf = createLeaf("stringLeaf", QName.create("base", "qName")); final LeafNode<YangInstanceIdentifier> idLeaf = createLeaf("stringLeaf", YangInstanceIdentifier.EMPTY); final MapEntryNode entry1 = Builders.mapEntryBuilder() .withNodeIdentifier(listId("mapNode", "key", "key1")) .withChild(stringLeaf) .build(); final MapEntryNode entry2 = Builders.mapEntryBuilder() .withNodeIdentifier(listId("mapNode", "key", "key2")) .withChild(stringLeaf) .build(); final MapNode mapNode = Builders.mapBuilder() .withNodeIdentifier(id("mapNode")) .withChild(entry1) .withChild(entry2) .build(); final OrderedMapNode orderedMapNode = Builders.orderedMapBuilder() .withNodeIdentifier(id("orderedMapNode")) .withChild(entry2) .withChild(entry1) .build(); final UnkeyedListEntryNode unkeyedListEntry1 = Builders.unkeyedListEntryBuilder() .withNodeIdentifier(id("unkeyedList")) .withChild(stringLeaf) .build(); final UnkeyedListEntryNode unkeyedListEntry2 = Builders.unkeyedListEntryBuilder() .withNodeIdentifier(id("unkeyedList")) .withChild(stringLeaf) .build(); final UnkeyedListNode unkeyedListNode = Builders.unkeyedListBuilder() .withNodeIdentifier(id("unkeyedList")) .withChild(unkeyedListEntry1) .withChild(unkeyedListEntry2) .build(); final ImmutableSet<QName> childNames = ImmutableSet.of(QName.create(CONTAINER_Q_NAME, "aug1"), QName.create(CONTAINER_Q_NAME, "aug1")); final AugmentationNode augmentationNode = Builders.augmentationBuilder() .withNodeIdentifier(new YangInstanceIdentifier.AugmentationIdentifier(childNames)) .withChild(createLeaf("aug1", "aug1Value")) .withChild(createLeaf("aug2", "aug2Value")) .build(); final ChoiceNode choiceNode = Builders.choiceBuilder() .withNodeIdentifier(id("choiceNode")) .withChild(createLeaf("choiceLeaf", 12)) .build(); return Builders.containerBuilder() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CONTAINER_Q_NAME)) .withChild(booleanLeaf) .withChild(byteLeaf) .withChild(shortLeaf) .withChild(intLeaf) .withChild(longLeaf) .withChild(stringLeaf) .withChild(longStringLeaf) .withChild(qNameLeaf) .withChild(idLeaf) .withChild(mapNode) .withChild(orderedMapNode) .withChild(unkeyedListNode) .withChild(leafSetNode) .withChild(orderedLeafSetNode) .withChild(augmentationNode) .withChild(choiceNode) .build(); } private static <T> LeafNode<T> createLeaf(final String name, final T value) { return ImmutableNodes.leafNode(id(name), value); } private static LeafSetEntryNode<Object> createLeafSetEntry(final String leafSet, final String value) { return Builders.leafSetEntryBuilder() .withNodeIdentifier(leafSetId(leafSet, value)) .withValue(value) .build(); } private static YangInstanceIdentifier.NodeIdentifier id(final String name) { return new YangInstanceIdentifier.NodeIdentifier(QName.create(CONTAINER_Q_NAME, name)); } private static YangInstanceIdentifier.NodeIdentifierWithPredicates listId(final String listName, final String keyName, final Object keyValue) { return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(CONTAINER_Q_NAME, listName), QName.create(CONTAINER_Q_NAME, keyName), keyValue); } private static <T> YangInstanceIdentifier.NodeWithValue<T> leafSetId(final String node, final T value) { return new YangInstanceIdentifier.NodeWithValue<>(QName.create(CONTAINER_Q_NAME, node), value); } private static YangInstanceIdentifier.AugmentationIdentifier autmentationId(final String... nodes) { final Set<QName> qNames = Arrays.stream(nodes) .map(node -> QName.create(CONTAINER_Q_NAME, node)) .collect(Collectors.toSet()); return new YangInstanceIdentifier.AugmentationIdentifier(qNames); } private static String getLongString() { final StringBuilder builder = new StringBuilder(10000); for (int i = 0; i < 1000; i++) { builder.append("0123456789"); } return builder.toString(); } }
opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SerializationUtilsTest.java
Add SerializationUtils unit test Change-Id: I7e8533c8c54c6d2cab234e9ad7db6037a97bdbdc Signed-off-by: Andrej Mak <[email protected]>
opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SerializationUtilsTest.java
Add SerializationUtils unit test
<ide><path>pendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/SerializationUtilsTest.java <add>/* <add> * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. <add> * <add> * This program and the accompanying materials are made available under the <add> * terms of the Eclipse Public License v1.0 which accompanies this distribution, <add> * and is available at http://www.eclipse.org/legal/epl-v10.html <add> */ <add>package org.opendaylight.controller.cluster.datastore.node.utils.stream; <add> <add>import com.google.common.collect.ImmutableSet; <add>import java.io.ByteArrayInputStream; <add>import java.io.ByteArrayOutputStream; <add>import java.io.DataInputStream; <add>import java.io.DataOutput; <add>import java.io.DataOutputStream; <add>import java.nio.charset.Charset; <add>import java.util.Arrays; <add>import java.util.Set; <add>import java.util.concurrent.atomic.AtomicBoolean; <add>import java.util.stream.Collectors; <add>import javax.xml.transform.dom.DOMSource; <add>import org.custommonkey.xmlunit.Diff; <add>import org.custommonkey.xmlunit.XMLUnit; <add>import org.junit.Assert; <add>import org.junit.Test; <add>import org.opendaylight.yangtools.util.xml.UntrustedXML; <add>import org.opendaylight.yangtools.yang.common.QName; <add>import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; <add>import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.MapNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode; <add>import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode; <add>import org.opendaylight.yangtools.yang.data.impl.schema.Builders; <add>import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; <add>import org.w3c.dom.Document; <add> <add>public class SerializationUtilsTest { <add> <add> private static final QName CONTAINER_Q_NAME = QName.create("ns-1", "2017-03-17", "container1"); <add> <add> @Test <add> public void testSerializeDeserializeNodes() throws Exception { <add> final NormalizedNode<?, ?> normalizedNode = createNormalizedNode(); <add> final byte[] bytes = SerializationUtils.serializeNormalizedNode(normalizedNode); <add> Assert.assertEquals(normalizedNode, SerializationUtils.deserializeNormalizedNode(bytes)); <add> <add> } <add> <add> @Test <add> public void testSerializeDeserializeAnyXmlNode() throws Exception { <add> final ByteArrayInputStream is = <add> new ByteArrayInputStream("<xml><data/></xml>".getBytes(Charset.defaultCharset())); <add> final Document parse = UntrustedXML.newDocumentBuilder().parse(is); <add> final AnyXmlNode anyXmlNode = Builders.anyXmlBuilder() <add> .withNodeIdentifier(id("anyXmlNode")) <add> .withValue(new DOMSource(parse)) <add> .build(); <add> final byte[] bytes = SerializationUtils.serializeNormalizedNode(anyXmlNode); <add> final NormalizedNode<?, ?> deserialized = SerializationUtils.deserializeNormalizedNode(bytes); <add> final DOMSource value = (DOMSource) deserialized.getValue(); <add> final Diff diff = XMLUnit.compareXML((Document) anyXmlNode.getValue().getNode(), <add> value.getNode().getOwnerDocument()); <add> Assert.assertTrue(diff.toString(), diff.similar()); <add> } <add> <add> @Test <add> public void testSerializeDeserializePath() throws Exception { <add> final ByteArrayOutputStream bos = new ByteArrayOutputStream(); <add> final DataOutput out = new DataOutputStream(bos); <add> final YangInstanceIdentifier path = YangInstanceIdentifier.builder() <add> .node(id("container1")) <add> .node(autmentationId("list1", "list2")) <add> .node(listId("list1", "keyName1", "keyValue1")) <add> .node(leafSetId("leafSer1", "leafSetValue1")) <add> .build(); <add> SerializationUtils.serializePath(path, out); <add> final YangInstanceIdentifier deserialized = <add> SerializationUtils.deserializePath(new DataInputStream(new ByteArrayInputStream(bos.toByteArray()))); <add> Assert.assertEquals(path, deserialized); <add> } <add> <add> @Test <add> public void testSerializeDeserializePathAndNode() throws Exception { <add> final ByteArrayOutputStream bos = new ByteArrayOutputStream(); <add> final DataOutput out = new DataOutputStream(bos); <add> final NormalizedNode<?, ?> node = createNormalizedNode(); <add> final YangInstanceIdentifier path = YangInstanceIdentifier.create(id("container1")); <add> SerializationUtils.serializePathAndNode(path, node, out); <add> final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bos.toByteArray())); <add> final AtomicBoolean applierCalled = new AtomicBoolean(false); <add> SerializationUtils.deserializePathAndNode(in, applierCalled, (instance, deserializedPath, deserializedNode) -> { <add> Assert.assertEquals(path, deserializedPath); <add> Assert.assertEquals(node, deserializedNode); <add> applierCalled.set(true); <add> }); <add> Assert.assertTrue(applierCalled.get()); <add> } <add> <add> private static NormalizedNode<?, ?> createNormalizedNode() { <add> final LeafSetNode<Object> leafSetNode = Builders.leafSetBuilder() <add> .withNodeIdentifier(id("leafSetNode")) <add> .withChild(createLeafSetEntry("leafSetNode", "leafSetValue1")) <add> .withChild(createLeafSetEntry("leafSetNode", "leafSetValue2")) <add> .build(); <add> final LeafSetNode<Object> orderedLeafSetNode = Builders.orderedLeafSetBuilder() <add> .withNodeIdentifier(id("orderedLeafSetNode")) <add> .withChild(createLeafSetEntry("orderedLeafSetNode", "value1")) <add> .withChild(createLeafSetEntry("orderedLeafSetNode", "value2")) <add> .build(); <add> final LeafNode<Boolean> booleanLeaf = createLeaf("booleanLeaf", true); <add> final LeafNode<Byte> byteLeaf = createLeaf("byteLeaf", (byte) 0); <add> final LeafNode<Short> shortLeaf = createLeaf("shortLeaf", (short) 55); <add> final LeafNode<Integer> intLeaf = createLeaf("intLeaf", 11); <add> final LeafNode<Long> longLeaf = createLeaf("longLeaf", 151515L); <add> final LeafNode<String> stringLeaf = createLeaf("stringLeaf", "stringValue"); <add> final LeafNode<String> longStringLeaf = createLeaf("longStringLeaf", getLongString()); <add> final LeafNode<QName> qNameLeaf = createLeaf("stringLeaf", QName.create("base", "qName")); <add> final LeafNode<YangInstanceIdentifier> idLeaf = createLeaf("stringLeaf", YangInstanceIdentifier.EMPTY); <add> final MapEntryNode entry1 = Builders.mapEntryBuilder() <add> .withNodeIdentifier(listId("mapNode", "key", "key1")) <add> .withChild(stringLeaf) <add> .build(); <add> final MapEntryNode entry2 = Builders.mapEntryBuilder() <add> .withNodeIdentifier(listId("mapNode", "key", "key2")) <add> .withChild(stringLeaf) <add> .build(); <add> final MapNode mapNode = Builders.mapBuilder() <add> .withNodeIdentifier(id("mapNode")) <add> .withChild(entry1) <add> .withChild(entry2) <add> .build(); <add> final OrderedMapNode orderedMapNode = Builders.orderedMapBuilder() <add> .withNodeIdentifier(id("orderedMapNode")) <add> .withChild(entry2) <add> .withChild(entry1) <add> .build(); <add> final UnkeyedListEntryNode unkeyedListEntry1 = Builders.unkeyedListEntryBuilder() <add> .withNodeIdentifier(id("unkeyedList")) <add> .withChild(stringLeaf) <add> .build(); <add> final UnkeyedListEntryNode unkeyedListEntry2 = Builders.unkeyedListEntryBuilder() <add> .withNodeIdentifier(id("unkeyedList")) <add> .withChild(stringLeaf) <add> .build(); <add> final UnkeyedListNode unkeyedListNode = Builders.unkeyedListBuilder() <add> .withNodeIdentifier(id("unkeyedList")) <add> .withChild(unkeyedListEntry1) <add> .withChild(unkeyedListEntry2) <add> .build(); <add> final ImmutableSet<QName> childNames = <add> ImmutableSet.of(QName.create(CONTAINER_Q_NAME, "aug1"), QName.create(CONTAINER_Q_NAME, "aug1")); <add> final AugmentationNode augmentationNode = Builders.augmentationBuilder() <add> .withNodeIdentifier(new YangInstanceIdentifier.AugmentationIdentifier(childNames)) <add> .withChild(createLeaf("aug1", "aug1Value")) <add> .withChild(createLeaf("aug2", "aug2Value")) <add> .build(); <add> final ChoiceNode choiceNode = Builders.choiceBuilder() <add> .withNodeIdentifier(id("choiceNode")) <add> .withChild(createLeaf("choiceLeaf", 12)) <add> .build(); <add> return Builders.containerBuilder() <add> .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CONTAINER_Q_NAME)) <add> .withChild(booleanLeaf) <add> .withChild(byteLeaf) <add> .withChild(shortLeaf) <add> .withChild(intLeaf) <add> .withChild(longLeaf) <add> .withChild(stringLeaf) <add> .withChild(longStringLeaf) <add> .withChild(qNameLeaf) <add> .withChild(idLeaf) <add> .withChild(mapNode) <add> .withChild(orderedMapNode) <add> .withChild(unkeyedListNode) <add> .withChild(leafSetNode) <add> .withChild(orderedLeafSetNode) <add> .withChild(augmentationNode) <add> .withChild(choiceNode) <add> .build(); <add> } <add> <add> private static <T> LeafNode<T> createLeaf(final String name, final T value) { <add> return ImmutableNodes.leafNode(id(name), value); <add> } <add> <add> private static LeafSetEntryNode<Object> createLeafSetEntry(final String leafSet, final String value) { <add> return Builders.leafSetEntryBuilder() <add> .withNodeIdentifier(leafSetId(leafSet, value)) <add> .withValue(value) <add> .build(); <add> } <add> <add> private static YangInstanceIdentifier.NodeIdentifier id(final String name) { <add> return new YangInstanceIdentifier.NodeIdentifier(QName.create(CONTAINER_Q_NAME, name)); <add> } <add> <add> private static YangInstanceIdentifier.NodeIdentifierWithPredicates listId(final String listName, <add> final String keyName, <add> final Object keyValue) { <add> return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(CONTAINER_Q_NAME, listName), <add> QName.create(CONTAINER_Q_NAME, keyName), keyValue); <add> } <add> <add> private static <T> YangInstanceIdentifier.NodeWithValue<T> leafSetId(final String node, final T value) { <add> return new YangInstanceIdentifier.NodeWithValue<>(QName.create(CONTAINER_Q_NAME, node), value); <add> } <add> <add> private static YangInstanceIdentifier.AugmentationIdentifier autmentationId(final String... nodes) { <add> final Set<QName> qNames = Arrays.stream(nodes) <add> .map(node -> QName.create(CONTAINER_Q_NAME, node)) <add> .collect(Collectors.toSet()); <add> return new YangInstanceIdentifier.AugmentationIdentifier(qNames); <add> } <add> <add> private static String getLongString() { <add> final StringBuilder builder = new StringBuilder(10000); <add> for (int i = 0; i < 1000; i++) { <add> builder.append("0123456789"); <add> } <add> return builder.toString(); <add> } <add>}
Java
apache-2.0
2df7b244ccb556a817e6ed76eb776abe26fbe9ae
0
nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/wfswarm-example-arjuna-old,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch
import java.util.Objects; public class MovementRoutine { public MovementRoutine (String command, int numberOfCommands) { _command = command; _numberOfCommands = numberOfCommands; System.out.println("NumberOfCommands "+numberOfCommands); if ((command == null) || (command.equals(""))) { System.out.println("OOPS"); System.exit(0); } } public boolean contains (MovementRoutine compare) { return (_command.indexOf(compare.getCommand()) != -1); } public String getCommand () { return _command; } public int getLength () { return ((_command == null) ? 0 : _command.length()); } public int numberOfCommands () { return _numberOfCommands; } @Override public String toString () { return _command; } @Override public int hashCode () { return Objects.hash(_command, _numberOfCommands); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() == obj.getClass()) { MovementRoutine temp = (MovementRoutine) obj; return (_command.equals(temp._command)); } return false; } private String _command; private int _numberOfCommands; }
AdventOfCode/2019/day17/part2/MovementRoutine.java
import java.util.Objects; public class MovementRoutine { public MovementRoutine (String command, int numberOfCommands) { _command = command; _numberOfCommands = numberOfCommands; System.out.println("NumberOfCommands "+numberOfCommands); if ((command == null) || (command.equals(""))) { System.out.println("OOPS"); System.exit(0); } } public String getCommand () { return _command; } public int getLength () { return ((_command == null) ? 0 : _command.length()); } public int numberOfCommands () { return _numberOfCommands; } @Override public String toString () { return _command; } @Override public int hashCode () { return Objects.hash(_command, _numberOfCommands); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() == obj.getClass()) { MovementRoutine temp = (MovementRoutine) obj; return (_command.equals(temp._command)); } return false; } private String _command; private int _numberOfCommands; }
Update MovementRoutine.java
AdventOfCode/2019/day17/part2/MovementRoutine.java
Update MovementRoutine.java
<ide><path>dventOfCode/2019/day17/part2/MovementRoutine.java <ide> System.out.println("OOPS"); <ide> System.exit(0); <ide> } <add> } <add> <add> public boolean contains (MovementRoutine compare) <add> { <add> return (_command.indexOf(compare.getCommand()) != -1); <ide> } <ide> <ide> public String getCommand ()
Java
mit
54b15b92ea678c6ed03b6a8df9bba4fd328da4e0
0
aviolette/foodtrucklocator,aviolette/foodtrucklocator,aviolette/foodtrucklocator,aviolette/foodtrucklocator
package foodtruck.schedule; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.gdata.client.calendar.CalendarQuery; import com.google.gdata.client.calendar.CalendarService; import com.google.gdata.data.DateTime; import com.google.gdata.data.Link; import com.google.gdata.data.calendar.CalendarEventEntry; import com.google.gdata.data.calendar.CalendarEventFeed; import com.google.gdata.data.extensions.When; import com.google.gdata.data.extensions.Where; import com.google.gdata.util.ServiceException; import com.google.inject.Inject; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormatter; import foodtruck.dao.TruckDAO; import foodtruck.geolocation.GeoLocator; import foodtruck.geolocation.GeolocationGranularity; import foodtruck.model.Location; import foodtruck.model.StopOrigin; import foodtruck.model.Truck; import foodtruck.model.TruckStop; import foodtruck.monitoring.Monitored; import foodtruck.util.Clock; import foodtruck.util.FriendlyDateOnlyFormat; import static foodtruck.schedule.TimeUtils.toJoda; /** * Uses a google calendar feed to load a truck's schedule. * @author [email protected] * @since 8/27/11 */ public class GoogleCalendar implements ScheduleStrategy { private static final Logger log = Logger.getLogger(GoogleCalendar.class.getName()); private final static int MAX_TRIES = 3; private final CalendarService calendarService; private final CalendarQueryFactory queryFactory; private final DateTimeZone defaultZone; private final GeoLocator geolocator; private final TruckDAO truckDAO; private final AddressExtractor addressExtractor; private final DateTimeFormatter formatter; private final Clock clock; @Inject public GoogleCalendar(CalendarService calendarService, CalendarQueryFactory queryFactory, DateTimeZone defaultZone, GeoLocator geolocator, TruckDAO truckDAO, AddressExtractor addressExtractor, @FriendlyDateOnlyFormat DateTimeFormatter formatter, Clock clock) { this.calendarService = calendarService; this.queryFactory = queryFactory; this.defaultZone = defaultZone; this.geolocator = geolocator; this.truckDAO = truckDAO; this.addressExtractor = addressExtractor; this.formatter = formatter; this.clock = clock; } // TODO: rewrite this...its awfully crappy @Override @Monitored public List<TruckStop> findForTime(Interval range, @Nullable Truck searchTruck) { CalendarQuery query = queryFactory.create(); String truckId = searchTruck == null ? null : searchTruck.getId(); log.info("Initiating calendar search " + truckId); List<TruckStop> stops = performTruckSearch(range, searchTruck, query, false); stops = Lists.newLinkedList(stops); if (searchTruck != null && !Strings.isNullOrEmpty(searchTruck.getCalendarUrl())) { customCalendarSearch(range, searchTruck, stops); } else if (searchTruck == null) { for (Truck truck : truckDAO.findTrucksWithCalendars()) { customCalendarSearch(range, truck, stops); } } return stops; } private void customCalendarSearch(Interval range, Truck truck, List<TruckStop> stops) { try { final String calendarUrl = truck.getCalendarUrl(); if (calendarUrl == null || !calendarUrl.startsWith("http")) { return; } log.info("Custom calendar search: " + calendarUrl); stops.addAll(performTruckSearch(range, truck, queryFactory.create(new URL(calendarUrl)), true)); } catch (RuntimeException rte) { log.info("Search truck: " + truck.getId()); log.severe(rte.getMessage()); } catch (MalformedURLException e) { log.warning(e.getMessage()); } } private List<TruckStop> performTruckSearch(Interval range, Truck searchTruck, CalendarQuery query, boolean customCalendar) { query.setMinimumStartTime(new DateTime(range.getStart().toDate(), defaultZone.toTimeZone())); query.setMaximumStartTime(new DateTime(range.getEnd().toDate(), defaultZone.toTimeZone())); query.setMaxResults(1000); if (searchTruck != null && !customCalendar) { query.setFullTextQuery(searchTruck.getId()); } query.setStringCustomParameter("singleevents", "true"); ImmutableList.Builder<TruckStop> builder = ImmutableList.builder(); try { CalendarEventFeed resultFeed = calendarQuery(query); for (CalendarEventEntry entry : resultFeed.getEntries()) { final String titleText = entry.getTitle().getPlainText(); if (Strings.isNullOrEmpty(titleText) && searchTruck == null) { Link htmlLink = entry.getHtmlLink(); String entryString = (htmlLink == null) ? entry.getId() : htmlLink.getHref(); log.log(Level.WARNING, "Could not find title text for {0}", new Object[] { entryString }); } Truck truck = (searchTruck != null || Strings.isNullOrEmpty(titleText)) ? searchTruck : truckDAO.findById(titleText); if (truck == null) { continue; } Where where = Iterables.getFirst(entry.getLocations(), null); if (where == null) { throw new IllegalStateException("No location specified"); } When time = Iterables.getFirst(entry.getTimes(), null); String whereString = where.getValueString(); Location location = null; if (!Strings.isNullOrEmpty(whereString)) { if (whereString.endsWith(", United States")) { whereString = whereString.substring(0, whereString.lastIndexOf(",")); // Fixes how google calendar normalizes fully-qualified addresses with a state, zip and country code } else if (whereString.lastIndexOf(", IL ") != -1) { whereString = whereString.substring(0, whereString.lastIndexOf(", IL ")) + ", IL"; } // HACK Alert, the address extractor doesn't handle non-Chicago addresses well, so // if it is a fully qualified address written by me, it will probably end in City, IL if (!whereString.endsWith(", IL")) { whereString = coalesce(Iterables.getFirst(addressExtractor.parse(whereString, truck), null), whereString); } location = geolocator.locate(whereString, GeolocationGranularity.NARROW); } if ((location == null || !location.isResolved()) && customCalendar) { // Sometimes the location is in the title - try that too log.info("Trying title text: " + titleText); final List<String> parsed = addressExtractor.parse(titleText, searchTruck); String locString = Iterables.getFirst(parsed, null); if (locString == null) { log.info("Failed to parse titletext for address, trying whole thing: " + titleText); locString = titleText; } if (locString != null) { location = geolocator.locate(locString, GeolocationGranularity.NARROW); } } if (location != null && location.isResolved()) { final String entered = enteredOn(entry); String note = customCalendar ? "Stop added from vendor's calendar" : "Entered manually " + (entered == null ? "" : "on ") + entered; Confidence confidence = customCalendar ? Confidence.HIGH : Confidence.MEDIUM; final TruckStop truckStop = TruckStop.builder().truck(truck) .origin(customCalendar ? StopOrigin.VENDORCAL : StopOrigin.MANUAL) .location(location) .confidence(confidence) .appendNote(note) .startTime(toJoda(time.getStartTime(), defaultZone)) .endTime(toJoda(time.getEndTime(), defaultZone)).build(); log.log(Level.INFO, "Loaded truckstop: {0}", truckStop); builder.add(truckStop); } else { log.log(Level.WARNING, "Location could not be resolved for {0}, {1} between {2} and {3}", new Object[] {truck.getId(), where.getValueString(), range.getStart(), range.getEnd()}); } } } catch (IOException e) { throw new RuntimeException(e); } catch (ServiceException e) { throw new RuntimeException(e); } return builder.build(); } private @Nullable String enteredOn(CalendarEventEntry entry) { try { return formatter.print(entry.getUpdated().getValue()); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); return clock.nowFormattedAsTime(); } } // TODO: make this generic and pull it out private String coalesce(String st1, String st2) { return (Strings.isNullOrEmpty(st1)) ? st2 : st1; } private CalendarEventFeed calendarQuery(CalendarQuery query) throws IOException, ServiceException { for (int i = 0; i < MAX_TRIES; i++) { try { return calendarService.query(query, CalendarEventFeed.class); } catch (Exception timeout) { if ((i + 1) == MAX_TRIES) { throw new RuntimeException(timeout); } } } throw new RuntimeException("Exhausted number of tries"); } }
src/main/java/foodtruck/schedule/GoogleCalendar.java
package foodtruck.schedule; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.gdata.client.calendar.CalendarQuery; import com.google.gdata.client.calendar.CalendarService; import com.google.gdata.data.DateTime; import com.google.gdata.data.Link; import com.google.gdata.data.calendar.CalendarEventEntry; import com.google.gdata.data.calendar.CalendarEventFeed; import com.google.gdata.data.extensions.When; import com.google.gdata.data.extensions.Where; import com.google.gdata.util.ServiceException; import com.google.inject.Inject; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormatter; import foodtruck.dao.TruckDAO; import foodtruck.geolocation.GeoLocator; import foodtruck.geolocation.GeolocationGranularity; import foodtruck.model.Location; import foodtruck.model.StopOrigin; import foodtruck.model.Truck; import foodtruck.model.TruckStop; import foodtruck.monitoring.Monitored; import foodtruck.util.Clock; import foodtruck.util.FriendlyDateOnlyFormat; import static foodtruck.schedule.TimeUtils.toJoda; /** * Uses a google calendar feed to load a truck's schedule. * @author [email protected] * @since 8/27/11 */ public class GoogleCalendar implements ScheduleStrategy { private static final Logger log = Logger.getLogger(GoogleCalendar.class.getName()); private final static int MAX_TRIES = 3; private final CalendarService calendarService; private final CalendarQueryFactory queryFactory; private final DateTimeZone defaultZone; private final GeoLocator geolocator; private final TruckDAO truckDAO; private final AddressExtractor addressExtractor; private final DateTimeFormatter formatter; private final Clock clock; @Inject public GoogleCalendar(CalendarService calendarService, CalendarQueryFactory queryFactory, DateTimeZone defaultZone, GeoLocator geolocator, TruckDAO truckDAO, AddressExtractor addressExtractor, @FriendlyDateOnlyFormat DateTimeFormatter formatter, Clock clock) { this.calendarService = calendarService; this.queryFactory = queryFactory; this.defaultZone = defaultZone; this.geolocator = geolocator; this.truckDAO = truckDAO; this.addressExtractor = addressExtractor; this.formatter = formatter; this.clock = clock; } // TODO: rewrite this...its awfully crappy @Override @Monitored public List<TruckStop> findForTime(Interval range, @Nullable Truck searchTruck) { CalendarQuery query = queryFactory.create(); String truckId = searchTruck == null ? null : searchTruck.getId(); log.info("Initiating calendar search " + truckId); List<TruckStop> stops = performTruckSearch(range, searchTruck, query, false); stops = Lists.newLinkedList(stops); if (searchTruck != null && !Strings.isNullOrEmpty(searchTruck.getCalendarUrl())) { customCalendarSearch(range, searchTruck, stops); } else if (searchTruck == null) { for (Truck truck : truckDAO.findTrucksWithCalendars()) { customCalendarSearch(range, truck, stops); } } return stops; } private void customCalendarSearch(Interval range, Truck truck, List<TruckStop> stops) { try { final String calendarUrl = truck.getCalendarUrl(); if (calendarUrl == null || !calendarUrl.startsWith("http")) { return; } log.info("Custom calendar search: " + calendarUrl); stops.addAll(performTruckSearch(range, truck, queryFactory.create(new URL(calendarUrl)), true)); } catch (RuntimeException rte) { log.info("Search truck: " + truck.getId()); log.severe(rte.getMessage()); } catch (MalformedURLException e) { log.warning(e.getMessage()); } } private List<TruckStop> performTruckSearch(Interval range, Truck searchTruck, CalendarQuery query, boolean customCalendar) { query.setMinimumStartTime(new DateTime(range.getStart().toDate(), defaultZone.toTimeZone())); query.setMaximumStartTime(new DateTime(range.getEnd().toDate(), defaultZone.toTimeZone())); query.setMaxResults(1000); if (searchTruck != null && !customCalendar) { query.setFullTextQuery(searchTruck.getId()); } query.setStringCustomParameter("singleevents", "true"); ImmutableList.Builder<TruckStop> builder = ImmutableList.builder(); try { CalendarEventFeed resultFeed = calendarQuery(query); for (CalendarEventEntry entry : resultFeed.getEntries()) { final String titleText = entry.getTitle().getPlainText(); if (Strings.isNullOrEmpty(titleText) && searchTruck == null) { Link htmlLink = entry.getHtmlLink(); String entryString = (htmlLink == null) ? entry.getId() : htmlLink.getHref(); log.log(Level.WARNING, "Could not find title text for {0}", new Object[] { entryString }); } Truck truck = (searchTruck != null || Strings.isNullOrEmpty(titleText)) ? searchTruck : truckDAO.findById(titleText); if (truck == null) { continue; } Where where = Iterables.getFirst(entry.getLocations(), null); if (where == null) { throw new IllegalStateException("No location specified"); } When time = Iterables.getFirst(entry.getTimes(), null); String whereString = where.getValueString(); Location location = null; if (!Strings.isNullOrEmpty(whereString)) { if (whereString.endsWith(", United States")) { whereString = whereString.substring(0, whereString.lastIndexOf(",")); } // HACK Alert, the address extractor doesn't handle non-Chicago addresses well, so // if it is a fully qualified address written by me, it will probably end in City, IL if (!whereString.endsWith(", IL")) { whereString = coalesce(Iterables.getFirst(addressExtractor.parse(whereString, truck), null), whereString); } location = geolocator.locate(whereString, GeolocationGranularity.NARROW); } if ((location == null || !location.isResolved()) && customCalendar) { // Sometimes the location is in the title - try that too log.info("Trying title text: " + titleText); final List<String> parsed = addressExtractor.parse(titleText, searchTruck); String locString = Iterables.getFirst(parsed, null); if (locString == null) { log.info("Failed to parse titletext for address, trying whole thing: " + titleText); locString = titleText; } if (locString != null) { location = geolocator.locate(locString, GeolocationGranularity.NARROW); } } if (location != null && location.isResolved()) { final String entered = enteredOn(entry); String note = customCalendar ? "Stop added from vendor's calendar" : "Entered manually " + (entered == null ? "" : "on ") + entered; Confidence confidence = customCalendar ? Confidence.HIGH : Confidence.MEDIUM; final TruckStop truckStop = TruckStop.builder().truck(truck) .origin(customCalendar ? StopOrigin.VENDORCAL : StopOrigin.MANUAL) .location(location) .confidence(confidence) .appendNote(note) .startTime(toJoda(time.getStartTime(), defaultZone)) .endTime(toJoda(time.getEndTime(), defaultZone)).build(); log.log(Level.INFO, "Loaded truckstop: {0}", truckStop); builder.add(truckStop); } else { log.log(Level.WARNING, "Location could not be resolved for {0}, {1} between {2} and {3}", new Object[] {truck.getId(), where.getValueString(), range.getStart(), range.getEnd()}); } } } catch (IOException e) { throw new RuntimeException(e); } catch (ServiceException e) { throw new RuntimeException(e); } return builder.build(); } private @Nullable String enteredOn(CalendarEventEntry entry) { try { return formatter.print(entry.getUpdated().getValue()); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); return clock.nowFormattedAsTime(); } } // TODO: make this generic and pull it out private String coalesce(String st1, String st2) { return (Strings.isNullOrEmpty(st1)) ? st2 : st1; } private CalendarEventFeed calendarQuery(CalendarQuery query) throws IOException, ServiceException { for (int i = 0; i < MAX_TRIES; i++) { try { return calendarService.query(query, CalendarEventFeed.class); } catch (Exception timeout) { if ((i + 1) == MAX_TRIES) { throw new RuntimeException(timeout); } } } throw new RuntimeException("Exhausted number of tries"); } }
Removed zip,USA from the end of google-normalized addresses
src/main/java/foodtruck/schedule/GoogleCalendar.java
Removed zip,USA from the end of google-normalized addresses
<ide><path>rc/main/java/foodtruck/schedule/GoogleCalendar.java <ide> if (!Strings.isNullOrEmpty(whereString)) { <ide> if (whereString.endsWith(", United States")) { <ide> whereString = whereString.substring(0, whereString.lastIndexOf(",")); <add> // Fixes how google calendar normalizes fully-qualified addresses with a state, zip and country code <add> } else if (whereString.lastIndexOf(", IL ") != -1) { <add> whereString = whereString.substring(0, whereString.lastIndexOf(", IL ")) + ", IL"; <ide> } <ide> // HACK Alert, the address extractor doesn't handle non-Chicago addresses well, so <ide> // if it is a fully qualified address written by me, it will probably end in City, IL
JavaScript
mit
75a5a35e3f3e76f9bc9148b4665f2c77146401a1
0
akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem
var Base64 = (function() { // private property var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // private method for UTF-8 encoding function utf8Encode(string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } // public method for encoding return { encode : (typeof btoa == 'function') ? function(input) { return btoa(input); } : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } }; })(); //http://druckit.wordpress.com/2013/10/26/generate-an-excel-file-from-an-ext-js-4-grid/ Ext.define('My.grid.ExcelGridPanel', { extend: 'Ext.grid.GridPanel', requires: 'Ext.form.action.StandardSubmit', /* Kick off process */ downloadExcelXml: function(includeHidden, title) { if (!title) title = this.title; var vExportContent = this.getExcelXml(includeHidden, title); var location = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + Base64.encode(vExportContent); /* dynamically create and anchor tag to force download with suggested filename note: download attribute is Google Chrome specific */ if (Ext.isChrome || Ext.isGecko) { // local download var gridEl = this.getEl(); var extension = 'xml'; if (Ext.isGecko) extension = 'xlsx'; var el = Ext.DomHelper.append(gridEl, { tag: "a", download: title + "-" + Ext.Date.format(new Date(), 'Y-m-d Hi') + '.'+extension, href: location }); el.click(); Ext.fly(el).destroy(); } else { // remote download var form = this.down('form#uploadForm'); if (form) { form.destroy(); } form = this.add({ xtype: 'form', itemId: 'uploadForm', hidden: true, standardSubmit: true, url: 'exportexcel.php', items: [{ xtype: 'hiddenfield', name: 'ex', value: vExportContent }] }); form.getForm().submit(); } }, /* Welcome to XML Hell See: http://msdn.microsoft.com/en-us/library/office/aa140066(v=office.10).aspx for more details */ getExcelXml: function(includeHidden, title) { var theTitle = title || this.title; var worksheet = this.createWorksheet(includeHidden, theTitle); var totalWidth = this.columns.length; return ''.concat( '<?xml version="1.0"?>', '<?mso-application progid="Excel.Sheet"?>', '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">', '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Title>' + theTitle + '</Title></DocumentProperties>', '<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"><AllowPNG/></OfficeDocumentSettings>', '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">', '<WindowHeight>' + worksheet.height + '</WindowHeight>', '<WindowWidth>' + worksheet.width + '</WindowWidth>', '<ProtectStructure>False</ProtectStructure>', '<ProtectWindows>False</ProtectWindows>', '</ExcelWorkbook>', '<Styles>', '<Style ss:ID="Default" ss:Name="Normal">', '<Alignment ss:Vertical="Bottom"/>', '<Borders/>', '<Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="12" ss:Color="#000000"/>', '<Interior/>', '<NumberFormat/>', '<Protection/>', '</Style>', '<Style ss:ID="title">', '<Borders />', '<Font ss:Bold="1" ss:Size="18" />', '<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="1" />', '<NumberFormat ss:Format="@" />', '</Style>', '<Style ss:ID="headercell">', '<Font ss:Bold="1" ss:Size="10" />', '<Alignment ss:Horizontal="Center" ss:WrapText="1" />', '<Interior ss:Color="#A3C9F1" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="even">', '<Interior ss:Color="#CCFFFF" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="evendate" ss:Parent="even">', '<NumberFormat ss:Format="yyyy-mm-dd" />', '</Style>', '<Style ss:ID="evenint" ss:Parent="even">', '<Numberformat ss:Format="0" />', '</Style>', '<Style ss:ID="evenfloat" ss:Parent="even">', '<Numberformat ss:Format="0.00" />', '</Style>', '<Style ss:ID="odd">', '<Interior ss:Color="#CCCCFF" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="groupSeparator">', '<Interior ss:Color="#D3D3D3" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="odddate" ss:Parent="odd">', '<NumberFormat ss:Format="yyyy-mm-dd" />', '</Style>', '<Style ss:ID="oddint" ss:Parent="odd">', '<NumberFormat Format="0" />', '</Style>', '<Style ss:ID="oddfloat" ss:Parent="odd">', '<NumberFormat Format="0.00" />', '</Style>', '</Styles>', worksheet.xml, '</Workbook>' ); }, /* Support function to return field info from store based on fieldname */ getModelField: function(fieldName) { var fields = this.store.model.getFields(); for (var i = 0; i < fields.length; i++) { if (fields[i].name === fieldName) { return fields[i]; } } }, /* Convert store into Excel Worksheet */ generateEmptyGroupRow: function(dataIndex, value, cellTypes, includeHidden) { var cm = this.columns; var colCount = this.columns.length; var rowTpl = '<Row ss:AutoFitHeight="0"><Cell ss:StyleID="groupSeparator" ss:MergeAcross="{0}"><Data ss:Type="String"><html:b>{1}</html:b></Data></Cell></Row>'; var visibleCols = 0; // rowXml += '<Cell ss:StyleID="groupSeparator">' for (var j = 0; j < colCount; j++) { if (cm[j].xtype != 'actioncolumn' && (cm[j].dataIndex != '') && (includeHidden || !cm[j].hidden)) { // rowXml += '<Cell ss:StyleID="groupSeparator"/>'; visibleCols++; } } // rowXml += "</Row>"; return Ext.String.format(rowTpl, visibleCols - 1, value); }, createWorksheet: function(includeHidden, theTitle) { // Calculate cell data types and extra class names which affect formatting var cellType = []; var cellTypeClass = []; var cm = this.columns; var totalWidthInPixels = 0; var colXml = ''; var headerXml = ''; var visibleColumnCountReduction = 0; var colCount = cm.length; for (var i = 0; i < colCount; i++) { if (cm[i].xtype != 'actioncolumn' && (cm[i].dataIndex != '') && (includeHidden || !cm[i].hidden)) { var w = cm[i].getEl().getWidth(); totalWidthInPixels += w; if (cm[i].text === "") { cellType.push("None"); cellTypeClass.push(""); ++visibleColumnCountReduction; } else { colXml += '<Column ss:AutoFitWidth="1" ss:Width="' + w + '" />'; headerXml += '<Cell ss:StyleID="headercell">' + '<Data ss:Type="String">' + cm[i].text + '</Data>' + '<NamedCell ss:Name="Print_Titles"></NamedCell></Cell>'; var fld = this.getModelField(cm[i].dataIndex); switch (fld.type.type) { case "int": cellType.push("Number"); cellTypeClass.push("int"); break; case "float": cellType.push("Number"); cellTypeClass.push("float"); break; case "bool": case "boolean": cellType.push("String"); cellTypeClass.push(""); break; case "date": cellType.push("DateTime"); cellTypeClass.push("date"); break; default: cellType.push("String"); cellTypeClass.push(""); break; } } } } var visibleColumnCount = cellType.length - visibleColumnCountReduction; var result = { height: 9000, width: Math.floor(totalWidthInPixels * 30) + 50 }; // Generate worksheet header details. // determine number of rows var numGridRows = this.store.getCount() + 2; if (!Ext.isEmpty(this.store.groupField)) { numGridRows = numGridRows + this.store.getGroups().length; } // create header for worksheet var t = ''.concat( '<Worksheet ss:Name="myworksheet">', '<Names>', '<NamedRange ss:Name="Print_Titles" ss:RefersTo="=\'myworksheet\'!R1:R2">', '</NamedRange></Names>', '<Table ss:ExpandedColumnCount="' + (visibleColumnCount + 2), '" ss:ExpandedRowCount="' + numGridRows + '" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="65" ss:DefaultRowHeight="15">', colXml, '<Row ss:Height="38">', '<Cell ss:MergeAcross="' + (visibleColumnCount - 1) + '" ss:StyleID="title">', '<Data ss:Type="String" xmlns:html="http://www.w3.org/TR/REC-html40">', '<html:b>' + theTitle + '</html:b></Data><NamedCell ss:Name="Print_Titles">', '</NamedCell></Cell>', '</Row>', '<Row ss:AutoFitHeight="1">', headerXml + '</Row>' ); // Generate the data rows from the data in the Store var groupVal = ""; for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) { if (!Ext.isEmpty(this.store.groupField)) { if (groupVal != this.store.getAt(i).get(this.store.groupField)) { groupVal = this.store.getAt(i).get(this.store.groupField); t += this.generateEmptyGroupRow(this.store.groupField, groupVal, cellType, includeHidden); } } t += '<Row>'; var cellClass = (i & 1) ? 'odd' : 'even'; r = it[i].data; var k = 0; for (var j = 0; j < colCount; j++) { if (cm[j].xtype != 'actioncolumn' && (cm[j].dataIndex != '') && (includeHidden || !cm[j].hidden)) { var v = r[cm[j].dataIndex]; if (cellType[k] !== "None") { t += '<Cell ss:StyleID="' + cellClass + cellTypeClass[k] + '"><Data ss:Type="' + cellType[k] + '">'; if (cellType[k] == 'DateTime') { t += Ext.Date.format(v, 'Y-m-d'); } else { t += v; } t += '</Data></Cell>'; } k++; } } t += '</Row>'; } result.xml = t.concat( '</Table>', '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">', '<PageLayoutZoom>0</PageLayoutZoom>', '<Selected/>', '<Panes>', '<Pane>', '<Number>3</Number>', '<ActiveRow>2</ActiveRow>', '</Pane>', '</Panes>', '<ProtectObjects>False</ProtectObjects>', '<ProtectScenarios>False</ProtectScenarios>', '</WorksheetOptions>', '</Worksheet>' ); return result; } });
htdocs/ext/ux/ExcelGridPanel.js
var Base64 = (function() { // private property var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // private method for UTF-8 encoding function utf8Encode(string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } // public method for encoding return { encode : (typeof btoa == 'function') ? function(input) { return btoa(input); } : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } }; })(); //http://druckit.wordpress.com/2013/10/26/generate-an-excel-file-from-an-ext-js-4-grid/ Ext.define('My.grid.ExcelGridPanel', { extend: 'Ext.grid.GridPanel', requires: 'Ext.form.action.StandardSubmit', /* Kick off process */ downloadExcelXml: function(includeHidden, title) { if (!title) title = this.title; var vExportContent = this.getExcelXml(includeHidden, title); var location = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + Base64.encode(vExportContent); /* dynamically create and anchor tag to force download with suggested filename note: download attribute is Google Chrome specific */ if (Ext.isChrome || Ext.isGecko) { // local download var gridEl = this.getEl(); var extension = 'xml'; if (Ext.isGecko) extension = 'xls'; var el = Ext.DomHelper.append(gridEl, { tag: "a", download: title + "-" + Ext.Date.format(new Date(), 'Y-m-d Hi') + '.'+extension, href: location }); el.click(); Ext.fly(el).destroy(); } else { // remote download var form = this.down('form#uploadForm'); if (form) { form.destroy(); } form = this.add({ xtype: 'form', itemId: 'uploadForm', hidden: true, standardSubmit: true, url: 'exportexcel.php', items: [{ xtype: 'hiddenfield', name: 'ex', value: vExportContent }] }); form.getForm().submit(); } }, /* Welcome to XML Hell See: http://msdn.microsoft.com/en-us/library/office/aa140066(v=office.10).aspx for more details */ getExcelXml: function(includeHidden, title) { var theTitle = title || this.title; var worksheet = this.createWorksheet(includeHidden, theTitle); var totalWidth = this.columns.length; return ''.concat( '<?xml version="1.0"?>', '<?mso-application progid="Excel.Sheet"?>', '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">', '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Title>' + theTitle + '</Title></DocumentProperties>', '<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office"><AllowPNG/></OfficeDocumentSettings>', '<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">', '<WindowHeight>' + worksheet.height + '</WindowHeight>', '<WindowWidth>' + worksheet.width + '</WindowWidth>', '<ProtectStructure>False</ProtectStructure>', '<ProtectWindows>False</ProtectWindows>', '</ExcelWorkbook>', '<Styles>', '<Style ss:ID="Default" ss:Name="Normal">', '<Alignment ss:Vertical="Bottom"/>', '<Borders/>', '<Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="12" ss:Color="#000000"/>', '<Interior/>', '<NumberFormat/>', '<Protection/>', '</Style>', '<Style ss:ID="title">', '<Borders />', '<Font ss:Bold="1" ss:Size="18" />', '<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="1" />', '<NumberFormat ss:Format="@" />', '</Style>', '<Style ss:ID="headercell">', '<Font ss:Bold="1" ss:Size="10" />', '<Alignment ss:Horizontal="Center" ss:WrapText="1" />', '<Interior ss:Color="#A3C9F1" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="even">', '<Interior ss:Color="#CCFFFF" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="evendate" ss:Parent="even">', '<NumberFormat ss:Format="yyyy-mm-dd" />', '</Style>', '<Style ss:ID="evenint" ss:Parent="even">', '<Numberformat ss:Format="0" />', '</Style>', '<Style ss:ID="evenfloat" ss:Parent="even">', '<Numberformat ss:Format="0.00" />', '</Style>', '<Style ss:ID="odd">', '<Interior ss:Color="#CCCCFF" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="groupSeparator">', '<Interior ss:Color="#D3D3D3" ss:Pattern="Solid" />', '</Style>', '<Style ss:ID="odddate" ss:Parent="odd">', '<NumberFormat ss:Format="yyyy-mm-dd" />', '</Style>', '<Style ss:ID="oddint" ss:Parent="odd">', '<NumberFormat Format="0" />', '</Style>', '<Style ss:ID="oddfloat" ss:Parent="odd">', '<NumberFormat Format="0.00" />', '</Style>', '</Styles>', worksheet.xml, '</Workbook>' ); }, /* Support function to return field info from store based on fieldname */ getModelField: function(fieldName) { var fields = this.store.model.getFields(); for (var i = 0; i < fields.length; i++) { if (fields[i].name === fieldName) { return fields[i]; } } }, /* Convert store into Excel Worksheet */ generateEmptyGroupRow: function(dataIndex, value, cellTypes, includeHidden) { var cm = this.columns; var colCount = this.columns.length; var rowTpl = '<Row ss:AutoFitHeight="0"><Cell ss:StyleID="groupSeparator" ss:MergeAcross="{0}"><Data ss:Type="String"><html:b>{1}</html:b></Data></Cell></Row>'; var visibleCols = 0; // rowXml += '<Cell ss:StyleID="groupSeparator">' for (var j = 0; j < colCount; j++) { if (cm[j].xtype != 'actioncolumn' && (cm[j].dataIndex != '') && (includeHidden || !cm[j].hidden)) { // rowXml += '<Cell ss:StyleID="groupSeparator"/>'; visibleCols++; } } // rowXml += "</Row>"; return Ext.String.format(rowTpl, visibleCols - 1, value); }, createWorksheet: function(includeHidden, theTitle) { // Calculate cell data types and extra class names which affect formatting var cellType = []; var cellTypeClass = []; var cm = this.columns; var totalWidthInPixels = 0; var colXml = ''; var headerXml = ''; var visibleColumnCountReduction = 0; var colCount = cm.length; for (var i = 0; i < colCount; i++) { if (cm[i].xtype != 'actioncolumn' && (cm[i].dataIndex != '') && (includeHidden || !cm[i].hidden)) { var w = cm[i].getEl().getWidth(); totalWidthInPixels += w; if (cm[i].text === "") { cellType.push("None"); cellTypeClass.push(""); ++visibleColumnCountReduction; } else { colXml += '<Column ss:AutoFitWidth="1" ss:Width="' + w + '" />'; headerXml += '<Cell ss:StyleID="headercell">' + '<Data ss:Type="String">' + cm[i].text + '</Data>' + '<NamedCell ss:Name="Print_Titles"></NamedCell></Cell>'; var fld = this.getModelField(cm[i].dataIndex); switch (fld.type.type) { case "int": cellType.push("Number"); cellTypeClass.push("int"); break; case "float": cellType.push("Number"); cellTypeClass.push("float"); break; case "bool": case "boolean": cellType.push("String"); cellTypeClass.push(""); break; case "date": cellType.push("DateTime"); cellTypeClass.push("date"); break; default: cellType.push("String"); cellTypeClass.push(""); break; } } } } var visibleColumnCount = cellType.length - visibleColumnCountReduction; var result = { height: 9000, width: Math.floor(totalWidthInPixels * 30) + 50 }; // Generate worksheet header details. // determine number of rows var numGridRows = this.store.getCount() + 2; if (!Ext.isEmpty(this.store.groupField)) { numGridRows = numGridRows + this.store.getGroups().length; } // create header for worksheet var t = ''.concat( '<Worksheet ss:Name="myworksheet">', '<Names>', '<NamedRange ss:Name="Print_Titles" ss:RefersTo="=\'myworksheet\'!R1:R2">', '</NamedRange></Names>', '<Table ss:ExpandedColumnCount="' + (visibleColumnCount + 2), '" ss:ExpandedRowCount="' + numGridRows + '" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="65" ss:DefaultRowHeight="15">', colXml, '<Row ss:Height="38">', '<Cell ss:MergeAcross="' + (visibleColumnCount - 1) + '" ss:StyleID="title">', '<Data ss:Type="String" xmlns:html="http://www.w3.org/TR/REC-html40">', '<html:b>' + theTitle + '</html:b></Data><NamedCell ss:Name="Print_Titles">', '</NamedCell></Cell>', '</Row>', '<Row ss:AutoFitHeight="1">', headerXml + '</Row>' ); // Generate the data rows from the data in the Store var groupVal = ""; for (var i = 0, it = this.store.data.items, l = it.length; i < l; i++) { if (!Ext.isEmpty(this.store.groupField)) { if (groupVal != this.store.getAt(i).get(this.store.groupField)) { groupVal = this.store.getAt(i).get(this.store.groupField); t += this.generateEmptyGroupRow(this.store.groupField, groupVal, cellType, includeHidden); } } t += '<Row>'; var cellClass = (i & 1) ? 'odd' : 'even'; r = it[i].data; var k = 0; for (var j = 0; j < colCount; j++) { if (cm[j].xtype != 'actioncolumn' && (cm[j].dataIndex != '') && (includeHidden || !cm[j].hidden)) { var v = r[cm[j].dataIndex]; if (cellType[k] !== "None") { t += '<Cell ss:StyleID="' + cellClass + cellTypeClass[k] + '"><Data ss:Type="' + cellType[k] + '">'; if (cellType[k] == 'DateTime') { t += Ext.Date.format(v, 'Y-m-d'); } else { t += v; } t += '</Data></Cell>'; } k++; } } t += '</Row>'; } result.xml = t.concat( '</Table>', '<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">', '<PageLayoutZoom>0</PageLayoutZoom>', '<Selected/>', '<Panes>', '<Pane>', '<Number>3</Number>', '<ActiveRow>2</ActiveRow>', '</Pane>', '</Panes>', '<ProtectObjects>False</ProtectObjects>', '<ProtectScenarios>False</ProtectScenarios>', '</WorksheetOptions>', '</Worksheet>' ); return result; } });
use xlsx for firefox
htdocs/ext/ux/ExcelGridPanel.js
use xlsx for firefox
<ide><path>tdocs/ext/ux/ExcelGridPanel.js <ide> if (Ext.isChrome || Ext.isGecko) { // local download <ide> var gridEl = this.getEl(); <ide> var extension = 'xml'; <del> if (Ext.isGecko) extension = 'xls'; <add> if (Ext.isGecko) extension = 'xlsx'; <ide> var el = Ext.DomHelper.append(gridEl, { <ide> tag: "a", <ide> download: title + "-" + Ext.Date.format(new Date(), 'Y-m-d Hi') + '.'+extension,
Java
bsd-2-clause
545c4c4b4d4594a1b36c304a978b6e9922aeaed3
0
clementval/claw-compiler,clementval/claw-compiler
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package claw.wani.transformation.sca; import claw.shenron.transformation.Transformation; import claw.shenron.translator.Translator; import claw.tatsu.common.*; import claw.tatsu.directive.common.Directive; import claw.tatsu.primitive.*; import claw.tatsu.xcodeml.abstraction.AssignStatement; import claw.tatsu.xcodeml.abstraction.DimensionDefinition; import claw.tatsu.xcodeml.abstraction.NestedDoStatement; import claw.tatsu.xcodeml.abstraction.PromotionInfo; import claw.tatsu.xcodeml.exception.IllegalTransformationException; import claw.tatsu.xcodeml.xnode.XnodeUtil; import claw.tatsu.xcodeml.xnode.common.*; import claw.tatsu.xcodeml.xnode.fortran.*; import claw.wani.language.ClawPragma; import claw.wani.transformation.ClawTransformation; import claw.wani.x2t.configuration.Configuration; import claw.wani.x2t.configuration.AcceleratorConfiguration; import claw.wani.x2t.configuration.AcceleratorLocalStrategy; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * The Single Column Abstraction (SCA) transformation transforms the code * contained in a subroutine/function by adding necessary dimensions and * parallelism to the defined data. * * Transformation for the GPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Do statements over the additional dimensions is added as an outer * loop and wrap the entire body of the subroutine. * </ul> * * Transformation for the CPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Propagated promotion is applied to all scalars or arrays used in an * assign statement at the lhs and where a promoted variable is used on the * rhs. * <li> Do statements over the additional dimensions are added as an inner * loop wrapping each assign statements including promoted variables. * </ul> * * Generation of OpenACC directives:<ul> * <li> acc routine seq is generated for subroutine called from the parallelized * subroutine if they are located in the same translation unit. * <li> acc data region with corresponding present clause for all promoted * variables with the intent in, out or inout. * <li> acc parallel region is generated to wrap all the body of the subroutine. * <li> acc private clause is added to the parallel directive for all local * variables. * <li> acc loop is generated for the generated do statement. * <li> acc loop seq is generated for already existing do statements. * </ul> * * Generation of OpenMP directives on CPU: <ul> * <li> omp parallel do is generated for each generated do statements. * </ul> * * Generation of OpenMP directives on GPU:<ul> * <li> MISSING FEATURE : omp declare target is generated for subroutine called from the parallelized * subroutine if they are located in the same translation unit. * <li> omp data region with corresponding present clause for all promoted * variables with the intent to, from or tofrom. * <li> omp target teams distribute region is generated to wrap all the body of the subroutine. * <li> omp private clause is added to the target directive for all local * variables. * <li> omp collapse is generated for the generated do statement (if more that 1). * </ul> * * @author clementval */ public class Parallelize extends ClawTransformation { private final Map<String, DimensionDefinition> _dimensions; private final Map<String, PromotionInfo> _promotions; private final Set<String> _arrayFieldsInOut; private final Set<String> _scalarFields; private int _overDimensions; private FfunctionDefinition _fctDef; private FfunctionType _fctType; /** * Constructs a new Parallelize transformation triggered from a specific * pragma. * * @param directive The directive that triggered the define transformation. */ public Parallelize(ClawPragma directive) { super(directive); _overDimensions = 0; _dimensions = new HashMap<>(); _promotions = new HashMap<>(); _arrayFieldsInOut = new HashSet<>(); _scalarFields = new HashSet<>(); } /** * Print information about promoted arrays, candidate for promotion arrays and * scalars. * * @param name Name of the subroutine. * @param promoted List of promoted array variables. * @param candidateArrays List of candidate array variables for promotion. * @param scalars List of candidate scalar variables for promotion. */ private void printDebugPromotionInfos(String name, Set<String> promoted, List<String> candidateArrays, List<String> scalars) { Message.debug("=========================================="); Message.debug("Parallelize promotion infos for subroutine " + name); Message.debug(" - Promoted arrays(" + promoted.size() + "):"); for(String array : promoted) { Message.debug(" " + array); } Message.debug(" - Candidate arrays(" + candidateArrays.size() + "):"); for(String array : candidateArrays) { Message.debug(" " + array); } Message.debug(" - Candidate scalars(" + scalars.size() + "):"); for(String array : scalars) { Message.debug(" " + array); } Message.debug("=========================================="); } @Override public boolean analyze(XcodeProgram xcodeml, Translator translator) { // Check for the parent fct/subroutine definition _fctDef = _claw.getPragma().findParentFunction(); if(_fctDef == null) { xcodeml.addError("Parent function/subroutine cannot be found. " + "Parallelize directive must be defined in a function/subroutine.", _claw.getPragma().lineNo()); return false; } _fctType = xcodeml.getTypeTable().getFunctionType(_fctDef); if(_fctType == null) { xcodeml.addError("Function/subroutine signature cannot be found. ", _claw.getPragma().lineNo()); return false; } /* Check if unsupported statements are located in the future parallel * region. */ if(Context.isTarget(Target.GPU) && (Context.get().getGenerator().getDirectiveLanguage() != CompilerDirective.NONE)) { Xnode contains = _fctDef.body().matchSeq(Xcode.F_CONTAINS_STATEMENT); Xnode parallelRegionStart = Directive.findParallelRegionStart(_fctDef, null); Xnode parallelRegionEnd = Directive.findParallelRegionEnd(_fctDef, contains); List<Xnode> unsupportedStatements = XnodeUtil.getNodes(parallelRegionStart, parallelRegionEnd, Context.get().getGenerator().getUnsupportedStatements()); if(unsupportedStatements.size() > 0) { for(Xnode statement : unsupportedStatements) { xcodeml.addError("Unsupported statement in parallel region", statement.lineNo()); } return false; } } return analyzeDimension(xcodeml) && analyzeData(xcodeml) && analyzeOver(xcodeml); } /** * Analyse the defined dimension. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeDimension(XcodeProgram xcodeml) { if(!_claw.hasDimensionClause()) { xcodeml.addError("No dimension defined for parallelization.", _claw.getPragma().lineNo()); return false; } for(DimensionDefinition d : _claw.getDimensionValues()) { if(_dimensions.containsKey(d.getIdentifier())) { xcodeml.addError( String.format("Dimension with identifier %s already specified.", d.getIdentifier()), _claw.getPragma().lineNo() ); return false; } _dimensions.put(d.getIdentifier(), d); } return true; } /** * Analyse the information defined in the data clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeData(XcodeProgram xcodeml) { /* If there is no data/over clause specified, an automatic deduction for * array promotion is performed. */ if(!_claw.hasOverDataClause()) { List<String> scalars = new ArrayList<>(); List<String> candidateArrays = new ArrayList<>(); List<Xnode> declarations = _fctDef.getDeclarationTable().values(); for(Xnode decl : declarations) { if(decl.opcode() != Xcode.VAR_DECL) { continue; } if(xcodeml.getTypeTable().isBasicType(decl)) { String varName = decl.matchSeq(Xcode.NAME).value(); FbasicType bType = xcodeml.getTypeTable().getBasicType(decl); if(bType.isArray()) { if(bType.hasIntent() || bType.isPointer()) { _arrayFieldsInOut.add(varName); } else { candidateArrays.add(varName); } } else { if(_claw.hasScalarClause() && _claw.getScalarClauseValues().contains(varName)) { _arrayFieldsInOut.add(varName); } if(!bType.isParameter() && bType.hasIntent()) { scalars.add(varName); } } } } _scalarFields.addAll(scalars); _scalarFields.addAll(candidateArrays); printDebugPromotionInfos(_fctDef.getName(), _arrayFieldsInOut, candidateArrays, scalars); return true; } /* If the data clause if defined at least once, manual promotion is the * rule. The array identifiers defined in the data clauses will be used as * the list of array to be promoted. * In the analysis, we control that all defined arrays in the data clauses * are actual declared variables. */ for(List<String> data : _claw.getOverDataClauseValues()) { for(String d : data) { if(!_fctDef.getSymbolTable().contains(d)) { xcodeml.addError( String.format("Data %s is not defined in the current block.", d), _claw.getPragma().lineNo() ); return false; } if(!_fctDef.getDeclarationTable().contains(d)) { xcodeml.addError( String.format("Data %s is not declared in the current block.", d), _claw.getPragma().lineNo() ); return false; } } _arrayFieldsInOut.addAll(data); } return true; } /** * Analyse the information defined in the over clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeOver(XcodeProgram xcodeml) { if(!_claw.hasOverClause()) { _overDimensions += _claw.getDimensionValues().size(); return true; } // Check if over dimensions are defined dimensions _overDimensions = _claw.getDimensionValues().size(); for(List<String> overLst : _claw.getOverClauseValues()) { int usedDimension = 0; for(String o : overLst) { if(!o.equals(DimensionDefinition.BASE_DIM)) { if(!_dimensions.containsKey(o)) { xcodeml.addError( String.format( "Dimension %s is not defined. Cannot be used in over " + "clause", o), _claw.getPragma().lineNo() ); return false; } ++usedDimension; } } if(usedDimension != _overDimensions) { xcodeml.addError("Over clause doesn't use one or more defined " + "dimensions", _claw.getPragma().lineNo()); return false; } } return true; } @Override public void transform(XcodeProgram xcodeml, Translator translator, Transformation other) throws Exception { // Handle PURE function / subroutine boolean pureRemoved = _fctType.isPure(); _fctType.removeAttribute(Xattr.IS_PURE); if(Configuration.get().isForcePure() && pureRemoved) { throw new IllegalTransformationException( "PURE specifier cannot be removed", _fctDef.lineNo()); } else if(pureRemoved) { String fctName = _fctDef.matchDirectDescendant(Xcode.NAME).value(); xcodeml.addWarning("PURE specifier removed from function " + fctName + ". Transformation and code generation applied to it.", _fctDef.lineNo()); } // Insert the declarations of variables to iterate over the new dimensions. insertVariableToIterateOverDimension(xcodeml); // Promote all array fields with new dimensions. promoteFields(xcodeml); // Adapt array references. if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { for(String id : _claw.getOverDataClauseValues().get(i)) { Field.adaptArrayRef(_promotions.get(id), _fctDef.body(), xcodeml); } } } else { for(String id : _arrayFieldsInOut) { Field.adaptArrayRef(_promotions.get(id), _fctDef.body(), xcodeml); } } removePragma(); // Apply specific target transformation if(Context.isTarget(Target.GPU)) { transformForGPU(xcodeml); } else if(Context.isTarget(Target.CPU) || Context.isTarget(Target.ARM)) { // Choose which mode to use switch (Configuration.get().getParameter(Configuration.CPU_STRATEGY)) { case Configuration.CPU_STRATEGY_FUSION: transformFusionForCPU(xcodeml); break; case Configuration.CPU_STRATEGY_SINGLE: default: transformForCPU(xcodeml); break; } } else { throw new IllegalTransformationException("Unsupported target " + Context.get().getTarget(), _claw.getPragma().lineNo()); } if(!_fctType.getBooleanAttribute(Xattr.IS_PRIVATE)) { FmoduleDefinition modDef = _fctDef.findParentModule(); if(modDef != null) { Xmod.updateSignature(modDef.getName(), xcodeml, _fctDef, _fctType, false); } } } /** * Apply GPU based transformation. * * @param xcodeml Current XcodeML program unit. */ private void transformForGPU(XcodeProgram xcodeml) throws IllegalTransformationException { AcceleratorConfiguration accConfig = Configuration.get().accelerator(); // TODO nodep should be passed in another way. int collapse = Directive.generateLoopSeq(xcodeml, _fctDef, CompilerDirective.CLAW.getPrefix() + " nodep"); if(!Body.isEmpty(_fctDef.body())) { /* Create a nested loop with the new defined dimensions and wrap it around * the whole subroutine's body. This is for the moment a really naive * transformation idea but it is our start point. * Use the first over clause to create it. */ NestedDoStatement loops = new NestedDoStatement(_claw.getDimensionValuesReversed(), xcodeml); /* Subroutine/function can have a contains section with inner subroutines * or functions. The newly created (nested) do statements should stop * before this contains section if it exists. */ Xnode contains = _fctDef.body().matchSeq(Xcode.F_CONTAINS_STATEMENT); if(contains != null) { Xnode parallelRegionStart = Directive.findParallelRegionStart(_fctDef, null); Xnode parallelRegionEnd = Directive.findParallelRegionEnd(_fctDef, contains); Body.shiftIn(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); contains.insertBefore(loops.getOuterStatement()); } else { // No contains section, all the body is copied to the do statements. Xnode parallelRegionStart = Directive.findParallelRegionStart(_fctDef, null); Xnode parallelRegionEnd = Directive.findParallelRegionEnd(_fctDef, null); // Define a hook from where we can insert the new do statement Xnode hook = parallelRegionEnd != null ? parallelRegionEnd.nextSibling() : null; Body.shiftIn(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); // Hook is null then we append the do statement to the current fct body if(hook == null) { _fctDef.body().append(loops.getOuterStatement()); } else { // Insert new do statement before the hook element hook.insertBefore(loops.getOuterStatement()); } } // Prepare variables list for present/pcreate clauses and handle // promotion/privatize local strategy List<String> presentList = Directive.getPresentVariables(xcodeml, _fctDef); List<String> privateList = Collections.emptyList(); List<String> createList = Collections.emptyList(); if(accConfig.getLocalStrategy() == AcceleratorLocalStrategy.PRIVATE) { privateList = Directive.getLocalArrays(xcodeml, _fctDef); // Iterate over a copy to be able to remove items for(String identifier : new ArrayList<>(privateList)) { if(_promotions.containsKey(identifier)) { privateList.remove(identifier); } } } else if(accConfig.getLocalStrategy() == AcceleratorLocalStrategy.PROMOTE) { createList = Directive.getLocalArrays(xcodeml, _fctDef); for(String arrayIdentifier : createList) { _arrayFieldsInOut.add(arrayIdentifier); PromotionInfo promotionInfo = new PromotionInfo(arrayIdentifier, _claw.getDimensionsForData(arrayIdentifier)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(arrayIdentifier, promotionInfo); Field.adaptArrayRef(promotionInfo, _fctDef.body(), xcodeml); Field.adaptAllocate(promotionInfo, _fctDef.body(), xcodeml); } } // Generate the data region Directive.generateDataRegionClause(xcodeml, presentList, createList, loops.getOuterStatement(), loops.getOuterStatement()); // Generate the parallel region Directive.generateParallelLoopClause(xcodeml, privateList, loops.getOuterStatement(), loops.getOuterStatement(), loops.size() + collapse); } Directive.generateRoutineDirectives(xcodeml, _fctDef); } /** * Apply a CPU transformation which group adjacent statements together and * promote the minimum number of variables possible. * * @param xcodeml Current XcodeML program unit. * @throws IllegalTransformationException If promotion of arrays fails. */ private void transformFusionForCPU(XcodeProgram xcodeml) throws IllegalTransformationException { // Apply transformation only when there is a body to modify if (Body.isEmpty(_fctDef.body())) { return; } // Variables on each "depth" of the method List<Set<String>> depthVars = new ArrayList<>(); depthVars.add(new HashSet<String>()); // A growing list of affecting variables. Starting from the ones // declared by SCA and successively any variables affected by the SCA // declaration Set<String> affectingVars = new HashSet<>(_promotions.keySet()); //affectingVars.addAll(_arrayFieldsInOut); // Extract all the variables used, this doesn't include vector's // iterator variables transformFusionForCPUExtraction(_fctDef.body(), new AtomicInteger(), depthVars, affectingVars); // Find the block we need to transform List<Set<String>> targetDepthIntersections = new ArrayList<>(); for (int i = 0; i < depthVars.size(); i++) { Set<String> depthVar = depthVars.get(i); if (depthVar.isEmpty()) { targetDepthIntersections.add(null); continue; } // Find intersection with other blocks Set<String> intersection = new HashSet<>(); for (int j = 0; j < depthVars.size(); j++) { // Skip itself if (i == j) { continue; } // Intersect the level set with the others Set<String> copy = new HashSet<>(depthVars.get(i)); copy.retainAll(depthVars.get(j)); intersection.addAll(copy); } // All are on the same index targetDepthIntersections.add(intersection); } // Gather all possible loop groups before their modification List<List<Xnode>> transformations = new ArrayList<>(); // Apply transformation at the indicated depth for (int targetDepth = 0; targetDepth < depthVars.size(); targetDepth++) { Set<String> vars = depthVars.get(targetDepth); if (vars.isEmpty()) continue; Set<String> intersection = targetDepthIntersections.get(targetDepth); // Variables still waiting for a promotion which aren't promoted yet Set<String> promotions = new HashSet<>(intersection); // Check only the LHS arrays Set<String> vectorType = new HashSet<>(vars); vectorType.retainAll(affectingVars); // Influenced arrays must be promoted anyway for (String var : vectorType) { Xid fieldId = _fctDef.getSymbolTable().get(var); FbasicType type = xcodeml.getTypeTable().getBasicType(fieldId); if (type != null && type.isArray()) { promotions.add(var); } } // Promote for (String promotion : promotions) { if (_promotions.containsKey(promotion)) { continue; } PromotionInfo promotionInfo = new PromotionInfo(promotion, _claw.getDimensionsForData(promotion)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(promotion, promotionInfo); Field.adaptArrayRef(promotionInfo, _fctDef.body(), xcodeml); Field.adaptAllocate(_promotions.get(promotion), _fctDef.body(), xcodeml); } // Transform indicated level by wrapping it in a DO loop transformFusionForCPUGather(_fctDef.body(), new AtomicInteger(), targetDepth, affectingVars, transformations); } // After gathering we apply the transformations for (List<Xnode> transformation : transformations) { transformFusionForCPUApply(transformation, xcodeml); } // If the last statement is a CONTAINS, fallback to the previous one Xnode lastNode = _fctDef.body().lastChild(); while (lastNode.opcode() == Xcode.F_CONTAINS_STATEMENT) { lastNode = lastNode.prevSibling(); } // Generate the parallel region Directive.generateParallelClause(xcodeml, _fctDef.body().firstChild(), lastNode); } /** * Analysis of a routine in order to extracts the information necessary in * order to promote a minimal number of variables. * Only variables affected by affectingVars are kept in depthVars. * * @param body The body to analyze. * @param depth The depth relative to the function declaration. * @param depthVars Vars used on each depth. * @param affectingVars Vars which are affected by SCA and consequently * affect other variables. */ private void transformFusionForCPUExtraction(Xnode body, AtomicInteger depth, List<Set<String>> depthVars, Set<String> affectingVars) { final List<Xnode> children = body.children(); for (Xnode node : children) { // Handle an assignment if (node.opcode() == Xcode.F_ASSIGN_STATEMENT) { AssignStatement as = new AssignStatement(node.element()); Set<String> vars = XnodeUtil.findChildrenVariables(node); // Check if it's affected by the promotion Set<String> affectedVars = new HashSet<>(vars); affectedVars.retainAll(affectingVars); // If the intersection of the sets contain anything the assignment is // affected by a previous promotions depthVars.get(depth.get()).addAll(affectedVars); if (!affectedVars.isEmpty()) { affectingVars.add(as.getLhsName()); depthVars.get(depth.get()).add(as.getLhsName()); } } // IF statement content shouldn't increase depth counter else if (node.opcode() == Xcode.F_IF_STATEMENT) { Xnode nThen = node.firstChild().matchSibling(Xcode.THEN); Xnode nElse = node.firstChild().matchSibling(Xcode.ELSE); if (nThen != null) { transformFusionForCPUExtraction(nThen.body(), depth, depthVars, affectingVars); } if (nElse != null) { transformFusionForCPUExtraction(nElse.body(), depth, depthVars, affectingVars); } } // Handle node containing a body else if (node.opcode().hasBody()) { if (depthVars.size() <= depth.get() + 1) { depthVars.add(new HashSet<String>()); } depth.incrementAndGet(); transformFusionForCPUExtraction(node.body(), depth, depthVars, affectingVars); } // Keep going inside the new node else { transformFusionForCPUExtraction(node, depth, depthVars, affectingVars); } } } /** * Transform the content of the routine and add a DO loop only at the * indicated depth and only around the affecting variables. * * @param body The body to transform. * @param currentDepth The depth we currently are at * @param targetDepth The depth we need to reach and transform. * @param affectingVars The variable which should be contained inside the loop */ private void transformFusionForCPUGather(Xnode body, AtomicInteger currentDepth, final int targetDepth, Set<String> affectingVars, List<List<Xnode>> toapply) { final List<Xnode> children = body.children(); final List<Xnode> hooks = new ArrayList<>(); nodeLoop: for (Xnode node : children) { // Handle an assignment if (node.opcode() == Xcode.F_ASSIGN_STATEMENT) { if (currentDepth.get() != targetDepth) continue; Set<String> vars = XnodeUtil.findChildrenVariables(node); // Statement need to be in the loop if (Utility.hasIntersection(vars, affectingVars)) { // Is the statement wasn't promoted and is not in a current loop // block, we can avoid to add it to a loop because it is not needed. AssignStatement as = new AssignStatement(node.element()); if (!_promotions.containsKey(as.getLhsName()) && hooks.isEmpty() && as.getVarRefNames().size() == 0) { continue; } // If the assignment is a vector, but we don't access its elements // we don't have to add it to a loop if (_promotions.containsKey(as.getLhsName()) && as.getVarRefNames().size() == 0) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); continue; } hooks.add(node); } // Particular case, unused variable inside the body else { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); } } // IF statement my have to be contained inside else if (node.opcode() == Xcode.F_IF_STATEMENT) { // Enter the if in case it contains DO statements if (currentDepth.get() != targetDepth) { Xnode nThen = node.firstChild().matchSibling(Xcode.THEN); Xnode nElse = node.firstChild().matchSibling(Xcode.ELSE); if (nThen != null) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); transformFusionForCPUGather(nThen.body(), currentDepth, targetDepth, affectingVars, toapply); } if (nElse != null) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); transformFusionForCPUGather(nElse.body(), currentDepth, targetDepth, affectingVars, toapply); } continue; } // We need to wrap the whole IF based on the condition Xnode condNode = node.firstChild().matchSibling(Xcode.CONDITION); if (Condition.dependsOn(condNode, affectingVars)) { hooks.add(node); continue nodeLoop; } // We need to wrap the whole IF based on the statement inside List<Xnode> statNode = node.matchAll(Xcode.F_ASSIGN_STATEMENT); xNodeLoop: for (Xnode xnode : statNode) { AssignStatement as = new AssignStatement(xnode.element()); if (affectingVars.contains(as.getLhsName())) { // If the affected node is child of a DO, a dedicated loop // group will be created. Xnode pnode = xnode.ancestor(); while (pnode.hashCode() != node.hashCode()) { if (pnode.opcode() == Xcode.F_DO_STATEMENT) { break xNodeLoop; } pnode = pnode.ancestor(); } // Add the whole if and continue otherwise hooks.add(node); continue nodeLoop; } } // If the IF statement doesn't contains any dependency we gather the // potential transformation and continue transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); } // Handle node containing a body else if (node.opcode().hasBody()) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); currentDepth.incrementAndGet(); transformFusionForCPUGather(node.body(), currentDepth, targetDepth, affectingVars, toapply); } // Keep going inside the new node else { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); transformFusionForCPUGather(node, currentDepth, targetDepth, affectingVars, toapply); } } transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); } /** * If a hooks group that will be wrapped exists, add it to the collection * containing all the hooks group found until now. * The content of `hooks` is copied in a new list and added to `toapply`, * while `hooks` will be cleared of its content. * * @param hooks A list of adjacent nodes to be wrapped in a DO statement * @param toapply A list to add a copy of `hooks` */ private void transformFusionForCPUGatherSaveHooksGroup(List<Xnode> hooks, List<List<Xnode>> toapply) { if (!hooks.isEmpty()) { toapply.add(new ArrayList<>(hooks)); hooks.clear(); } } /** * Given a series of sequential hooks (nodes), envelope them in a DO loop. * * @param hooks List of nodes do envelope in a DO statement * @param xcodeml The program */ private void transformFusionForCPUApply(List<Xnode> hooks, XcodeProgram xcodeml) { if (hooks.isEmpty()) { return; } NestedDoStatement loop = new NestedDoStatement(_claw.getDimensionValuesReversed(), xcodeml); // Add loop to AST hooks.get(0).insertBefore(loop.getOuterStatement()); for(Xnode hook : hooks) { loop.getInnerStatement().body().append(hook, false); } Directive.generateLoopDirectives(xcodeml, loop.getOuterStatement(), loop.getOuterStatement(), Directive.NO_COLLAPSE); hooks.clear(); } /** * Apply CPU based transformations. * * @param xcodeml Current XcodeML program unit. * @throws IllegalTransformationException If promotion of arrays fails. */ private void transformForCPU(XcodeProgram xcodeml) throws IllegalTransformationException { /* Create a group of nested loop with the newly defined dimension and wrap * every assignment statement in the column loop or including data with it. * This is for the moment a really naive transformation idea but it is our * start point. * Use the first over clause to do it. */ List<AssignStatement> assignStatements = Function.gatherAssignStatements(_fctDef); // Iterate over all assign statements to detect all the indirect promotion. for (AssignStatement assign : assignStatements) { Xnode lhs = assign.getLhs(); String lhsName = assign.getLhsName(); if (lhs.opcode() == Xcode.VAR || lhs.opcode() == Xcode.F_ARRAY_REF) { /* If the assignment is in the column loop and is composed with some * promoted variables, the field must be promoted and the var reference * switch to an array reference */ PromotionInfo promotionInfo; if (shouldBePromoted(assign)) { // Do the promotion if needed if (!_arrayFieldsInOut.contains(lhsName)) { _arrayFieldsInOut.add(lhsName); promotionInfo = new PromotionInfo(lhsName, _claw.getDimensionsForData(lhsName)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(lhsName, promotionInfo); } else { promotionInfo = _promotions.get(lhsName); } // Adapt references if (lhs.opcode() == Xcode.VAR) { Field.adaptScalarRefToArrayRef(lhsName, _fctDef, _claw.getDimensionValues(), xcodeml); } else { Field.adaptArrayRef(_promotions.get(lhsName), _fctDef.body(), xcodeml); Field.adaptAllocate(_promotions.get(lhsName), _fctDef.body(), xcodeml); } promotionInfo.setRefAdapted(); } } } // Hold hooks on which do statement will be inserted Set<Xnode> hooks = new HashSet<>(); /* Check whether condition includes a promoted variables. If so, the * ancestor node using the condition must be wrapped in a do statement. */ List<Xnode> conditions = _fctDef.body().matchAll(Xcode.CONDITION); for (Xnode condition : conditions) { if (Condition.dependsOn(condition, _arrayFieldsInOut)) { Xnode ancestor = condition.ancestor(); Iterator<Xnode> iter = hooks.iterator(); boolean addHook = true; while (iter.hasNext()) { if (ancestor.isNestedIn(iter.next())) { addHook = false; break; } } if (addHook) { hooks.add(ancestor); } } } /* Iterate a second time over assign statements to flag places where to * insert the do statements */ for (AssignStatement assign : assignStatements) { Xnode lhs = assign.getLhs(); String lhsName = assign.getLhsName(); boolean wrapInDoStatement = true; // Check if assignment is dependant of an if statement. if (assign.isChildOf(Xcode.F_IF_STATEMENT)) { // Gather all potential ancestor if statements List<Xnode> ifStatements = assign.matchAllAncestor(Xcode.F_IF_STATEMENT, Xcode.F_FUNCTION_DEFINITION); Xnode hookIfStmt = null; for (Xnode ifStmt : ifStatements) { if (Condition.dependsOn( ifStmt.matchDirectDescendant(Xcode.CONDITION), assign.getVarRefNames())) { // Have to put the do statement around the if as the assignment // is conditional as well. hookIfStmt = ifStmt; } } if (hookIfStmt != null) { wrapInDoStatement = false; boolean addIfHook = true; // Get rid of previously flagged hook in this if body. Iterator<Xnode> iter = hooks.iterator(); while (iter.hasNext()) { Xnode crt = iter.next(); if (assign.isNestedIn(crt) || hookIfStmt.isNestedIn(crt)) { addIfHook = false; } if (crt.isNestedIn(hookIfStmt)) { iter.remove(); } } if (addIfHook) { hooks.add(hookIfStmt); } } } Iterator<Xnode> iter = hooks.iterator(); while (iter.hasNext()) { if (assign.isNestedIn(iter.next())) { wrapInDoStatement = false; break; } } if (lhs.opcode() == Xcode.F_ARRAY_REF && _arrayFieldsInOut.contains(lhsName) && wrapInDoStatement) { hooks.add(assign); } else if (lhs.opcode() == Xcode.VAR || lhs.opcode() == Xcode.F_ARRAY_REF && _scalarFields.contains(lhsName)) { if (shouldBePromoted(assign) && wrapInDoStatement) { hooks.add(assign); } } } // Generate loops around statements flagged in previous stage for (Xnode hook : hooks) { NestedDoStatement loops = new NestedDoStatement(_claw.getDimensionValuesReversed(), xcodeml); hook.insertAfter(loops.getOuterStatement()); loops.getInnerStatement().body().append(hook, true); hook.delete(); Directive.generateLoopDirectives(xcodeml, loops.getOuterStatement(), loops.getOuterStatement(), Directive.NO_COLLAPSE); } // Generate the parallel region Directive.generateParallelClause(xcodeml, _fctDef.body().firstChild(), _fctDef.body().lastChild()); } /** * Check whether the LHS variable should be promoted. * * @param assignStmt Assign statement node. * @return True if the LHS variable should be promoted. False otherwise. */ private boolean shouldBePromoted(Xnode assignStmt) { Xnode rhs = assignStmt.child(Xnode.RHS); if (rhs == null) { return false; } List<Xnode> vars = XnodeUtil.findAllReferences(rhs); Set<String> names = XnodeUtil.getNamesFromReferences(vars); return Utility.hasIntersection(names, _arrayFieldsInOut); } /** * Promote all fields declared in the data clause with the additional * dimensions. * * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void promoteFields(XcodeProgram xcodeml) throws IllegalTransformationException { if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { for(String fieldId : _claw.getOverDataClauseValues().get(i)) { PromotionInfo promotionInfo = new PromotionInfo(fieldId, _claw.getDimensionsForData(fieldId)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(fieldId, promotionInfo); } } } else { // Promote all arrays in a similar manner for(String fieldId : _arrayFieldsInOut) { PromotionInfo promotionInfo = new PromotionInfo(fieldId, _claw.getDimensionsForData(fieldId)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(fieldId, promotionInfo); } } } /** * Insert the declaration of the different variables needed to iterate over * the additional dimensions. * * @param xcodeml Current XcodeML program unit in which element are * created. */ private void insertVariableToIterateOverDimension(XcodeProgram xcodeml) { // Create type and declaration for iterations over the new dimensions FbasicType bt = xcodeml.createBasicType(FortranType.INTEGER, Intent.IN); xcodeml.getTypeTable().add(bt); // For each dimension defined in the directive for(DimensionDefinition dimension : _claw.getDimensionValues()) { // Create the parameter for the lower bound if(dimension.getLowerBound().isVar()) { xcodeml.createIdAndDecl(dimension.getLowerBound().getValue(), bt.getType(), XstorageClass.F_PARAM, _fctDef, DeclarationPosition.FIRST); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam( dimension.getLowerBound().getValue(), bt.getType(), _fctType); param.setBooleanAttribute(Xattr.IS_INSERTED, true); } // Create parameter for the upper bound if(dimension.getUpperBound().isVar()) { xcodeml.createIdAndDecl(dimension.getUpperBound().getValue(), bt.getType(), XstorageClass.F_PARAM, _fctDef, DeclarationPosition.FIRST); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam( dimension.getUpperBound().getValue(), bt.getType(), _fctType); param.setBooleanAttribute(Xattr.IS_INSERTED, true); } // Create induction variable declaration xcodeml.createIdAndDecl(dimension.getIdentifier(), FortranType.INTEGER, XstorageClass.F_LOCAL, _fctDef, DeclarationPosition.LAST); } } /** * @return Always false as independent transformation are applied one by one. * @see Transformation#canBeTransformedWith(XcodeProgram, Transformation) */ @Override public boolean canBeTransformedWith(XcodeProgram xcodeml, Transformation other) { return false; // This is an independent transformation } }
cx2t/src/claw/wani/transformation/sca/Parallelize.java
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package claw.wani.transformation.sca; import claw.shenron.transformation.Transformation; import claw.shenron.translator.Translator; import claw.tatsu.common.*; import claw.tatsu.directive.common.Directive; import claw.tatsu.primitive.*; import claw.tatsu.xcodeml.abstraction.AssignStatement; import claw.tatsu.xcodeml.abstraction.DimensionDefinition; import claw.tatsu.xcodeml.abstraction.NestedDoStatement; import claw.tatsu.xcodeml.abstraction.PromotionInfo; import claw.tatsu.xcodeml.exception.IllegalTransformationException; import claw.tatsu.xcodeml.xnode.XnodeUtil; import claw.tatsu.xcodeml.xnode.common.*; import claw.tatsu.xcodeml.xnode.fortran.*; import claw.wani.language.ClawPragma; import claw.wani.transformation.ClawTransformation; import claw.wani.x2t.configuration.Configuration; import claw.wani.x2t.configuration.AcceleratorConfiguration; import claw.wani.x2t.configuration.AcceleratorLocalStrategy; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * The Single Column Abstraction (SCA) transformation transforms the code * contained in a subroutine/function by adding necessary dimensions and * parallelism to the defined data. * * Transformation for the GPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Do statements over the additional dimensions is added as an outer * loop and wrap the entire body of the subroutine. * </ul> * * Transformation for the CPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Propagated promotion is applied to all scalars or arrays used in an * assign statement at the lhs and where a promoted variable is used on the * rhs. * <li> Do statements over the additional dimensions are added as an inner * loop wrapping each assign statements including promoted variables. * </ul> * * Generation of OpenACC directives:<ul> * <li> acc routine seq is generated for subroutine called from the parallelized * subroutine if they are located in the same translation unit. * <li> acc data region with corresponding present clause for all promoted * variables with the intent in, out or inout. * <li> acc parallel region is generated to wrap all the body of the subroutine. * <li> acc private clause is added to the parallel directive for all local * variables. * <li> acc loop is generated for the generated do statement. * <li> acc loop seq is generated for already existing do statements. * </ul> * * Generation of OpenMP directives on CPU: <ul> * <li> omp parallel do is generated for each generated do statements. * </ul> * * Generation of OpenMP directives on GPU:<ul> * <li> MISSING FEATURE : omp declare target is generated for subroutine called from the parallelized * subroutine if they are located in the same translation unit. * <li> omp data region with corresponding present clause for all promoted * variables with the intent to, from or tofrom. * <li> omp target teams distribute region is generated to wrap all the body of the subroutine. * <li> omp private clause is added to the target directive for all local * variables. * <li> omp collapse is generated for the generated do statement (if more that 1). * </ul> * * @author clementval */ public class Parallelize extends ClawTransformation { private final Map<String, DimensionDefinition> _dimensions; private final Map<String, PromotionInfo> _promotions; private final Set<String> _arrayFieldsInOut; private final Set<String> _scalarFields; private int _overDimensions; private FfunctionDefinition _fctDef; private FfunctionType _fctType; /** * Constructs a new Parallelize transformation triggered from a specific * pragma. * * @param directive The directive that triggered the define transformation. */ public Parallelize(ClawPragma directive) { super(directive); _overDimensions = 0; _dimensions = new HashMap<>(); _promotions = new HashMap<>(); _arrayFieldsInOut = new HashSet<>(); _scalarFields = new HashSet<>(); } /** * Print information about promoted arrays, candidate for promotion arrays and * scalars. * * @param name Name of the subroutine. * @param promoted List of promoted array variables. * @param candidateArrays List of candidate array variables for promotion. * @param scalars List of candidate scalar variables for promotion. */ private void printDebugPromotionInfos(String name, Set<String> promoted, List<String> candidateArrays, List<String> scalars) { Message.debug("=========================================="); Message.debug("Parallelize promotion infos for subroutine " + name); Message.debug(" - Promoted arrays(" + promoted.size() + "):"); for(String array : promoted) { Message.debug(" " + array); } Message.debug(" - Candidate arrays(" + candidateArrays.size() + "):"); for(String array : candidateArrays) { Message.debug(" " + array); } Message.debug(" - Candidate scalars(" + scalars.size() + "):"); for(String array : scalars) { Message.debug(" " + array); } Message.debug("=========================================="); } @Override public boolean analyze(XcodeProgram xcodeml, Translator translator) { // Check for the parent fct/subroutine definition _fctDef = _claw.getPragma().findParentFunction(); if(_fctDef == null) { xcodeml.addError("Parent function/subroutine cannot be found. " + "Parallelize directive must be defined in a function/subroutine.", _claw.getPragma().lineNo()); return false; } _fctType = xcodeml.getTypeTable().getFunctionType(_fctDef); if(_fctType == null) { xcodeml.addError("Function/subroutine signature cannot be found. ", _claw.getPragma().lineNo()); return false; } /* Check if unsupported statements are located in the future parallel * region. */ if(Context.isTarget(Target.GPU) && (Context.get().getGenerator().getDirectiveLanguage() != CompilerDirective.NONE)) { Xnode contains = _fctDef.body().matchSeq(Xcode.F_CONTAINS_STATEMENT); Xnode parallelRegionStart = Directive.findParallelRegionStart(_fctDef, null); Xnode parallelRegionEnd = Directive.findParallelRegionEnd(_fctDef, contains); List<Xnode> unsupportedStatements = XnodeUtil.getNodes(parallelRegionStart, parallelRegionEnd, Context.get().getGenerator().getUnsupportedStatements()); if(unsupportedStatements.size() > 0) { for(Xnode statement : unsupportedStatements) { xcodeml.addError("Unsupported statement in parallel region", statement.lineNo()); } return false; } } return analyzeDimension(xcodeml) && analyzeData(xcodeml) && analyzeOver(xcodeml); } /** * Analyse the defined dimension. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeDimension(XcodeProgram xcodeml) { if(!_claw.hasDimensionClause()) { xcodeml.addError("No dimension defined for parallelization.", _claw.getPragma().lineNo()); return false; } for(DimensionDefinition d : _claw.getDimensionValues()) { if(_dimensions.containsKey(d.getIdentifier())) { xcodeml.addError( String.format("Dimension with identifier %s already specified.", d.getIdentifier()), _claw.getPragma().lineNo() ); return false; } _dimensions.put(d.getIdentifier(), d); } return true; } /** * Analyse the information defined in the data clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeData(XcodeProgram xcodeml) { /* If there is no data/over clause specified, an automatic deduction for * array promotion is performed. */ if(!_claw.hasOverDataClause()) { List<String> scalars = new ArrayList<>(); List<String> candidateArrays = new ArrayList<>(); List<Xnode> declarations = _fctDef.getDeclarationTable().values(); for(Xnode decl : declarations) { if(decl.opcode() != Xcode.VAR_DECL) { continue; } if(xcodeml.getTypeTable().isBasicType(decl)) { String varName = decl.matchSeq(Xcode.NAME).value(); FbasicType bType = xcodeml.getTypeTable().getBasicType(decl); if(bType.isArray()) { if(bType.hasIntent() || bType.isPointer()) { _arrayFieldsInOut.add(varName); } else { candidateArrays.add(varName); } } else { if(_claw.hasScalarClause() && _claw.getScalarClauseValues().contains(varName)) { _arrayFieldsInOut.add(varName); } if(!bType.isParameter() && bType.hasIntent()) { scalars.add(varName); } } } } _scalarFields.addAll(scalars); _scalarFields.addAll(candidateArrays); printDebugPromotionInfos(_fctDef.getName(), _arrayFieldsInOut, candidateArrays, scalars); return true; } /* If the data clause if defined at least once, manual promotion is the * rule. The array identifiers defined in the data clauses will be used as * the list of array to be promoted. * In the analysis, we control that all defined arrays in the data clauses * are actual declared variables. */ for(List<String> data : _claw.getOverDataClauseValues()) { for(String d : data) { if(!_fctDef.getSymbolTable().contains(d)) { xcodeml.addError( String.format("Data %s is not defined in the current block.", d), _claw.getPragma().lineNo() ); return false; } if(!_fctDef.getDeclarationTable().contains(d)) { xcodeml.addError( String.format("Data %s is not declared in the current block.", d), _claw.getPragma().lineNo() ); return false; } } _arrayFieldsInOut.addAll(data); } return true; } /** * Analyse the information defined in the over clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeOver(XcodeProgram xcodeml) { if(!_claw.hasOverClause()) { _overDimensions += _claw.getDimensionValues().size(); return true; } // Check if over dimensions are defined dimensions _overDimensions = _claw.getDimensionValues().size(); for(List<String> overLst : _claw.getOverClauseValues()) { int usedDimension = 0; for(String o : overLst) { if(!o.equals(DimensionDefinition.BASE_DIM)) { if(!_dimensions.containsKey(o)) { xcodeml.addError( String.format( "Dimension %s is not defined. Cannot be used in over " + "clause", o), _claw.getPragma().lineNo() ); return false; } ++usedDimension; } } if(usedDimension != _overDimensions) { xcodeml.addError("Over clause doesn't use one or more defined " + "dimensions", _claw.getPragma().lineNo()); return false; } } return true; } @Override public void transform(XcodeProgram xcodeml, Translator translator, Transformation other) throws Exception { // Handle PURE function / subroutine boolean pureRemoved = _fctType.isPure(); _fctType.removeAttribute(Xattr.IS_PURE); if(Configuration.get().isForcePure() && pureRemoved) { throw new IllegalTransformationException( "PURE specifier cannot be removed", _fctDef.lineNo()); } else if(pureRemoved) { String fctName = _fctDef.matchDirectDescendant(Xcode.NAME).value(); xcodeml.addWarning("PURE specifier removed from function " + fctName + ". Transformation and code generation applied to it.", _fctDef.lineNo()); } // Insert the declarations of variables to iterate over the new dimensions. insertVariableToIterateOverDimension(xcodeml); // Promote all array fields with new dimensions. promoteFields(xcodeml); // Adapt array references. if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { for(String id : _claw.getOverDataClauseValues().get(i)) { Field.adaptArrayRef(_promotions.get(id), _fctDef.body(), xcodeml); } } } else { for(String id : _arrayFieldsInOut) { Field.adaptArrayRef(_promotions.get(id), _fctDef.body(), xcodeml); } } removePragma(); // Apply specific target transformation if(Context.isTarget(Target.GPU)) { transformForGPU(xcodeml); } else if(Context.isTarget(Target.CPU) || Context.isTarget(Target.ARM)) { // Choose which mode to use switch (Configuration.get().getParameter(Configuration.CPU_STRATEGY)) { case Configuration.CPU_STRATEGY_FUSION: transformFusionForCPU(xcodeml); break; case Configuration.CPU_STRATEGY_SINGLE: default: transformForCPU(xcodeml); break; } } else { throw new IllegalTransformationException("Unsupported target " + Context.get().getTarget(), _claw.getPragma().lineNo()); } if(!_fctType.getBooleanAttribute(Xattr.IS_PRIVATE)) { FmoduleDefinition modDef = _fctDef.findParentModule(); if(modDef != null) { Xmod.updateSignature(modDef.getName(), xcodeml, _fctDef, _fctType, false); } } } /** * Apply GPU based transformation. * * @param xcodeml Current XcodeML program unit. */ private void transformForGPU(XcodeProgram xcodeml) throws IllegalTransformationException { AcceleratorConfiguration accConfig = Configuration.get().accelerator(); // TODO nodep should be passed in another way. int collapse = Directive.generateLoopSeq(xcodeml, _fctDef, CompilerDirective.CLAW.getPrefix() + " nodep"); if(!Body.isEmpty(_fctDef.body())) { /* Create a nested loop with the new defined dimensions and wrap it around * the whole subroutine's body. This is for the moment a really naive * transformation idea but it is our start point. * Use the first over clause to create it. */ NestedDoStatement loops = new NestedDoStatement(_claw.getDimensionValuesReversed(), xcodeml); /* Subroutine/function can have a contains section with inner subroutines * or functions. The newly created (nested) do statements should stop * before this contains section if it exists. */ Xnode contains = _fctDef.body().matchSeq(Xcode.F_CONTAINS_STATEMENT); if(contains != null) { Xnode parallelRegionStart = Directive.findParallelRegionStart(_fctDef, null); Xnode parallelRegionEnd = Directive.findParallelRegionEnd(_fctDef, contains); Body.shiftIn(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); contains.insertBefore(loops.getOuterStatement()); } else { // No contains section, all the body is copied to the do statements. Xnode parallelRegionStart = Directive.findParallelRegionStart(_fctDef, null); Xnode parallelRegionEnd = Directive.findParallelRegionEnd(_fctDef, null); // Define a hook from where we can insert the new do statement Xnode hook = parallelRegionEnd != null ? parallelRegionEnd.nextSibling() : null; Body.shiftIn(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); // Hook is null then we append the do statement to the current fct body if(hook == null) { _fctDef.body().append(loops.getOuterStatement()); } else { // Insert new do statement before the hook element hook.insertBefore(loops.getOuterStatement()); } } // Prepare variables list for present/pcreate clauses and handle // promotion/privatize local strategy List<String> presentList = Directive.getPresentVariables(xcodeml, _fctDef); List<String> privateList = Collections.emptyList(); List<String> createList = Collections.emptyList(); if(accConfig.getLocalStrategy() == AcceleratorLocalStrategy.PRIVATE) { privateList = Directive.getLocalArrays(xcodeml, _fctDef); // Iterate over a copy to be able to remove items for(String identifier : new ArrayList<>(privateList)) { if(_promotions.containsKey(identifier)) { privateList.remove(identifier); } } } else if(accConfig.getLocalStrategy() == AcceleratorLocalStrategy.PROMOTE) { createList = Directive.getLocalArrays(xcodeml, _fctDef); for(String arrayIdentifier : createList) { _arrayFieldsInOut.add(arrayIdentifier); PromotionInfo promotionInfo = new PromotionInfo(arrayIdentifier, _claw.getDimensionsForData(arrayIdentifier)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(arrayIdentifier, promotionInfo); Field.adaptArrayRef(promotionInfo, _fctDef.body(), xcodeml); Field.adaptAllocate(promotionInfo, _fctDef.body(), xcodeml); } } // Generate the data region Directive.generateDataRegionClause(xcodeml, presentList, createList, loops.getOuterStatement(), loops.getOuterStatement()); // Generate the parallel region Directive.generateParallelLoopClause(xcodeml, privateList, loops.getOuterStatement(), loops.getOuterStatement(), loops.size() + collapse); } Directive.generateRoutineDirectives(xcodeml, _fctDef); } /** * Apply a CPU transformation which group adjacent statements together and * promote the minimum number of variables possible. * * @param xcodeml Current XcodeML program unit. * @throws IllegalTransformationException If promotion of arrays fails. */ private void transformFusionForCPU(XcodeProgram xcodeml) throws IllegalTransformationException { // Apply transformation only when there is a body to modify if (Body.isEmpty(_fctDef.body())) { return; } // Variables on each "depth" of the method List<Set<String>> depthVars = new ArrayList<>(); depthVars.add(new HashSet<String>()); // A growing list of affecting variables. Starting from the ones // declared by SCA and successively any variables affected by the SCA // declaration Set<String> affectingVars = new HashSet<>(_promotions.keySet()); //affectingVars.addAll(_arrayFieldsInOut); // Extract all the variables used, this doesn't include vector's // iterator variables transformFusionForCPUExtraction(_fctDef.body(), new AtomicInteger(), depthVars, affectingVars); // Find the block we need to transform List<Set<String>> targetDepthIntersections = new ArrayList<>(); for (int i = 0; i < depthVars.size(); i++) { Set<String> depthVar = depthVars.get(i); if (depthVar.isEmpty()) { targetDepthIntersections.add(null); continue; } // Find intersection with other blocks Set<String> intersection = new HashSet<>(); for (int j = 0; j < depthVars.size(); j++) { // Skip itself if (i == j) { continue; } // Intersect the level set with the others Set<String> copy = new HashSet<>(depthVars.get(i)); copy.retainAll(depthVars.get(j)); intersection.addAll(copy); } // All are on the same index targetDepthIntersections.add(intersection); } // Gather all possible loop groups before their modification List<List<Xnode>> transformations = new ArrayList<>(); // Apply transformation at the indicated depth for (int targetDepth = 0; targetDepth < depthVars.size(); targetDepth++) { Set<String> vars = depthVars.get(targetDepth); if (vars.isEmpty()) continue; Set<String> intersection = targetDepthIntersections.get(targetDepth); // Variables still waiting for a promotion which aren't promoted yet Set<String> promotions = new HashSet<>(intersection); // Check only the LHS arrays Set<String> vectorType = new HashSet<>(vars); vectorType.retainAll(affectingVars); // Influenced arrays must be promoted anyway for (String var : vectorType) { Xid fieldId = _fctDef.getSymbolTable().get(var); FbasicType type = xcodeml.getTypeTable().getBasicType(fieldId); if (type != null && type.isArray()) { promotions.add(var); } } // Promote for (String promotion : promotions) { if (_promotions.containsKey(promotion)) { continue; } PromotionInfo promotionInfo = new PromotionInfo(promotion, _claw.getDimensionsForData(promotion)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(promotion, promotionInfo); Field.adaptArrayRef(promotionInfo, _fctDef.body(), xcodeml); Field.adaptAllocate(_promotions.get(promotion), _fctDef.body(), xcodeml); } // Transform indicated level by wrapping it in a DO loop transformFusionForCPUGather(_fctDef.body(), new AtomicInteger(), targetDepth, affectingVars, transformations); } // After gathering we apply the transformations for (List<Xnode> transformation : transformations) { transformFusionForCPUApply(transformation, xcodeml); } // If the last statement is a CONTAINS, fallback to the previous one Xnode lastNode = _fctDef.body().lastChild(); while (lastNode.opcode() == Xcode.F_CONTAINS_STATEMENT) { lastNode = lastNode.prevSibling(); } // Generate the parallel region Directive.generateParallelClause(xcodeml, _fctDef.body().firstChild(), lastNode); } /** * Analysis of a routine in order to extracts the information necessary in * order to promote a minimal number of variables. * Only variables affected by affectingVars are kept in depthVars. * * @param body The body to analyze. * @param depth The depth relative to the function declaration. * @param depthVars Vars used on each depth. * @param affectingVars Vars which are affected by SCA and consequently * affect other variables. */ private void transformFusionForCPUExtraction(Xnode body, AtomicInteger depth, List<Set<String>> depthVars, Set<String> affectingVars) { final List<Xnode> children = body.children(); for (Xnode node : children) { // Handle an assignment if (node.opcode() == Xcode.F_ASSIGN_STATEMENT) { AssignStatement as = new AssignStatement(node.element()); Set<String> vars = XnodeUtil.findChildrenVariables(node); // Check if it's affected by the promotion Set<String> affectedVars = new HashSet<>(vars); affectedVars.retainAll(affectingVars); // If the intersection of the sets contain anything the assignment is // affected by a previous promotions depthVars.get(depth.get()).addAll(affectedVars); if (!affectedVars.isEmpty()) { affectingVars.add(as.getLhsName()); depthVars.get(depth.get()).add(as.getLhsName()); } } // IF statement content shouldn't increase depth counter else if (node.opcode() == Xcode.F_IF_STATEMENT) { Xnode nThen = node.firstChild().matchSibling(Xcode.THEN); Xnode nElse = node.firstChild().matchSibling(Xcode.ELSE); if (nThen != null) { transformFusionForCPUExtraction(nThen.body(), depth, depthVars, affectingVars); } if (nElse != null) { transformFusionForCPUExtraction(nElse.body(), depth, depthVars, affectingVars); } } // Handle node containing a body else if (node.opcode().hasBody()) { if (depthVars.size() <= depth.get() + 1) { depthVars.add(new HashSet<String>()); } depth.incrementAndGet(); transformFusionForCPUExtraction(node.body(), depth, depthVars, affectingVars); } // Keep going inside the new node else { transformFusionForCPUExtraction(node, depth, depthVars, affectingVars); } } } /** * Transform the content of the routine and add a DO loop only at the * indicated depth and only around the affecting variables. * * @param body The body to transform. * @param currentDepth The depth we currently are at * @param targetDepth The depth we need to reach and transform. * @param affectingVars The variable which should be contained inside the loop */ private void transformFusionForCPUGather(Xnode body, AtomicInteger currentDepth, final int targetDepth, Set<String> affectingVars, List<List<Xnode>> toapply) { final List<Xnode> children = body.children(); final List<Xnode> hooks = new ArrayList<>(); nodeLoop: for (Xnode node : children) { // Handle an assignment if (node.opcode() == Xcode.F_ASSIGN_STATEMENT) { if (currentDepth.get() != targetDepth) continue; Set<String> vars = XnodeUtil.findChildrenVariables(node); // Statement need to be in the loop if (Utility.hasIntersection(vars, affectingVars)) { // Is the statement wasn't promoted and is not in a current loop // block, we can avoid to add it to a loop because it is not needed. AssignStatement as = new AssignStatement(node.element()); if (!_promotions.containsKey(as.getLhsName()) && hooks.isEmpty() && as.getVarRefNames().size() == 0) { continue; } // If the assignment is a vector, but we don't access its elements // we don't have to add it to a loop if (_promotions.containsKey(as.getLhsName()) && as.getVarRefNames().size() == 0) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); continue; } hooks.add(node); } // Particular case, unused variable inside the body else { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); } } // IF statement my have to be contained inside else if (node.opcode() == Xcode.F_IF_STATEMENT) { // Enter the if in case it contains DO statements if (currentDepth.get() != targetDepth) { Xnode nThen = node.firstChild().matchSibling(Xcode.THEN); Xnode nElse = node.firstChild().matchSibling(Xcode.ELSE); if (nThen != null) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); transformFusionForCPUGather(nThen.body(), currentDepth, targetDepth, affectingVars, toapply); } if (nElse != null) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); transformFusionForCPUGather(nElse.body(), currentDepth, targetDepth, affectingVars, toapply); } continue; } // We need to wrap the whole IF based on the condition List<Xnode> condNode = node.matchAll(Xcode.CONDITION); for (Xnode xnode : condNode) { if (Condition.dependsOn(xnode, affectingVars)) { hooks.add(node); continue nodeLoop; } } // We need to wrap the whole IF based on the statement inside List<Xnode> statNode = node.matchAll(Xcode.F_ASSIGN_STATEMENT); xNodeLoop: for (Xnode xnode : statNode) { AssignStatement as = new AssignStatement(xnode.element()); if (affectingVars.contains(as.getLhsName())) { // If the affected node is child of a DO, a dedicated loop // group will be created. Xnode pnode = xnode.ancestor(); while (pnode.hashCode() != node.hashCode()) { if (pnode.opcode() == Xcode.F_DO_STATEMENT) { break xNodeLoop; } pnode = pnode.ancestor(); } // Add the whole if and continue otherwise hooks.add(node); continue nodeLoop; } } // If the IF statement doesn't contains any dependency we gather the // potential transformation and continue transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); } // Handle node containing a body else if (node.opcode().hasBody()) { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); currentDepth.incrementAndGet(); transformFusionForCPUGather(node.body(), currentDepth, targetDepth, affectingVars, toapply); } // Keep going inside the new node else { transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); transformFusionForCPUGather(node, currentDepth, targetDepth, affectingVars, toapply); } } transformFusionForCPUGatherSaveHooksGroup(hooks, toapply); } /** * If a hooks group that will be wrapped exists, add it to the collection * containing all the hooks group found until now. * The content of `hooks` is copied in a new list and added to `toapply`, * while `hooks` will be cleared of its content. * * @param hooks A list of adjacent nodes to be wrapped in a DO statement * @param toapply A list to add a copy of `hooks` */ private void transformFusionForCPUGatherSaveHooksGroup(List<Xnode> hooks, List<List<Xnode>> toapply) { if (!hooks.isEmpty()) { toapply.add(new ArrayList<>(hooks)); hooks.clear(); } } /** * Given a series of sequential hooks (nodes), envelope them in a DO loop. * * @param hooks List of nodes do envelope in a DO statement * @param xcodeml The program */ private void transformFusionForCPUApply(List<Xnode> hooks, XcodeProgram xcodeml) { if (hooks.isEmpty()) { return; } NestedDoStatement loop = new NestedDoStatement(_claw.getDimensionValuesReversed(), xcodeml); // Add loop to AST hooks.get(0).insertBefore(loop.getOuterStatement()); for(Xnode hook : hooks) { loop.getInnerStatement().body().append(hook, false); } Directive.generateLoopDirectives(xcodeml, loop.getOuterStatement(), loop.getOuterStatement(), Directive.NO_COLLAPSE); hooks.clear(); } /** * Apply CPU based transformations. * * @param xcodeml Current XcodeML program unit. * @throws IllegalTransformationException If promotion of arrays fails. */ private void transformForCPU(XcodeProgram xcodeml) throws IllegalTransformationException { /* Create a group of nested loop with the newly defined dimension and wrap * every assignment statement in the column loop or including data with it. * This is for the moment a really naive transformation idea but it is our * start point. * Use the first over clause to do it. */ List<AssignStatement> assignStatements = Function.gatherAssignStatements(_fctDef); // Iterate over all assign statements to detect all the indirect promotion. for (AssignStatement assign : assignStatements) { Xnode lhs = assign.getLhs(); String lhsName = assign.getLhsName(); if (lhs.opcode() == Xcode.VAR || lhs.opcode() == Xcode.F_ARRAY_REF) { /* If the assignment is in the column loop and is composed with some * promoted variables, the field must be promoted and the var reference * switch to an array reference */ PromotionInfo promotionInfo; if (shouldBePromoted(assign)) { // Do the promotion if needed if (!_arrayFieldsInOut.contains(lhsName)) { _arrayFieldsInOut.add(lhsName); promotionInfo = new PromotionInfo(lhsName, _claw.getDimensionsForData(lhsName)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(lhsName, promotionInfo); } else { promotionInfo = _promotions.get(lhsName); } // Adapt references if (lhs.opcode() == Xcode.VAR) { Field.adaptScalarRefToArrayRef(lhsName, _fctDef, _claw.getDimensionValues(), xcodeml); } else { Field.adaptArrayRef(_promotions.get(lhsName), _fctDef.body(), xcodeml); Field.adaptAllocate(_promotions.get(lhsName), _fctDef.body(), xcodeml); } promotionInfo.setRefAdapted(); } } } // Hold hooks on which do statement will be inserted Set<Xnode> hooks = new HashSet<>(); /* Check whether condition includes a promoted variables. If so, the * ancestor node using the condition must be wrapped in a do statement. */ List<Xnode> conditions = _fctDef.body().matchAll(Xcode.CONDITION); for (Xnode condition : conditions) { if (Condition.dependsOn(condition, _arrayFieldsInOut)) { Xnode ancestor = condition.ancestor(); Iterator<Xnode> iter = hooks.iterator(); boolean addHook = true; while (iter.hasNext()) { if (ancestor.isNestedIn(iter.next())) { addHook = false; break; } } if (addHook) { hooks.add(ancestor); } } } /* Iterate a second time over assign statements to flag places where to * insert the do statements */ for (AssignStatement assign : assignStatements) { Xnode lhs = assign.getLhs(); String lhsName = assign.getLhsName(); boolean wrapInDoStatement = true; // Check if assignment is dependant of an if statement. if (assign.isChildOf(Xcode.F_IF_STATEMENT)) { // Gather all potential ancestor if statements List<Xnode> ifStatements = assign.matchAllAncestor(Xcode.F_IF_STATEMENT, Xcode.F_FUNCTION_DEFINITION); Xnode hookIfStmt = null; for (Xnode ifStmt : ifStatements) { if (Condition.dependsOn( ifStmt.matchDirectDescendant(Xcode.CONDITION), assign.getVarRefNames())) { // Have to put the do statement around the if as the assignment // is conditional as well. hookIfStmt = ifStmt; } } if (hookIfStmt != null) { wrapInDoStatement = false; boolean addIfHook = true; // Get rid of previously flagged hook in this if body. Iterator<Xnode> iter = hooks.iterator(); while (iter.hasNext()) { Xnode crt = iter.next(); if (assign.isNestedIn(crt) || hookIfStmt.isNestedIn(crt)) { addIfHook = false; } if (crt.isNestedIn(hookIfStmt)) { iter.remove(); } } if (addIfHook) { hooks.add(hookIfStmt); } } } Iterator<Xnode> iter = hooks.iterator(); while (iter.hasNext()) { if (assign.isNestedIn(iter.next())) { wrapInDoStatement = false; break; } } if (lhs.opcode() == Xcode.F_ARRAY_REF && _arrayFieldsInOut.contains(lhsName) && wrapInDoStatement) { hooks.add(assign); } else if (lhs.opcode() == Xcode.VAR || lhs.opcode() == Xcode.F_ARRAY_REF && _scalarFields.contains(lhsName)) { if (shouldBePromoted(assign) && wrapInDoStatement) { hooks.add(assign); } } } // Generate loops around statements flagged in previous stage for (Xnode hook : hooks) { NestedDoStatement loops = new NestedDoStatement(_claw.getDimensionValuesReversed(), xcodeml); hook.insertAfter(loops.getOuterStatement()); loops.getInnerStatement().body().append(hook, true); hook.delete(); Directive.generateLoopDirectives(xcodeml, loops.getOuterStatement(), loops.getOuterStatement(), Directive.NO_COLLAPSE); } // Generate the parallel region Directive.generateParallelClause(xcodeml, _fctDef.body().firstChild(), _fctDef.body().lastChild()); } /** * Check whether the LHS variable should be promoted. * * @param assignStmt Assign statement node. * @return True if the LHS variable should be promoted. False otherwise. */ private boolean shouldBePromoted(Xnode assignStmt) { Xnode rhs = assignStmt.child(Xnode.RHS); if (rhs == null) { return false; } List<Xnode> vars = XnodeUtil.findAllReferences(rhs); Set<String> names = XnodeUtil.getNamesFromReferences(vars); return Utility.hasIntersection(names, _arrayFieldsInOut); } /** * Promote all fields declared in the data clause with the additional * dimensions. * * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void promoteFields(XcodeProgram xcodeml) throws IllegalTransformationException { if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { for(String fieldId : _claw.getOverDataClauseValues().get(i)) { PromotionInfo promotionInfo = new PromotionInfo(fieldId, _claw.getDimensionsForData(fieldId)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(fieldId, promotionInfo); } } } else { // Promote all arrays in a similar manner for(String fieldId : _arrayFieldsInOut) { PromotionInfo promotionInfo = new PromotionInfo(fieldId, _claw.getDimensionsForData(fieldId)); Field.promote(promotionInfo, _fctDef, xcodeml); _promotions.put(fieldId, promotionInfo); } } } /** * Insert the declaration of the different variables needed to iterate over * the additional dimensions. * * @param xcodeml Current XcodeML program unit in which element are * created. */ private void insertVariableToIterateOverDimension(XcodeProgram xcodeml) { // Create type and declaration for iterations over the new dimensions FbasicType bt = xcodeml.createBasicType(FortranType.INTEGER, Intent.IN); xcodeml.getTypeTable().add(bt); // For each dimension defined in the directive for(DimensionDefinition dimension : _claw.getDimensionValues()) { // Create the parameter for the lower bound if(dimension.getLowerBound().isVar()) { xcodeml.createIdAndDecl(dimension.getLowerBound().getValue(), bt.getType(), XstorageClass.F_PARAM, _fctDef, DeclarationPosition.FIRST); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam( dimension.getLowerBound().getValue(), bt.getType(), _fctType); param.setBooleanAttribute(Xattr.IS_INSERTED, true); } // Create parameter for the upper bound if(dimension.getUpperBound().isVar()) { xcodeml.createIdAndDecl(dimension.getUpperBound().getValue(), bt.getType(), XstorageClass.F_PARAM, _fctDef, DeclarationPosition.FIRST); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam( dimension.getUpperBound().getValue(), bt.getType(), _fctType); param.setBooleanAttribute(Xattr.IS_INSERTED, true); } // Create induction variable declaration xcodeml.createIdAndDecl(dimension.getIdentifier(), FortranType.INTEGER, XstorageClass.F_LOCAL, _fctDef, DeclarationPosition.LAST); } } /** * @return Always false as independent transformation are applied one by one. * @see Transformation#canBeTransformedWith(XcodeProgram, Transformation) */ @Override public boolean canBeTransformedWith(XcodeProgram xcodeml, Transformation other) { return false; // This is an independent transformation } }
SCA-CPU: Only wrap IFs if the current condition is matched The previous approach would wrap all ifs in nested conditionals if one of them matches.
cx2t/src/claw/wani/transformation/sca/Parallelize.java
SCA-CPU: Only wrap IFs if the current condition is matched
<ide><path>x2t/src/claw/wani/transformation/sca/Parallelize.java <ide> } <ide> <ide> // We need to wrap the whole IF based on the condition <del> List<Xnode> condNode = node.matchAll(Xcode.CONDITION); <del> for (Xnode xnode : condNode) { <del> if (Condition.dependsOn(xnode, affectingVars)) { <add> Xnode condNode = node.firstChild().matchSibling(Xcode.CONDITION); <add> if (Condition.dependsOn(condNode, affectingVars)) { <ide> hooks.add(node); <ide> continue nodeLoop; <del> } <ide> } <ide> <ide> // We need to wrap the whole IF based on the statement inside
Java
apache-2.0
6e3aa711f82fdf44f0fad645e248f84cc0734548
0
libgdx/libgdx,libgdx/libgdx,libgdx/libgdx,libgdx/libgdx,libgdx/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; /** Extend this class to implement a material attribute. Register the attribute type by statically calling the * {@link #register(String)} method, whose return value should be used to instantiate the attribute. A class can implement * multiple types * @author Xoppa */ public abstract class Attribute implements Comparable<Attribute> { /** The registered type aliases */ private final static Array<String> types = new Array<String>(); /** The long bitmask is limited to 64 bits **/ private final static int MAX_ATTRIBUTE_COUNT = 64; /** @return The ID of the specified attribute type, or zero if not available */ public final static long getAttributeType (final String alias) { for (int i = 0; i < types.size; i++) if (types.get(i).compareTo(alias) == 0) return 1L << i; return 0; } /** @return The alias of the specified attribute type, or null if not available. */ public final static String getAttributeAlias (final long type) { int idx = -1; while (type != 0 && ++idx < 63 && (((type >> idx) & 1) == 0)) ; return (idx >= 0 && idx < types.size) ? types.get(idx) : null; } /** Call this method to register a custom attribute type, see the wiki for an example. If the alias already exists, then that * ID will be reused. The alias should be unambiguously and will by default be returned by the call to {@link #toString()}. A * maximum of 64 attributes can be registered as a long bitmask can only hold 64 bits. * @param alias The alias of the type to register, must be different for each direct type, will be used for debugging * @return the ID of the newly registered type, or the ID of the existing type if the alias was already registered * @throws GdxRuntimeException if maximum attribute count reached */ protected final static long register (final String alias) { long result = getAttributeType(alias); if (result > 0) return result; if (types.size >= MAX_ATTRIBUTE_COUNT) { throw new GdxRuntimeException("Cannot register " + alias + ", maximum registered attribute count reached."); } types.add(alias); return 1L << (types.size - 1); } /** The type of this attribute */ public final long type; private final int typeBit; protected Attribute (final long type) { this.type = type; this.typeBit = Long.numberOfTrailingZeros(type); } /** @return An exact copy of this attribute */ public abstract Attribute copy (); protected boolean equals (Attribute other) { return other.hashCode() == hashCode(); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Attribute)) return false; final Attribute other = (Attribute)obj; if (this.type != other.type) return false; return equals(other); } @Override public String toString () { return getAttributeAlias(type); } @Override public int hashCode () { return 7489 * typeBit; } }
gdx/src/com/badlogic/gdx/graphics/g3d/Attribute.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.graphics.g3d; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; /** Extend this class to implement a material attribute. Register the attribute type by statically calling the * {@link #register(String)} method, whose return value should be used to instantiate the attribute. A class can implement * multiple types * @author Xoppa */ public abstract class Attribute implements Comparable<Attribute> { /** The registered type aliases */ private final static Array<String> types = new Array<String>(); /** The long bitmask is limited to 64 bits **/ private final static int MAX_ATTRIBUTE_COUNT = 64; /** @return The ID of the specified attribute type, or zero if not available */ public final static long getAttributeType (final String alias) { for (int i = 0; i < types.size; i++) if (types.get(i).compareTo(alias) == 0) return 1L << i; return 0; } /** @return The alias of the specified attribute type, or null if not available. */ public final static String getAttributeAlias (final long type) { int idx = -1; while (type != 0 && ++idx < 63 && (((type >> idx) & 1) == 0)) ; return (idx >= 0 && idx < types.size) ? types.get(idx) : null; } /** Call this method to register a custom attribute type, see the wiki for an example. If the alias already exists, then that * ID will be reused. The alias should be unambiguously and will by default be returned by the call to {@link #toString()}. * A maximum of 64 attributes can be registered as a long bitmask can only hold 64 bits. * @param alias The alias of the type to register, must be different for each direct type, will be used for debugging * @return the ID of the newly registered type, or the ID of the existing type if the alias was already registered * @throws GdxRuntimeException if maximum attribute count reached */ protected final static long register (final String alias) { long result = getAttributeType(alias); if (result > 0) return result; if (types.size >= MAX_ATTRIBUTE_COUNT) { throw new GdxRuntimeException("Cannot register " + alias + ", maximum registered attribute count reached."); } types.add(alias); return 1L << (types.size - 1); } /** The type of this attribute */ public final long type; private final int typeBit; protected Attribute (final long type) { this.type = type; this.typeBit = Long.numberOfTrailingZeros(type); } /** @return An exact copy of this attribute */ public abstract Attribute copy (); protected boolean equals (Attribute other) { return other.hashCode() == hashCode(); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof Attribute)) return false; final Attribute other = (Attribute)obj; if (this.type != other.type) return false; return equals(other); } @Override public String toString () { return getAttributeAlias(type); } @Override public int hashCode () { return 7489 * typeBit; } }
Run spotlessApply
gdx/src/com/badlogic/gdx/graphics/g3d/Attribute.java
Run spotlessApply
<ide><path>dx/src/com/badlogic/gdx/graphics/g3d/Attribute.java <ide> } <ide> <ide> /** Call this method to register a custom attribute type, see the wiki for an example. If the alias already exists, then that <del> * ID will be reused. The alias should be unambiguously and will by default be returned by the call to {@link #toString()}. <del> * A maximum of 64 attributes can be registered as a long bitmask can only hold 64 bits. <add> * ID will be reused. The alias should be unambiguously and will by default be returned by the call to {@link #toString()}. A <add> * maximum of 64 attributes can be registered as a long bitmask can only hold 64 bits. <ide> * @param alias The alias of the type to register, must be different for each direct type, will be used for debugging <ide> * @return the ID of the newly registered type, or the ID of the existing type if the alias was already registered <ide> * @throws GdxRuntimeException if maximum attribute count reached */
Java
apache-2.0
a19df39fea21b9448cbdd64a241732a4191b876c
0
androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.car.app.model; import static java.util.Objects.requireNonNull; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.car.app.annotations.CarProtocol; import androidx.car.app.annotations.RequiresCarApi; import androidx.car.app.utils.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; /** * Represents a list of rows used for displaying informational content and a set of {@link Action}s * that users can perform based on such content. */ @CarProtocol public final class Pane { @Keep private final List<Action> mActionList; @Keep private final List<Row> mRows; @Keep private final boolean mIsLoading; @Keep @Nullable private final CarIcon mImage; /** * Returns whether the pane is in a loading state. * * @see Builder#setLoading(boolean) */ public boolean isLoading() { return mIsLoading; } /** * Returns the list of {@link Action}s displayed alongside the {@link Row}s in this pane. */ @NonNull public List<Action> getActions() { return CollectionUtils.emptyIfNull(mActionList); } /** * Returns the list of {@link Row} objects that make up the {@link Pane}. */ @NonNull public List<Row> getRows() { return CollectionUtils.emptyIfNull(mRows); } /** * Returns the optional image to display in this pane. */ @RequiresCarApi(4) @Nullable public CarIcon getImage() { return mImage; } @Override @NonNull public String toString() { return "[ rows: " + (mRows != null ? mRows.toString() : null) + ", action list: " + mActionList + "]"; } @Override public int hashCode() { return Objects.hash(mRows, mActionList, mIsLoading, mImage); } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (!(other instanceof Pane)) { return false; } Pane otherPane = (Pane) other; return mIsLoading == otherPane.mIsLoading && Objects.equals(mActionList, otherPane.mActionList) && Objects.equals(mRows, otherPane.mRows) && Objects.equals(mImage, otherPane.mImage); } Pane(Builder builder) { mRows = CollectionUtils.unmodifiableCopy(builder.mRows); mActionList = CollectionUtils.unmodifiableCopy(builder.mActionList); mImage = builder.mImage; mIsLoading = builder.mIsLoading; } /** Constructs an empty instance, used by serialization code. */ private Pane() { mRows = Collections.emptyList(); mActionList = Collections.emptyList(); mIsLoading = false; mImage = null; } /** A builder of {@link Pane}. */ public static final class Builder { final List<Row> mRows = new ArrayList<>(); List<Action> mActionList = new ArrayList<>(); boolean mIsLoading; @Nullable CarIcon mImage; /** * Sets whether the {@link Pane} is in a loading state. * * <p>If set to {@code true}, the UI will display a loading indicator where the list content * would be otherwise. The caller is expected to call {@link * androidx.car.app.Screen#invalidate()} and send the new template content * to the host once the data is ready. If set to {@code false}, the UI shows the actual row * contents. * * @see #build */ @NonNull public Builder setLoading(boolean isLoading) { mIsLoading = isLoading; return this; } /** * Adds a row to display in the list. * * @throws NullPointerException if {@code row} is {@code null} */ @NonNull public Builder addRow(@NonNull Row row) { mRows.add(requireNonNull(row)); return this; } /** * Adds an {@link Action} to display alongside the rows in the pane. * * <p>By default, no actions are displayed. * * @throws NullPointerException if {@code action} is {@code null} */ @NonNull public Builder addAction(@NonNull Action action) { requireNonNull(action); mActionList.add(action); return this; } /** * Sets an {@link CarIcon} to display alongside the rows in the pane. * * <h4>Image Sizing Guidance</h4> * * To minimize scaling artifacts across a wide range of car screens, apps should provide * images targeting a 480 x 480 dp bounding box. If the image exceeds this maximum size * in either one of the dimensions, it will be scaled down to be centered inside the * bounding box while preserving its aspect ratio. * * @throws NullPointerException if {@code image} is {@code null} */ @RequiresCarApi(4) @NonNull public Builder setImage(@NonNull CarIcon image) { mImage = requireNonNull(image); return this; } /** * Constructs the row list defined by this builder. * * @throws IllegalStateException if the pane is in loading state and also contains rows, or * vice versa */ @NonNull public Pane build() { int size = size(); if (size > 0 == mIsLoading) { throw new IllegalStateException( "The pane is set to loading but is not empty, or vice versa"); } return new Pane(this); } private int size() { return mRows.size(); } /** Returns an empty {@link Builder} instance. */ public Builder() { } } }
car/app/app/src/main/java/androidx/car/app/model/Pane.java
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.car.app.model; import static java.util.Objects.requireNonNull; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.car.app.annotations.CarProtocol; import androidx.car.app.annotations.RequiresCarApi; import androidx.car.app.utils.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; /** * Represents a list of rows used for displaying informational content and a set of {@link Action}s * that users can perform based on such content. */ @CarProtocol public final class Pane { @Keep private final List<Action> mActionList; @Keep private final List<Row> mRows; @Keep private final boolean mIsLoading; @Keep @Nullable private final CarIcon mImage; /** * Returns whether the pane is in a loading state. * * @see Builder#setLoading(boolean) */ public boolean isLoading() { return mIsLoading; } /** * Returns the list of {@link Action}s displayed alongside the {@link Row}s in this pane. */ @NonNull public List<Action> getActions() { return CollectionUtils.emptyIfNull(mActionList); } /** * Returns the list of {@link Row} objects that make up the {@link Pane}. */ @NonNull public List<Row> getRows() { return CollectionUtils.emptyIfNull(mRows); } /** * Returns the optional image to display in this pane. */ @RequiresCarApi(4) @Nullable public CarIcon getImage() { return mImage; } @Override @NonNull public String toString() { return "[ rows: " + (mRows != null ? mRows.toString() : null) + ", action list: " + mActionList + "]"; } @Override public int hashCode() { return Objects.hash(mRows, mActionList, mIsLoading, mImage); } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (!(other instanceof Pane)) { return false; } Pane otherPane = (Pane) other; return mIsLoading == otherPane.mIsLoading && Objects.equals(mActionList, otherPane.mActionList) && Objects.equals(mRows, otherPane.mRows) && Objects.equals(mImage, otherPane.mImage); } Pane(Builder builder) { mRows = CollectionUtils.unmodifiableCopy(builder.mRows); mActionList = CollectionUtils.unmodifiableCopy(builder.mActionList); mImage = builder.mImage; mIsLoading = builder.mIsLoading; } /** Constructs an empty instance, used by serialization code. */ private Pane() { mRows = Collections.emptyList(); mActionList = Collections.emptyList(); mIsLoading = false; mImage = null; } /** A builder of {@link Pane}. */ public static final class Builder { final List<Row> mRows = new ArrayList<>(); List<Action> mActionList = new ArrayList<>(); boolean mIsLoading; @Nullable CarIcon mImage; /** * Sets whether the {@link Pane} is in a loading state. * * <p>If set to {@code true}, the UI will display a loading indicator where the list content * would be otherwise. The caller is expected to call {@link * androidx.car.app.Screen#invalidate()} and send the new template content * to the host once the data is ready. If set to {@code false}, the UI shows the actual row * contents. * * @see #build */ @NonNull public Builder setLoading(boolean isLoading) { mIsLoading = isLoading; return this; } /** * Adds a row to display in the list. * * @throws NullPointerException if {@code row} is {@code null} */ @NonNull public Builder addRow(@NonNull Row row) { mRows.add(requireNonNull(row)); return this; } /** * Adds an {@link Action} to display alongside the rows in the pane. * * <p>By default, no actions are displayed. * * @throws NullPointerException if {@code action} is {@code null} */ @NonNull public Builder addAction(@NonNull Action action) { requireNonNull(action); mActionList.add(action); return this; } /** * Sets an {@link CarIcon} to display alongside the rows in the pane. * * <h4>Image Sizing Guidance</h4> * * To minimize scaling artifacts across a wide range of car screens, apps should provide * images targeting a 480 x 854 (9:16) dp bounding box. If the image exceeds this maximum * size in either one of the dimensions, it will be scaled down to be centered inside the * bounding box while preserving its aspect ratio. * * @throws NullPointerException if {@code image} is {@code null} */ @RequiresCarApi(4) @NonNull public Builder setImage(@NonNull CarIcon image) { mImage = requireNonNull(image); return this; } /** * Constructs the row list defined by this builder. * * @throws IllegalStateException if the pane is in loading state and also contains rows, or * vice versa */ @NonNull public Pane build() { int size = size(); if (size > 0 == mIsLoading) { throw new IllegalStateException( "The pane is set to loading but is not empty, or vice versa"); } return new Pane(this); } private int size() { return mRows.size(); } /** Returns an empty {@link Builder} instance. */ public Builder() { } } }
Updated PaneTemplate image sizing rules to be a square bounding box Bug: 219542939 Relnote: updated `PaneTemplate` image sizing rules to be a square bounding box Test: n/a Change-Id: Idd72e4584dfa066f8db113afb567a71017fcca85
car/app/app/src/main/java/androidx/car/app/model/Pane.java
Updated PaneTemplate image sizing rules to be a square bounding box
<ide><path>ar/app/app/src/main/java/androidx/car/app/model/Pane.java <ide> * <h4>Image Sizing Guidance</h4> <ide> * <ide> * To minimize scaling artifacts across a wide range of car screens, apps should provide <del> * images targeting a 480 x 854 (9:16) dp bounding box. If the image exceeds this maximum <del> * size in either one of the dimensions, it will be scaled down to be centered inside the <add> * images targeting a 480 x 480 dp bounding box. If the image exceeds this maximum size <add> * in either one of the dimensions, it will be scaled down to be centered inside the <ide> * bounding box while preserving its aspect ratio. <ide> * <ide> * @throws NullPointerException if {@code image} is {@code null}
Java
apache-2.0
b70cd7e5d48b895a8073cfac490a0eafb15b77b7
0
jcamachor/hive,jcamachor/hive,sankarh/hive,anishek/hive,vergilchiu/hive,vergilchiu/hive,anishek/hive,sankarh/hive,alanfgates/hive,lirui-apache/hive,lirui-apache/hive,b-slim/hive,nishantmonu51/hive,nishantmonu51/hive,b-slim/hive,jcamachor/hive,lirui-apache/hive,anishek/hive,jcamachor/hive,nishantmonu51/hive,nishantmonu51/hive,b-slim/hive,sankarh/hive,vineetgarg02/hive,vineetgarg02/hive,b-slim/hive,jcamachor/hive,vergilchiu/hive,nishantmonu51/hive,vineetgarg02/hive,b-slim/hive,sankarh/hive,anishek/hive,nishantmonu51/hive,anishek/hive,vineetgarg02/hive,alanfgates/hive,vergilchiu/hive,nishantmonu51/hive,vergilchiu/hive,vergilchiu/hive,alanfgates/hive,vineetgarg02/hive,vineetgarg02/hive,alanfgates/hive,sankarh/hive,b-slim/hive,sankarh/hive,alanfgates/hive,jcamachor/hive,b-slim/hive,nishantmonu51/hive,lirui-apache/hive,lirui-apache/hive,vergilchiu/hive,anishek/hive,vergilchiu/hive,lirui-apache/hive,nishantmonu51/hive,vineetgarg02/hive,alanfgates/hive,lirui-apache/hive,sankarh/hive,vineetgarg02/hive,alanfgates/hive,alanfgates/hive,alanfgates/hive,anishek/hive,vineetgarg02/hive,jcamachor/hive,jcamachor/hive,lirui-apache/hive,sankarh/hive,jcamachor/hive,anishek/hive,sankarh/hive,anishek/hive,vergilchiu/hive,b-slim/hive,lirui-apache/hive,b-slim/hive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.io.orc; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.ArrayList; import java.util.List; import org.apache.orc.impl.AcidStats; import org.apache.orc.impl.OrcAcidUtils; import org.apache.orc.OrcConf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.io.AcidOutputFormat; import org.apache.hadoop.hive.ql.io.AcidUtils; import org.apache.hadoop.hive.ql.io.RecordIdentifier; import org.apache.hadoop.hive.ql.io.RecordUpdater; import org.apache.hadoop.hive.serde2.SerDeStats; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import com.google.common.annotations.VisibleForTesting; /** * A RecordUpdater where the files are stored as ORC. */ public class OrcRecordUpdater implements RecordUpdater { private static final Logger LOG = LoggerFactory.getLogger(OrcRecordUpdater.class); public static final String ACID_KEY_INDEX_NAME = "hive.acid.key.index"; public static final String ACID_FORMAT = "_orc_acid_version"; public static final int ORC_ACID_VERSION = 0; final static int INSERT_OPERATION = 0; final static int UPDATE_OPERATION = 1; final static int DELETE_OPERATION = 2; final static int OPERATION = 0; final static int ORIGINAL_TRANSACTION = 1; final static int BUCKET = 2; final static int ROW_ID = 3; final static int CURRENT_TRANSACTION = 4; final static int ROW = 5; final static int FIELDS = 6; final static int DELTA_BUFFER_SIZE = 16 * 1024; final static long DELTA_STRIPE_SIZE = 16 * 1024 * 1024; private static final Charset UTF8 = Charset.forName("UTF-8"); private final AcidOutputFormat.Options options; private final Path path; private final FileSystem fs; private Writer writer; private final FSDataOutputStream flushLengths; private final OrcStruct item; private final IntWritable operation = new IntWritable(); private final LongWritable currentTransaction = new LongWritable(-1); private final LongWritable originalTransaction = new LongWritable(-1); private final IntWritable bucket = new IntWritable(); private final LongWritable rowId = new LongWritable(); private long insertedRows = 0; private long rowIdOffset = 0; // This records how many rows have been inserted or deleted. It is separate from insertedRows // because that is monotonically increasing to give new unique row ids. private long rowCountDelta = 0; private final KeyIndexBuilder indexBuilder = new KeyIndexBuilder(); private StructField recIdField = null; // field to look for the record identifier in private StructField rowIdField = null; // field inside recId to look for row id in private StructField originalTxnField = null; // field inside recId to look for original txn in private StructObjectInspector rowInspector; // OI for the original row private StructObjectInspector recIdInspector; // OI for the record identifier struct private LongObjectInspector rowIdInspector; // OI for the long row id inside the recordIdentifier private LongObjectInspector origTxnInspector; // OI for the original txn inside the record // identifer static int getOperation(OrcStruct struct) { return ((IntWritable) struct.getFieldValue(OPERATION)).get(); } static long getCurrentTransaction(OrcStruct struct) { return ((LongWritable) struct.getFieldValue(CURRENT_TRANSACTION)).get(); } static long getOriginalTransaction(OrcStruct struct) { return ((LongWritable) struct.getFieldValue(ORIGINAL_TRANSACTION)).get(); } static int getBucket(OrcStruct struct) { return ((IntWritable) struct.getFieldValue(BUCKET)).get(); } static long getRowId(OrcStruct struct) { return ((LongWritable) struct.getFieldValue(ROW_ID)).get(); } static OrcStruct getRow(OrcStruct struct) { if (struct == null) { return null; } else { return (OrcStruct) struct.getFieldValue(ROW); } } /** * An extension to AcidOutputFormat that allows users to add additional * options. */ public static class OrcOptions extends AcidOutputFormat.Options { OrcFile.WriterOptions orcOptions = null; public OrcOptions(Configuration conf) { super(conf); } public OrcOptions orcOptions(OrcFile.WriterOptions opts) { this.orcOptions = opts; return this; } public OrcFile.WriterOptions getOrcOptions() { return orcOptions; } } /** * Create an object inspector for the ACID event based on the object inspector * for the underlying row. * @param rowInspector the row's object inspector * @return an object inspector for the event stream */ static StructObjectInspector createEventSchema(ObjectInspector rowInspector) { List<StructField> fields = new ArrayList<StructField>(); fields.add(new OrcStruct.Field("operation", PrimitiveObjectInspectorFactory.writableIntObjectInspector, OPERATION)); fields.add(new OrcStruct.Field("originalTransaction", PrimitiveObjectInspectorFactory.writableLongObjectInspector, ORIGINAL_TRANSACTION)); fields.add(new OrcStruct.Field("bucket", PrimitiveObjectInspectorFactory.writableIntObjectInspector, BUCKET)); fields.add(new OrcStruct.Field("rowId", PrimitiveObjectInspectorFactory.writableLongObjectInspector, ROW_ID)); fields.add(new OrcStruct.Field("currentTransaction", PrimitiveObjectInspectorFactory.writableLongObjectInspector, CURRENT_TRANSACTION)); fields.add(new OrcStruct.Field("row", rowInspector, ROW)); return new OrcStruct.OrcStructInspector(fields); } OrcRecordUpdater(Path path, AcidOutputFormat.Options options) throws IOException { this.options = options; this.bucket.set(options.getBucket()); this.path = AcidUtils.createFilename(path, options); FileSystem fs = options.getFilesystem(); if (fs == null) { fs = path.getFileSystem(options.getConfiguration()); } this.fs = fs; Path formatFile = new Path(path, ACID_FORMAT); if(!fs.exists(formatFile)) { try (FSDataOutputStream strm = fs.create(formatFile, false)) { strm.writeInt(ORC_ACID_VERSION); } catch (IOException ioe) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to create " + path + "/" + ACID_FORMAT + " with " + ioe); } } } if (options.getMinimumTransactionId() != options.getMaximumTransactionId() && !options.isWritingBase()){ flushLengths = fs.create(OrcAcidUtils.getSideFile(this.path), true, 8, options.getReporter()); } else { flushLengths = null; } OrcFile.WriterOptions writerOptions = null; // If writing delta dirs, we need to make a clone of original options, to avoid polluting it for // the base writer if (options.isWritingBase()) { if (options instanceof OrcOptions) { writerOptions = ((OrcOptions) options).getOrcOptions(); } if (writerOptions == null) { writerOptions = OrcFile.writerOptions(options.getTableProperties(), options.getConfiguration()); } } else { // delta writer AcidOutputFormat.Options optionsCloneForDelta = options.clone(); if (optionsCloneForDelta instanceof OrcOptions) { writerOptions = ((OrcOptions) optionsCloneForDelta).getOrcOptions(); } if (writerOptions == null) { writerOptions = OrcFile.writerOptions(optionsCloneForDelta.getTableProperties(), optionsCloneForDelta.getConfiguration()); } // get buffer size and stripe size for base writer int baseBufferSizeValue = writerOptions.getBufferSize(); long baseStripeSizeValue = writerOptions.getStripeSize(); // overwrite buffer size and stripe size for delta writer, based on BASE_DELTA_RATIO int ratio = (int) OrcConf.BASE_DELTA_RATIO.getLong(options.getConfiguration()); writerOptions.bufferSize(baseBufferSizeValue / ratio); writerOptions.stripeSize(baseStripeSizeValue / ratio); writerOptions.blockPadding(false); } writerOptions.fileSystem(fs).callback(indexBuilder); rowInspector = (StructObjectInspector)options.getInspector(); writerOptions.inspector(createEventSchema(findRecId(options.getInspector(), options.getRecordIdColumn()))); this.writer = OrcFile.createWriter(this.path, writerOptions); item = new OrcStruct(FIELDS); item.setFieldValue(OPERATION, operation); item.setFieldValue(CURRENT_TRANSACTION, currentTransaction); item.setFieldValue(ORIGINAL_TRANSACTION, originalTransaction); item.setFieldValue(BUCKET, bucket); item.setFieldValue(ROW_ID, rowId); } public String toString() { return getClass().getName() + "[" + path +"]"; } /** * To handle multiple INSERT... statements in a single transaction, we want to make sure * to generate unique {@code rowId} for all inserted rows of the transaction. * @return largest rowId created by previous statements (maybe 0) * @throws IOException */ private long findRowIdOffsetForInsert() throws IOException { /* * 1. need to know bucket we are writing to * 2. need to know which delta dir it's in * Then, * 1. find the same bucket file in previous delta dir for this txn * 2. read the footer and get AcidStats which has insert count * 2.1 if AcidStats.inserts>0 done * else go to previous delta file * For example, consider insert/update/insert case...*/ if(options.getStatementId() <= 0) { return 0;//there is only 1 statement in this transaction (so far) } for(int pastStmt = options.getStatementId() - 1; pastStmt >= 0; pastStmt--) { Path matchingBucket = AcidUtils.createFilename(options.getFinalDestination(), options.clone().statementId(pastStmt)); if(!fs.exists(matchingBucket)) { continue; } Reader reader = OrcFile.createReader(matchingBucket, OrcFile.readerOptions(options.getConfiguration())); //no close() on Reader?! AcidStats acidStats = OrcAcidUtils.parseAcidStats(reader); if(acidStats.inserts > 0) { return acidStats.inserts; } } //if we got here, we looked at all delta files in this txn, prior to current statement and didn't //find any inserts... return 0; } // Find the record identifier column (if there) and return a possibly new ObjectInspector that // will strain out the record id for the underlying writer. private ObjectInspector findRecId(ObjectInspector inspector, int rowIdColNum) { if (!(inspector instanceof StructObjectInspector)) { throw new RuntimeException("Serious problem, expected a StructObjectInspector, but got a " + inspector.getClass().getName()); } if (rowIdColNum < 0) { return inspector; } else { RecIdStrippingObjectInspector newInspector = new RecIdStrippingObjectInspector(inspector, rowIdColNum); recIdField = newInspector.getRecId(); List<? extends StructField> fields = ((StructObjectInspector) recIdField.getFieldObjectInspector()).getAllStructFieldRefs(); // Go by position, not field name, as field names aren't guaranteed. The order of fields // in RecordIdentifier is transactionId, bucketId, rowId originalTxnField = fields.get(0); origTxnInspector = (LongObjectInspector)originalTxnField.getFieldObjectInspector(); rowIdField = fields.get(2); rowIdInspector = (LongObjectInspector)rowIdField.getFieldObjectInspector(); recIdInspector = (StructObjectInspector) recIdField.getFieldObjectInspector(); return newInspector; } } private void addEvent(int operation, long currentTransaction, long rowId, Object row) throws IOException { this.operation.set(operation); this.currentTransaction.set(currentTransaction); // If this is an insert, originalTransaction should be set to this transaction. If not, // it will be reset by the following if anyway. long originalTransaction = currentTransaction; if (operation == DELETE_OPERATION || operation == UPDATE_OPERATION) { Object rowIdValue = rowInspector.getStructFieldData(row, recIdField); originalTransaction = origTxnInspector.get( recIdInspector.getStructFieldData(rowIdValue, originalTxnField)); rowId = rowIdInspector.get(recIdInspector.getStructFieldData(rowIdValue, rowIdField)); } else if(operation == INSERT_OPERATION) { rowId += rowIdOffset; } this.rowId.set(rowId); this.originalTransaction.set(originalTransaction); item.setFieldValue(OrcRecordUpdater.ROW, (operation == DELETE_OPERATION ? null : row)); indexBuilder.addKey(operation, originalTransaction, bucket.get(), rowId); writer.addRow(item); } @Override public void insert(long currentTransaction, Object row) throws IOException { if (this.currentTransaction.get() != currentTransaction) { insertedRows = 0; //this method is almost no-op in hcatalog.streaming case since statementId == 0 is //always true in that case rowIdOffset = findRowIdOffsetForInsert(); } addEvent(INSERT_OPERATION, currentTransaction, insertedRows++, row); rowCountDelta++; } @Override public void update(long currentTransaction, Object row) throws IOException { if (this.currentTransaction.get() != currentTransaction) { insertedRows = 0; } addEvent(UPDATE_OPERATION, currentTransaction, -1L, row); } @Override public void delete(long currentTransaction, Object row) throws IOException { if (this.currentTransaction.get() != currentTransaction) { insertedRows = 0; } addEvent(DELETE_OPERATION, currentTransaction, -1, row); rowCountDelta--; } @Override public void flush() throws IOException { // We only support flushes on files with multiple transactions, because // flushes create significant overhead in HDFS. Record updaters with a // single transaction should be closed rather than flushed. if (flushLengths == null) { throw new IllegalStateException("Attempting to flush a RecordUpdater on " + path + " with a single transaction."); } long len = writer.writeIntermediateFooter(); flushLengths.writeLong(len); OrcInputFormat.SHIMS.hflush(flushLengths); } @Override public void close(boolean abort) throws IOException { if (abort) { if (flushLengths == null) { fs.delete(path, false); } } else { if (writer != null) writer.close(); } if (flushLengths != null) { flushLengths.close(); fs.delete(OrcAcidUtils.getSideFile(path), false); } writer = null; } @Override public SerDeStats getStats() { SerDeStats stats = new SerDeStats(); stats.setRowCount(rowCountDelta); // Don't worry about setting raw data size diff. I have no idea how to calculate that // without finding the row we are updating or deleting, which would be a mess. return stats; } @VisibleForTesting Writer getWriter() { return writer; } private static final Charset utf8 = Charset.forName("UTF-8"); private static final CharsetDecoder utf8Decoder = utf8.newDecoder(); static RecordIdentifier[] parseKeyIndex(Reader reader) { String[] stripes; try { ByteBuffer val = reader.getMetadataValue(OrcRecordUpdater.ACID_KEY_INDEX_NAME) .duplicate(); stripes = utf8Decoder.decode(val).toString().split(";"); } catch (CharacterCodingException e) { throw new IllegalArgumentException("Bad string encoding for " + OrcRecordUpdater.ACID_KEY_INDEX_NAME, e); } RecordIdentifier[] result = new RecordIdentifier[stripes.length]; for(int i=0; i < stripes.length; ++i) { if (stripes[i].length() != 0) { String[] parts = stripes[i].split(","); result[i] = new RecordIdentifier(); result[i].setValues(Long.parseLong(parts[0]), Integer.parseInt(parts[1]), Long.parseLong(parts[2])); } } return result; } static class KeyIndexBuilder implements OrcFile.WriterCallback { StringBuilder lastKey = new StringBuilder(); long lastTransaction; int lastBucket; long lastRowId; AcidStats acidStats = new AcidStats(); @Override public void preStripeWrite(OrcFile.WriterContext context ) throws IOException { lastKey.append(lastTransaction); lastKey.append(','); lastKey.append(lastBucket); lastKey.append(','); lastKey.append(lastRowId); lastKey.append(';'); } @Override public void preFooterWrite(OrcFile.WriterContext context ) throws IOException { context.getWriter().addUserMetadata(ACID_KEY_INDEX_NAME, UTF8.encode(lastKey.toString())); context.getWriter().addUserMetadata(OrcAcidUtils.ACID_STATS, UTF8.encode(acidStats.serialize())); } void addKey(int op, long transaction, int bucket, long rowId) { switch (op) { case INSERT_OPERATION: acidStats.inserts += 1; break; case UPDATE_OPERATION: acidStats.updates += 1; break; case DELETE_OPERATION: acidStats.deletes += 1; break; default: throw new IllegalArgumentException("Unknown operation " + op); } lastTransaction = transaction; lastBucket = bucket; lastRowId = rowId; } } /** * An ObjectInspector that will strip out the record identifier so that the underlying writer * doesn't see it. */ private static class RecIdStrippingObjectInspector extends StructObjectInspector { private StructObjectInspector wrapped; List<StructField> fields; StructField recId; RecIdStrippingObjectInspector(ObjectInspector oi, int rowIdColNum) { if (!(oi instanceof StructObjectInspector)) { throw new RuntimeException("Serious problem, expected a StructObjectInspector, " + "but got a " + oi.getClass().getName()); } wrapped = (StructObjectInspector)oi; List<? extends StructField> wrappedFields = wrapped.getAllStructFieldRefs(); fields = new ArrayList<StructField>(wrapped.getAllStructFieldRefs().size()); for (int i = 0; i < wrappedFields.size(); i++) { if (i == rowIdColNum) { recId = wrappedFields.get(i); } else { fields.add(wrappedFields.get(i)); } } } @Override public List<? extends StructField> getAllStructFieldRefs() { return fields; } @Override public StructField getStructFieldRef(String fieldName) { return wrapped.getStructFieldRef(fieldName); } @Override public Object getStructFieldData(Object data, StructField fieldRef) { // For performance don't check that that the fieldRef isn't recId everytime, // just assume that the caller used getAllStructFieldRefs and thus doesn't have that fieldRef return wrapped.getStructFieldData(data, fieldRef); } @Override public List<Object> getStructFieldsDataAsList(Object data) { return wrapped.getStructFieldsDataAsList(data); } @Override public String getTypeName() { return wrapped.getTypeName(); } @Override public Category getCategory() { return wrapped.getCategory(); } StructField getRecId() { return recId; } } }
ql/src/java/org/apache/hadoop/hive/ql/io/orc/OrcRecordUpdater.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.hive.ql.io.orc; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.ArrayList; import java.util.List; import org.apache.orc.impl.AcidStats; import org.apache.orc.impl.OrcAcidUtils; import org.apache.orc.OrcConf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.io.AcidOutputFormat; import org.apache.hadoop.hive.ql.io.AcidUtils; import org.apache.hadoop.hive.ql.io.RecordIdentifier; import org.apache.hadoop.hive.ql.io.RecordUpdater; import org.apache.hadoop.hive.serde2.SerDeStats; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import com.google.common.annotations.VisibleForTesting; /** * A RecordUpdater where the files are stored as ORC. */ public class OrcRecordUpdater implements RecordUpdater { private static final Logger LOG = LoggerFactory.getLogger(OrcRecordUpdater.class); public static final String ACID_KEY_INDEX_NAME = "hive.acid.key.index"; public static final String ACID_FORMAT = "_orc_acid_version"; public static final int ORC_ACID_VERSION = 0; final static int INSERT_OPERATION = 0; final static int UPDATE_OPERATION = 1; final static int DELETE_OPERATION = 2; final static int OPERATION = 0; final static int ORIGINAL_TRANSACTION = 1; final static int BUCKET = 2; final static int ROW_ID = 3; final static int CURRENT_TRANSACTION = 4; final static int ROW = 5; final static int FIELDS = 6; final static int DELTA_BUFFER_SIZE = 16 * 1024; final static long DELTA_STRIPE_SIZE = 16 * 1024 * 1024; private static final Charset UTF8 = Charset.forName("UTF-8"); private final AcidOutputFormat.Options options; private final Path path; private final FileSystem fs; private Writer writer; private final FSDataOutputStream flushLengths; private final OrcStruct item; private final IntWritable operation = new IntWritable(); private final LongWritable currentTransaction = new LongWritable(-1); private final LongWritable originalTransaction = new LongWritable(-1); private final IntWritable bucket = new IntWritable(); private final LongWritable rowId = new LongWritable(); private long insertedRows = 0; private long rowIdOffset = 0; // This records how many rows have been inserted or deleted. It is separate from insertedRows // because that is monotonically increasing to give new unique row ids. private long rowCountDelta = 0; private final KeyIndexBuilder indexBuilder = new KeyIndexBuilder(); private StructField recIdField = null; // field to look for the record identifier in private StructField rowIdField = null; // field inside recId to look for row id in private StructField originalTxnField = null; // field inside recId to look for original txn in private StructObjectInspector rowInspector; // OI for the original row private StructObjectInspector recIdInspector; // OI for the record identifier struct private LongObjectInspector rowIdInspector; // OI for the long row id inside the recordIdentifier private LongObjectInspector origTxnInspector; // OI for the original txn inside the record // identifer static int getOperation(OrcStruct struct) { return ((IntWritable) struct.getFieldValue(OPERATION)).get(); } static long getCurrentTransaction(OrcStruct struct) { return ((LongWritable) struct.getFieldValue(CURRENT_TRANSACTION)).get(); } static long getOriginalTransaction(OrcStruct struct) { return ((LongWritable) struct.getFieldValue(ORIGINAL_TRANSACTION)).get(); } static int getBucket(OrcStruct struct) { return ((IntWritable) struct.getFieldValue(BUCKET)).get(); } static long getRowId(OrcStruct struct) { return ((LongWritable) struct.getFieldValue(ROW_ID)).get(); } static OrcStruct getRow(OrcStruct struct) { if (struct == null) { return null; } else { return (OrcStruct) struct.getFieldValue(ROW); } } /** * An extension to AcidOutputFormat that allows users to add additional * options. */ public static class OrcOptions extends AcidOutputFormat.Options { OrcFile.WriterOptions orcOptions = null; public OrcOptions(Configuration conf) { super(conf); } public OrcOptions orcOptions(OrcFile.WriterOptions opts) { this.orcOptions = opts; return this; } public OrcFile.WriterOptions getOrcOptions() { return orcOptions; } } /** * Create an object inspector for the ACID event based on the object inspector * for the underlying row. * @param rowInspector the row's object inspector * @return an object inspector for the event stream */ static StructObjectInspector createEventSchema(ObjectInspector rowInspector) { List<StructField> fields = new ArrayList<StructField>(); fields.add(new OrcStruct.Field("operation", PrimitiveObjectInspectorFactory.writableIntObjectInspector, OPERATION)); fields.add(new OrcStruct.Field("originalTransaction", PrimitiveObjectInspectorFactory.writableLongObjectInspector, ORIGINAL_TRANSACTION)); fields.add(new OrcStruct.Field("bucket", PrimitiveObjectInspectorFactory.writableIntObjectInspector, BUCKET)); fields.add(new OrcStruct.Field("rowId", PrimitiveObjectInspectorFactory.writableLongObjectInspector, ROW_ID)); fields.add(new OrcStruct.Field("currentTransaction", PrimitiveObjectInspectorFactory.writableLongObjectInspector, CURRENT_TRANSACTION)); fields.add(new OrcStruct.Field("row", rowInspector, ROW)); return new OrcStruct.OrcStructInspector(fields); } OrcRecordUpdater(Path path, AcidOutputFormat.Options options) throws IOException { this.options = options; this.bucket.set(options.getBucket()); this.path = AcidUtils.createFilename(path, options); FileSystem fs = options.getFilesystem(); if (fs == null) { fs = path.getFileSystem(options.getConfiguration()); } this.fs = fs; try { FSDataOutputStream strm = fs.create(new Path(path, ACID_FORMAT), false); strm.writeInt(ORC_ACID_VERSION); strm.close(); } catch (IOException ioe) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to create " + path + "/" + ACID_FORMAT + " with " + ioe); } } if (options.getMinimumTransactionId() != options.getMaximumTransactionId() && !options.isWritingBase()){ flushLengths = fs.create(OrcAcidUtils.getSideFile(this.path), true, 8, options.getReporter()); } else { flushLengths = null; } OrcFile.WriterOptions writerOptions = null; // If writing delta dirs, we need to make a clone of original options, to avoid polluting it for // the base writer if (options.isWritingBase()) { if (options instanceof OrcOptions) { writerOptions = ((OrcOptions) options).getOrcOptions(); } if (writerOptions == null) { writerOptions = OrcFile.writerOptions(options.getTableProperties(), options.getConfiguration()); } } else { // delta writer AcidOutputFormat.Options optionsCloneForDelta = options.clone(); if (optionsCloneForDelta instanceof OrcOptions) { writerOptions = ((OrcOptions) optionsCloneForDelta).getOrcOptions(); } if (writerOptions == null) { writerOptions = OrcFile.writerOptions(optionsCloneForDelta.getTableProperties(), optionsCloneForDelta.getConfiguration()); } // get buffer size and stripe size for base writer int baseBufferSizeValue = writerOptions.getBufferSize(); long baseStripeSizeValue = writerOptions.getStripeSize(); // overwrite buffer size and stripe size for delta writer, based on BASE_DELTA_RATIO int ratio = (int) OrcConf.BASE_DELTA_RATIO.getLong(options.getConfiguration()); writerOptions.bufferSize(baseBufferSizeValue / ratio); writerOptions.stripeSize(baseStripeSizeValue / ratio); writerOptions.blockPadding(false); } writerOptions.fileSystem(fs).callback(indexBuilder); rowInspector = (StructObjectInspector)options.getInspector(); writerOptions.inspector(createEventSchema(findRecId(options.getInspector(), options.getRecordIdColumn()))); this.writer = OrcFile.createWriter(this.path, writerOptions); item = new OrcStruct(FIELDS); item.setFieldValue(OPERATION, operation); item.setFieldValue(CURRENT_TRANSACTION, currentTransaction); item.setFieldValue(ORIGINAL_TRANSACTION, originalTransaction); item.setFieldValue(BUCKET, bucket); item.setFieldValue(ROW_ID, rowId); } public String toString() { return getClass().getName() + "[" + path +"]"; } /** * To handle multiple INSERT... statements in a single transaction, we want to make sure * to generate unique {@code rowId} for all inserted rows of the transaction. * @return largest rowId created by previous statements (maybe 0) * @throws IOException */ private long findRowIdOffsetForInsert() throws IOException { /* * 1. need to know bucket we are writing to * 2. need to know which delta dir it's in * Then, * 1. find the same bucket file in previous delta dir for this txn * 2. read the footer and get AcidStats which has insert count * 2.1 if AcidStats.inserts>0 done * else go to previous delta file * For example, consider insert/update/insert case...*/ if(options.getStatementId() <= 0) { return 0;//there is only 1 statement in this transaction (so far) } for(int pastStmt = options.getStatementId() - 1; pastStmt >= 0; pastStmt--) { Path matchingBucket = AcidUtils.createFilename(options.getFinalDestination(), options.clone().statementId(pastStmt)); if(!fs.exists(matchingBucket)) { continue; } Reader reader = OrcFile.createReader(matchingBucket, OrcFile.readerOptions(options.getConfiguration())); //no close() on Reader?! AcidStats acidStats = OrcAcidUtils.parseAcidStats(reader); if(acidStats.inserts > 0) { return acidStats.inserts; } } //if we got here, we looked at all delta files in this txn, prior to current statement and didn't //find any inserts... return 0; } // Find the record identifier column (if there) and return a possibly new ObjectInspector that // will strain out the record id for the underlying writer. private ObjectInspector findRecId(ObjectInspector inspector, int rowIdColNum) { if (!(inspector instanceof StructObjectInspector)) { throw new RuntimeException("Serious problem, expected a StructObjectInspector, but got a " + inspector.getClass().getName()); } if (rowIdColNum < 0) { return inspector; } else { RecIdStrippingObjectInspector newInspector = new RecIdStrippingObjectInspector(inspector, rowIdColNum); recIdField = newInspector.getRecId(); List<? extends StructField> fields = ((StructObjectInspector) recIdField.getFieldObjectInspector()).getAllStructFieldRefs(); // Go by position, not field name, as field names aren't guaranteed. The order of fields // in RecordIdentifier is transactionId, bucketId, rowId originalTxnField = fields.get(0); origTxnInspector = (LongObjectInspector)originalTxnField.getFieldObjectInspector(); rowIdField = fields.get(2); rowIdInspector = (LongObjectInspector)rowIdField.getFieldObjectInspector(); recIdInspector = (StructObjectInspector) recIdField.getFieldObjectInspector(); return newInspector; } } private void addEvent(int operation, long currentTransaction, long rowId, Object row) throws IOException { this.operation.set(operation); this.currentTransaction.set(currentTransaction); // If this is an insert, originalTransaction should be set to this transaction. If not, // it will be reset by the following if anyway. long originalTransaction = currentTransaction; if (operation == DELETE_OPERATION || operation == UPDATE_OPERATION) { Object rowIdValue = rowInspector.getStructFieldData(row, recIdField); originalTransaction = origTxnInspector.get( recIdInspector.getStructFieldData(rowIdValue, originalTxnField)); rowId = rowIdInspector.get(recIdInspector.getStructFieldData(rowIdValue, rowIdField)); } else if(operation == INSERT_OPERATION) { rowId += rowIdOffset; } this.rowId.set(rowId); this.originalTransaction.set(originalTransaction); item.setFieldValue(OrcRecordUpdater.ROW, (operation == DELETE_OPERATION ? null : row)); indexBuilder.addKey(operation, originalTransaction, bucket.get(), rowId); writer.addRow(item); } @Override public void insert(long currentTransaction, Object row) throws IOException { if (this.currentTransaction.get() != currentTransaction) { insertedRows = 0; //this method is almost no-op in hcatalog.streaming case since statementId == 0 is //always true in that case rowIdOffset = findRowIdOffsetForInsert(); } addEvent(INSERT_OPERATION, currentTransaction, insertedRows++, row); rowCountDelta++; } @Override public void update(long currentTransaction, Object row) throws IOException { if (this.currentTransaction.get() != currentTransaction) { insertedRows = 0; } addEvent(UPDATE_OPERATION, currentTransaction, -1L, row); } @Override public void delete(long currentTransaction, Object row) throws IOException { if (this.currentTransaction.get() != currentTransaction) { insertedRows = 0; } addEvent(DELETE_OPERATION, currentTransaction, -1, row); rowCountDelta--; } @Override public void flush() throws IOException { // We only support flushes on files with multiple transactions, because // flushes create significant overhead in HDFS. Record updaters with a // single transaction should be closed rather than flushed. if (flushLengths == null) { throw new IllegalStateException("Attempting to flush a RecordUpdater on " + path + " with a single transaction."); } long len = writer.writeIntermediateFooter(); flushLengths.writeLong(len); OrcInputFormat.SHIMS.hflush(flushLengths); } @Override public void close(boolean abort) throws IOException { if (abort) { if (flushLengths == null) { fs.delete(path, false); } } else { if (writer != null) writer.close(); } if (flushLengths != null) { flushLengths.close(); fs.delete(OrcAcidUtils.getSideFile(path), false); } writer = null; } @Override public SerDeStats getStats() { SerDeStats stats = new SerDeStats(); stats.setRowCount(rowCountDelta); // Don't worry about setting raw data size diff. I have no idea how to calculate that // without finding the row we are updating or deleting, which would be a mess. return stats; } @VisibleForTesting Writer getWriter() { return writer; } private static final Charset utf8 = Charset.forName("UTF-8"); private static final CharsetDecoder utf8Decoder = utf8.newDecoder(); static RecordIdentifier[] parseKeyIndex(Reader reader) { String[] stripes; try { ByteBuffer val = reader.getMetadataValue(OrcRecordUpdater.ACID_KEY_INDEX_NAME) .duplicate(); stripes = utf8Decoder.decode(val).toString().split(";"); } catch (CharacterCodingException e) { throw new IllegalArgumentException("Bad string encoding for " + OrcRecordUpdater.ACID_KEY_INDEX_NAME, e); } RecordIdentifier[] result = new RecordIdentifier[stripes.length]; for(int i=0; i < stripes.length; ++i) { if (stripes[i].length() != 0) { String[] parts = stripes[i].split(","); result[i] = new RecordIdentifier(); result[i].setValues(Long.parseLong(parts[0]), Integer.parseInt(parts[1]), Long.parseLong(parts[2])); } } return result; } static class KeyIndexBuilder implements OrcFile.WriterCallback { StringBuilder lastKey = new StringBuilder(); long lastTransaction; int lastBucket; long lastRowId; AcidStats acidStats = new AcidStats(); @Override public void preStripeWrite(OrcFile.WriterContext context ) throws IOException { lastKey.append(lastTransaction); lastKey.append(','); lastKey.append(lastBucket); lastKey.append(','); lastKey.append(lastRowId); lastKey.append(';'); } @Override public void preFooterWrite(OrcFile.WriterContext context ) throws IOException { context.getWriter().addUserMetadata(ACID_KEY_INDEX_NAME, UTF8.encode(lastKey.toString())); context.getWriter().addUserMetadata(OrcAcidUtils.ACID_STATS, UTF8.encode(acidStats.serialize())); } void addKey(int op, long transaction, int bucket, long rowId) { switch (op) { case INSERT_OPERATION: acidStats.inserts += 1; break; case UPDATE_OPERATION: acidStats.updates += 1; break; case DELETE_OPERATION: acidStats.deletes += 1; break; default: throw new IllegalArgumentException("Unknown operation " + op); } lastTransaction = transaction; lastBucket = bucket; lastRowId = rowId; } } /** * An ObjectInspector that will strip out the record identifier so that the underlying writer * doesn't see it. */ private static class RecIdStrippingObjectInspector extends StructObjectInspector { private StructObjectInspector wrapped; List<StructField> fields; StructField recId; RecIdStrippingObjectInspector(ObjectInspector oi, int rowIdColNum) { if (!(oi instanceof StructObjectInspector)) { throw new RuntimeException("Serious problem, expected a StructObjectInspector, " + "but got a " + oi.getClass().getName()); } wrapped = (StructObjectInspector)oi; List<? extends StructField> wrappedFields = wrapped.getAllStructFieldRefs(); fields = new ArrayList<StructField>(wrapped.getAllStructFieldRefs().size()); for (int i = 0; i < wrappedFields.size(); i++) { if (i == rowIdColNum) { recId = wrappedFields.get(i); } else { fields.add(wrappedFields.get(i)); } } } @Override public List<? extends StructField> getAllStructFieldRefs() { return fields; } @Override public StructField getStructFieldRef(String fieldName) { return wrapped.getStructFieldRef(fieldName); } @Override public Object getStructFieldData(Object data, StructField fieldRef) { // For performance don't check that that the fieldRef isn't recId everytime, // just assume that the caller used getAllStructFieldRefs and thus doesn't have that fieldRef return wrapped.getStructFieldData(data, fieldRef); } @Override public List<Object> getStructFieldsDataAsList(Object data) { return wrapped.getStructFieldsDataAsList(data); } @Override public String getTypeName() { return wrapped.getTypeName(); } @Override public Category getCategory() { return wrapped.getCategory(); } StructField getRecId() { return recId; } } }
HIVE-14297 OrcRecordUpdater floods logs trying to create _orc_acid_version file (Eugene Koifman, reviewed by Owen O'Malley)
ql/src/java/org/apache/hadoop/hive/ql/io/orc/OrcRecordUpdater.java
HIVE-14297 OrcRecordUpdater floods logs trying to create _orc_acid_version file (Eugene Koifman, reviewed by Owen O'Malley)
<ide><path>l/src/java/org/apache/hadoop/hive/ql/io/orc/OrcRecordUpdater.java <ide> fs = path.getFileSystem(options.getConfiguration()); <ide> } <ide> this.fs = fs; <del> try { <del> FSDataOutputStream strm = fs.create(new Path(path, ACID_FORMAT), false); <del> strm.writeInt(ORC_ACID_VERSION); <del> strm.close(); <del> } catch (IOException ioe) { <del> if (LOG.isDebugEnabled()) { <del> LOG.debug("Failed to create " + path + "/" + ACID_FORMAT + " with " + <add> Path formatFile = new Path(path, ACID_FORMAT); <add> if(!fs.exists(formatFile)) { <add> try (FSDataOutputStream strm = fs.create(formatFile, false)) { <add> strm.writeInt(ORC_ACID_VERSION); <add> } catch (IOException ioe) { <add> if (LOG.isDebugEnabled()) { <add> LOG.debug("Failed to create " + path + "/" + ACID_FORMAT + " with " + <ide> ioe); <add> } <ide> } <ide> } <ide> if (options.getMinimumTransactionId() != options.getMaximumTransactionId()
JavaScript
mit
8c9ca84725df799784f9d5d70bf15581e85efbab
0
RAllner/fassets_core,RAllner/fassets_core
$(function(){ $( "#facets" ).sortable({ axis: "y", handle: ".handle", update: function (e, ui){ $.post($(this).data('update-url'), $(this).sortable('serialize')+"&catalog_id="+$(this).data('catalog_id')) } }); $("#assets li.asset").draggable({ handle: ".handle", helper: "clone", connectToSortable: "#tray ol", start:function(e, ui) { $('#tray ol').addClass("active"); }, stop:function(e, ui) { $('#tray ol').removeClass("active"); } }); $("#catalog_main").droppable({ accept:'.asset', activeClass:'active', hoverClass:'hover', drop:function(ev,ui){ var id; var asset = $(ui.draggable).clone(); if ($(ui.draggable).is("[id^='tp']")) { id = $(ui.draggable).attr("rel"); asset.find("input").remove(); asset.attr("id", "asset_" + id); } else { id = $(ui.draggable).attr("asset_id"); } $.ajax({ type: 'put', url: window.location.href + "/add_asset", data: "&asset_id="+id, success: function(){ window.location.reload(); } }); } }); });
app/assets/javascripts/fassets_core/catalogs.js
$(function(){ $("#assets li.asset").draggable({ handle: ".handle", helper: "clone", connectToSortable: "#tray ol", start:function(e, ui) { $('#tray ol').addClass("active"); }, stop:function(e, ui) { $('#tray ol').removeClass("active"); } }); $("#catalog_main").droppable({ accept:'.asset', activeClass:'active', hoverClass:'hover', drop:function(ev,ui){ var id; var asset = $(ui.draggable).clone(); if ($(ui.draggable).is("[id^='tp']")) { id = $(ui.draggable).attr("rel"); asset.find("input").remove(); asset.attr("id", "asset_" + id); } else { id = $(ui.draggable).attr("asset_id"); } $.ajax({ type: 'put', url: window.location.href + "/add_asset", data: "&asset_id="+id, success: function(){ window.location.reload(); } }); } }); });
Add jquery-ui sortable function
app/assets/javascripts/fassets_core/catalogs.js
Add jquery-ui sortable function
<ide><path>pp/assets/javascripts/fassets_core/catalogs.js <ide> $(function(){ <add> $( "#facets" ).sortable({ <add> axis: "y", <add> handle: ".handle", <add> update: function (e, ui){ <add> $.post($(this).data('update-url'), $(this).sortable('serialize')+"&catalog_id="+$(this).data('catalog_id')) <add> } <add> }); <add> <ide> $("#assets li.asset").draggable({ <ide> handle: ".handle", <ide> helper: "clone",
Java
mpl-2.0
a0931edcc1709b74570a7acdd8e6ac9cca3b2321
0
pith/seed,adrienlauer/seed,adrienlauer/seed,kavi87/seed,Sherpard/seed,seedstack/seed,seedstack/seed,adrienlauer/seed,seedstack/seed,Sherpard/seed,pith/seed,Sherpard/seed,kavi87/seed,pith/seed,kavi87/seed
/** * Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.rest.internal; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.sun.jersey.spi.container.ResourceFilterFactory; import io.nuun.kernel.api.Plugin; import io.nuun.kernel.api.plugin.InitState; import io.nuun.kernel.api.plugin.PluginException; import io.nuun.kernel.api.plugin.context.Context; import io.nuun.kernel.api.plugin.context.InitContext; import io.nuun.kernel.api.plugin.request.ClasspathScanRequest; import io.nuun.kernel.core.AbstractPlugin; import org.apache.commons.configuration.Configuration; import org.kametic.specifications.Specification; import org.seedstack.seed.core.internal.application.ApplicationPlugin; import org.seedstack.seed.core.utils.SeedConfigurationUtils; import org.seedstack.seed.rest.RelRegistry; import org.seedstack.seed.rest.ResourceFiltering; import org.seedstack.seed.rest.internal.exceptionmapper.AuthenticationExceptionMapper; import org.seedstack.seed.rest.internal.exceptionmapper.AuthorizationExceptionMapper; import org.seedstack.seed.rest.internal.exceptionmapper.InternalErrorExceptionMapper; import org.seedstack.seed.rest.internal.exceptionmapper.WebApplicationExceptionMapper; import org.seedstack.seed.rest.internal.hal.RelRegistryImpl; import org.seedstack.seed.rest.internal.jsonhome.JsonHome; import org.seedstack.seed.rest.internal.jsonhome.JsonHomeRootResource; import org.seedstack.seed.rest.internal.jsonhome.Resource; import org.seedstack.seed.rest.spi.RootResource; import org.seedstack.seed.web.internal.WebPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.servlet.ServletContext; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Variant; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; /** * This plugin enables JAX-RS usage in SEED applications. The JAX-RS implementation is Jersey. * * @author [email protected] */ public class RestPlugin extends AbstractPlugin { private static final String REST_PLUGIN_CONFIGURATION_PREFIX = "org.seedstack.seed.rest"; private static final Logger LOGGER = LoggerFactory.getLogger(RestPlugin.class); private final Specification<Class<?>> resourcesSpecification = new JaxRsResourceSpecification(); private final Specification<Class<?>> providersSpecification = new JaxRsProviderSpecification(); private WebPlugin webPlugin; private Configuration restConfiguration; private final Map<Variant, Class<? extends RootResource>> rootResourceClasses = new HashMap<Variant, Class<? extends RootResource>>(); private RelRegistry relRegistry; private JsonHome jsonHome; private String restPath; private String jspPath; private ServletContext servletContext; @Override public String name() { return "seed-rest-plugin"; } @Override public InitState init(InitContext initContext) { // Initialize required and dependent plugins collectPlugins(initContext); Map<Specification, Collection<Class<?>>> scannedClassesBySpecification = initContext.scannedTypesBySpecification(); Collection<Class<?>> resourceClasses = scannedClassesBySpecification.get(resourcesSpecification); restPath = restConfiguration.getString("path", ""); jspPath = restConfiguration.getString("jsp-path", "/WEB-INF/jsp"); // Scan resource for HAL and JSON-HOME scanResources(restPath, restConfiguration, resourceClasses); // Register JSON-HOME as root resource registerRootResource(new Variant(new MediaType("application", "json"), null, null), JsonHomeRootResource.class); // Skip the rest of the init phase if we are not in a servlet context if (servletContext == null) { LOGGER.info("No servlet context detected, REST support disabled"); return InitState.INITIALIZED; } Set<Class<? extends ResourceFilterFactory>> resourceFilterFactories = scanResourceFilterFactories(initContext); Map<String, String> jerseyParameters = scanJerseyParameters(); webPlugin.registerAdditionalModule( new RestModule( rootResourceClasses, resourceClasses, scannedClassesBySpecification.get(providersSpecification), jerseyParameters, resourceFilterFactories, restPath, jspPath, jsonHome) ); return InitState.INITIALIZED; } @Inject private Injector injector; @Override public void start(Context context) { if (servletContext != null) { SeedContainer seedContainer = injector.getInstance(SeedContainer.class); if (restConfiguration.getBoolean("map-security-exceptions", true)) { seedContainer.registerClass(AuthenticationExceptionMapper.class); seedContainer.registerClass(AuthorizationExceptionMapper.class); } if (restConfiguration.getBoolean("map-all-exceptions", true)) { seedContainer.registerClass(WebApplicationExceptionMapper.class); injector.injectMembers(InternalErrorExceptionMapper.class); seedContainer.registerClass(InternalErrorExceptionMapper.class); } } } private void collectPlugins(InitContext initContext) { restConfiguration = null; webPlugin = null; for (Plugin plugin : initContext.pluginsRequired()) { if (plugin instanceof ApplicationPlugin) { restConfiguration = ((ApplicationPlugin) plugin).getApplication().getConfiguration().subset(RestPlugin.REST_PLUGIN_CONFIGURATION_PREFIX); } else if (plugin instanceof WebPlugin) { webPlugin = (WebPlugin) plugin; } } if (restConfiguration == null) { throw new PluginException("Unable to find SEED application plugin"); } if (webPlugin == null) { throw new PluginException("Unable to find SEED Web plugin"); } } private Collection<Class<?>> scanResources(String restPath, Configuration restConfiguration, Collection<Class<?>> resourceClasses) { String baseRel = restConfiguration.getString("baseRel", ""); String baseParam = restConfiguration.getString("baseParam", ""); ResourceScanner resourceScanner = new ResourceScanner(restPath, baseRel, baseParam) .scan(resourceClasses); Map<String, Resource> resourceMap = resourceScanner.jsonHomeResources(); relRegistry = new RelRegistryImpl(resourceScanner.halLinks()); jsonHome = new JsonHome(resourceMap); return resourceClasses; } private Set<Class<? extends ResourceFilterFactory>> scanResourceFilterFactories(InitContext initContext) { Map<Class<? extends Annotation>, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext.scannedClassesByAnnotationClass(); Collection<Class<?>> resourceFilterFactoryClasses = scannedClassesByAnnotationClass.get(ResourceFiltering.class); Set<Class<? extends ResourceFilterFactory>> resourceFilterFactories = new HashSet<Class<? extends ResourceFilterFactory>>(); if (resourceFilterFactoryClasses != null) { for (Class<?> candidate : resourceFilterFactoryClasses) { if (ResourceFilterFactory.class.isAssignableFrom(candidate)) { resourceFilterFactories.add(candidate.asSubclass(ResourceFilterFactory.class)); } } } return resourceFilterFactories; } private Map<String, String> scanJerseyParameters() { Map<String, String> jerseyParameters = new HashMap<String, String>(); Properties jerseyProperties = SeedConfigurationUtils.buildPropertiesFromConfiguration(restConfiguration, "jersey.property"); for (Object key : jerseyProperties.keySet()) { jerseyParameters.put(key.toString(), jerseyProperties.getProperty(key.toString())); } return jerseyParameters; } @Override public Object nativeUnitModule() { return new AbstractModule() { @Override protected void configure() { bind(RelRegistry.class).toInstance(relRegistry); } }; } @Override public void provideContainerContext(Object containerContext) { if (containerContext != null && ServletContext.class.isAssignableFrom(containerContext.getClass())) { this.servletContext = (ServletContext) containerContext; } } @Override @SuppressWarnings("unchecked") public Collection<ClasspathScanRequest> classpathScanRequests() { return classpathScanRequestBuilder() .annotationType(ResourceFiltering.class) .specification(providersSpecification) .specification(resourcesSpecification) .build(); } @Override public Collection<Class<? extends Plugin>> requiredPlugins() { Collection<Class<? extends Plugin>> plugins = new ArrayList<Class<? extends Plugin>>(); plugins.add(ApplicationPlugin.class); plugins.add(WebPlugin.class); return plugins; } public void registerRootResource(Variant variant, Class<? extends RootResource> rootResource) { rootResourceClasses.put(variant, rootResource); } public String getRestPath() { return restPath; } public String getJspPath() { return jspPath; } }
rest/jersey1/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java
/** * Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.rest.internal; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.sun.jersey.spi.container.ResourceFilterFactory; import io.nuun.kernel.api.Plugin; import io.nuun.kernel.api.plugin.InitState; import io.nuun.kernel.api.plugin.PluginException; import io.nuun.kernel.api.plugin.context.Context; import io.nuun.kernel.api.plugin.context.InitContext; import io.nuun.kernel.api.plugin.request.ClasspathScanRequest; import io.nuun.kernel.core.AbstractPlugin; import org.apache.commons.configuration.Configuration; import org.kametic.specifications.Specification; import org.seedstack.seed.core.internal.application.ApplicationPlugin; import org.seedstack.seed.core.utils.SeedConfigurationUtils; import org.seedstack.seed.rest.RelRegistry; import org.seedstack.seed.rest.ResourceFiltering; import org.seedstack.seed.rest.internal.exceptionmapper.AuthenticationExceptionMapper; import org.seedstack.seed.rest.internal.exceptionmapper.AuthorizationExceptionMapper; import org.seedstack.seed.rest.internal.exceptionmapper.InternalErrorExceptionMapper; import org.seedstack.seed.rest.internal.exceptionmapper.WebApplicationExceptionMapper; import org.seedstack.seed.rest.internal.hal.RelRegistryImpl; import org.seedstack.seed.rest.internal.jsonhome.JsonHome; import org.seedstack.seed.rest.internal.jsonhome.JsonHomeRootResource; import org.seedstack.seed.rest.internal.jsonhome.Resource; import org.seedstack.seed.rest.spi.RootResource; import org.seedstack.seed.web.internal.WebPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.servlet.ServletContext; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Variant; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; /** * This plugin enables JAX-RS usage in SEED applications. The JAX-RS implementation is Jersey. * * @author [email protected] */ public class RestPlugin extends AbstractPlugin { private static final String REST_PLUGIN_CONFIGURATION_PREFIX = "org.seedstack.seed.rest"; private static final Logger LOGGER = LoggerFactory.getLogger(RestPlugin.class); private final Specification<Class<?>> resourcesSpecification = new JaxRsResourceSpecification(); private final Specification<Class<?>> providersSpecification = new JaxRsProviderSpecification(); private WebPlugin webPlugin; private Configuration restConfiguration; private final Map<Variant, Class<? extends RootResource>> rootResourceClasses = new HashMap<Variant, Class<? extends RootResource>>(); private RelRegistry relRegistry; private JsonHome jsonHome; private ServletContext servletContext; @Override public String name() { return "seed-rest-plugin"; } @Override public InitState init(InitContext initContext) { // Initialize required and dependent plugins collectPlugins(initContext); Map<Specification, Collection<Class<?>>> scannedClassesBySpecification = initContext.scannedTypesBySpecification(); Collection<Class<?>> resourceClasses = scannedClassesBySpecification.get(resourcesSpecification); String restPath = restConfiguration.getString("path", ""); String jspPath = restConfiguration.getString("jsp-path", "/WEB-INF/jsp"); // Scan resource for HAL and JSON-HOME scanResources(restPath, restConfiguration, resourceClasses); // Register JSON-HOME as root resource registerRootResource(new Variant(new MediaType("application", "json"), null, null), JsonHomeRootResource.class); // Skip the rest of the init phase if we are not in a servlet context if (servletContext == null) { LOGGER.info("No servlet context detected, REST support disabled"); return InitState.INITIALIZED; } Set<Class<? extends ResourceFilterFactory>> resourceFilterFactories = scanResourceFilterFactories(initContext); Map<String, String> jerseyParameters = scanJerseyParameters(); webPlugin.registerAdditionalModule( new RestModule( rootResourceClasses, resourceClasses, scannedClassesBySpecification.get(providersSpecification), jerseyParameters, resourceFilterFactories, restPath, jspPath, jsonHome) ); return InitState.INITIALIZED; } @Inject private Injector injector; @Override public void start(Context context) { if (servletContext != null) { SeedContainer seedContainer = injector.getInstance(SeedContainer.class); if (restConfiguration.getBoolean("map-security-exceptions", true)) { seedContainer.registerClass(AuthenticationExceptionMapper.class); seedContainer.registerClass(AuthorizationExceptionMapper.class); } if (restConfiguration.getBoolean("map-all-exceptions", true)) { seedContainer.registerClass(WebApplicationExceptionMapper.class); injector.injectMembers(InternalErrorExceptionMapper.class); seedContainer.registerClass(InternalErrorExceptionMapper.class); } } } private void collectPlugins(InitContext initContext) { restConfiguration = null; webPlugin = null; for (Plugin plugin : initContext.pluginsRequired()) { if (plugin instanceof ApplicationPlugin) { restConfiguration = ((ApplicationPlugin) plugin).getApplication().getConfiguration().subset(RestPlugin.REST_PLUGIN_CONFIGURATION_PREFIX); } else if (plugin instanceof WebPlugin) { webPlugin = (WebPlugin) plugin; } } if (restConfiguration == null) { throw new PluginException("Unable to find SEED application plugin"); } if (webPlugin == null) { throw new PluginException("Unable to find SEED Web plugin"); } } private Collection<Class<?>> scanResources(String restPath, Configuration restConfiguration, Collection<Class<?>> resourceClasses) { String baseRel = restConfiguration.getString("baseRel", ""); String baseParam = restConfiguration.getString("baseParam", ""); ResourceScanner resourceScanner = new ResourceScanner(restPath, baseRel, baseParam) .scan(resourceClasses); Map<String, Resource> resourceMap = resourceScanner.jsonHomeResources(); relRegistry = new RelRegistryImpl(resourceScanner.halLinks()); jsonHome = new JsonHome(resourceMap); return resourceClasses; } private Set<Class<? extends ResourceFilterFactory>> scanResourceFilterFactories(InitContext initContext) { Map<Class<? extends Annotation>, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext.scannedClassesByAnnotationClass(); Collection<Class<?>> resourceFilterFactoryClasses = scannedClassesByAnnotationClass.get(ResourceFiltering.class); Set<Class<? extends ResourceFilterFactory>> resourceFilterFactories = new HashSet<Class<? extends ResourceFilterFactory>>(); if (resourceFilterFactoryClasses != null) { for (Class<?> candidate : resourceFilterFactoryClasses) { if (ResourceFilterFactory.class.isAssignableFrom(candidate)) { resourceFilterFactories.add(candidate.asSubclass(ResourceFilterFactory.class)); } } } return resourceFilterFactories; } private Map<String, String> scanJerseyParameters() { Map<String, String> jerseyParameters = new HashMap<String, String>(); Properties jerseyProperties = SeedConfigurationUtils.buildPropertiesFromConfiguration(restConfiguration, "jersey.property"); for (Object key : jerseyProperties.keySet()) { jerseyParameters.put(key.toString(), jerseyProperties.getProperty(key.toString())); } return jerseyParameters; } @Override public Object nativeUnitModule() { return new AbstractModule() { @Override protected void configure() { bind(RelRegistry.class).toInstance(relRegistry); } }; } @Override public void provideContainerContext(Object containerContext) { if (containerContext != null && ServletContext.class.isAssignableFrom(containerContext.getClass())) { this.servletContext = (ServletContext) containerContext; } } @Override @SuppressWarnings("unchecked") public Collection<ClasspathScanRequest> classpathScanRequests() { return classpathScanRequestBuilder() .annotationType(ResourceFiltering.class) .specification(providersSpecification) .specification(resourcesSpecification) .build(); } @Override public Collection<Class<? extends Plugin>> requiredPlugins() { Collection<Class<? extends Plugin>> plugins = new ArrayList<Class<? extends Plugin>>(); plugins.add(ApplicationPlugin.class); plugins.add(WebPlugin.class); return plugins; } public void registerRootResource(Variant variant, Class<? extends RootResource> rootResource) { rootResourceClasses.put(variant, rootResource); } }
Add access to REST paths from plugin
rest/jersey1/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java
Add access to REST paths from plugin
<ide><path>est/jersey1/src/main/java/org/seedstack/seed/rest/internal/RestPlugin.java <ide> private final Map<Variant, Class<? extends RootResource>> rootResourceClasses = new HashMap<Variant, Class<? extends RootResource>>(); <ide> private RelRegistry relRegistry; <ide> private JsonHome jsonHome; <add> private String restPath; <add> private String jspPath; <ide> <ide> private ServletContext servletContext; <ide> <ide> Map<Specification, Collection<Class<?>>> scannedClassesBySpecification = initContext.scannedTypesBySpecification(); <ide> Collection<Class<?>> resourceClasses = scannedClassesBySpecification.get(resourcesSpecification); <ide> <del> String restPath = restConfiguration.getString("path", ""); <del> String jspPath = restConfiguration.getString("jsp-path", "/WEB-INF/jsp"); <add> restPath = restConfiguration.getString("path", ""); <add> jspPath = restConfiguration.getString("jsp-path", "/WEB-INF/jsp"); <ide> <ide> // Scan resource for HAL and JSON-HOME <ide> scanResources(restPath, restConfiguration, resourceClasses); <ide> public void registerRootResource(Variant variant, Class<? extends RootResource> rootResource) { <ide> rootResourceClasses.put(variant, rootResource); <ide> } <add> <add> public String getRestPath() { <add> return restPath; <add> } <add> <add> public String getJspPath() { <add> return jspPath; <add> } <ide> }
JavaScript
mpl-2.0
62e67b7e97a3b4f6fe681312061de73835a46faa
0
rse/slideshow-forecast,rse/slideshow-forecast
/* ** slideshow-forecast -- Slideshow Duration Forecasting ** Copyright (c) 2014 Ralf S. Engelschall <http://engelschall.com> ** ** This Source Code Form is subject to the terms of the Mozilla Public ** License (MPL), version 2.0. If a copy of the MPL was not distributed ** with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* global require: false */ /* global module: false */ /* global console: false */ /* global process: false */ /* external requirements */ var sprintf = require("sprintfjs") var chalk = require("chalk") /* intermal requirements */ var ssfapi = require("../api") var slideshowCLI = function (myProg, mySpeed, myFocus) { var ssf = new ssfapi(myProg) ssf.start() ssf.forecast(function (FC) { /* helper function for formatting time */ var ppt = function (t) { var S = Math.floor(t % 60); t /= 60 var M = Math.floor(t % 60); t /= 60 var H = Math.floor(t % 24); t /= 24 return sprintf("%02.0f:%02.0f:%02.0f", H, M, S) } /* show results */ var out = "" out += chalk.grey("+------------+---------------------+---------------------+---------------------+") + "\n" out += chalk.grey("|") + chalk.bold("focus/speed:") + chalk.grey("| ") + chalk.bold("fast: ") + chalk.grey("|") + chalk.bold(" normal: ") + chalk.grey("|") + chalk.bold(" slow: ") + chalk.grey("|") + "\n" out += chalk.grey("+------------+---------------------+---------------------+---------------------+") + "\n" Object.keys(FC.T).forEach(function (focus) { out += chalk.grey("|") + chalk.bold(sprintf("%-11s", focus + ":")) + chalk.grey(" |") Object.keys(FC.T[focus]).forEach(function (speed) { var min = ppt(Math.round(FC.T[focus][speed].min)) var exp = ppt(Math.round(FC.T[focus][speed].exp)) var x = " " + exp + " (" + min + ") " if (focus === myFocus && speed === mySpeed) x = chalk.inverse.red(x) out += x + chalk.grey("|") }) out += "\n" }) out += chalk.grey("+------------+---------------------+---------------------+---------------------+") + "\n" out += "(total slides: " + chalk.bold(sprintf("%d", FC.slidesTotal)) + ", tagged slides: " + chalk.bold(sprintf("%d", FC.slidesTagged)) + ", statements: " + chalk.bold(sprintf("%d", FC.slidesStatements)) + ")" if (!chalk.supportsColor) out = chalk.stripColor(out) console.log(out) ssf.end() process.exit(0) }) } module.exports = slideshowCLI
src/cli/cli.js
/* ** slideshow-forecast -- Slideshow Duration Forecasting ** Copyright (c) 2014 Ralf S. Engelschall <http://engelschall.com> ** ** This Source Code Form is subject to the terms of the Mozilla Public ** License (MPL), version 2.0. If a copy of the MPL was not distributed ** with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* global require: false */ /* global module: false */ /* global console: false */ /* global process: false */ /* external requirements */ var sprintf = require("sprintfjs") var chalk = require("chalk") /* intermal requirements */ var ssfapi = require("../api") var slideshowCLI = function (myProg, mySpeed, myFocus) { var ssf = new ssfapi(myProg) ssf.start() ssf.forecast(function (FC) { /* helper function for formatting time */ var ppt = function (t) { var S = Math.floor(t % 60); t /= 60 var M = Math.floor(t % 60); t /= 60 var H = Math.floor(t % 24); t /= 24 return sprintf("%02.0f:%02.0f:%02.0f", H, M, S) } /* show results */ var out = "" out += chalk.grey("+------------+---------------------+---------------------+---------------------+") + "\n" out += chalk.grey("|") + chalk.bold("focus/speed:") + chalk.grey("| ") + chalk.bold("fast: ") + chalk.grey("|") + chalk.bold(" normal: ") + chalk.grey("|") + chalk.bold(" slow: ") + chalk.grey("|") + "\n" out += chalk.grey("+------------+---------------------+---------------------+---------------------+") + "\n" Object.keys(FC.T).forEach(function (focus) { out += chalk.grey("|") + chalk.bold(sprintf("%-11s", focus + ":")) + chalk.grey(" |") Object.keys(FC.T[focus]).forEach(function (speed) { var min = ppt(Math.round(FC.T[focus][speed].min)) var exp = ppt(Math.round(FC.T[focus][speed].exp)) var x = " " + exp + " (" + min + ") " if (focus === myFocus && speed === mySpeed) x = chalk.inverse(x) out += x + chalk.grey("|") }) out += "\n" }) out += chalk.grey("+------------+---------------------+---------------------+---------------------+") + "\n" out += "(total slides: " + chalk.bold(sprintf("%d", FC.slidesTotal)) + ", tagged slides: " + chalk.bold(sprintf("%d", FC.slidesTagged)) + ", statements: " + chalk.bold(sprintf("%d", FC.slidesStatements)) + ")" if (!chalk.supportsColor) out = chalk.stripColor(out) console.log(out) ssf.end() process.exit(0) }) } module.exports = slideshowCLI
use red also on CLI
src/cli/cli.js
use red also on CLI
<ide><path>rc/cli/cli.js <ide> var exp = ppt(Math.round(FC.T[focus][speed].exp)) <ide> var x = " " + exp + " (" + min + ") " <ide> if (focus === myFocus && speed === mySpeed) <del> x = chalk.inverse(x) <add> x = chalk.inverse.red(x) <ide> out += x + chalk.grey("|") <ide> }) <ide> out += "\n"
Java
apache-2.0
fe3b2da761b919f6a6a69be700216ad1b1162109
0
Teradata/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo
package com.thinkbiganalytics.integration.domaintype; /*- * #%L * kylo-service-app * %% * Copyright (C) 2017 - 2018 ThinkBig Analytics * %% * 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% */ import com.thinkbiganalytics.discovery.model.DefaultField; import com.thinkbiganalytics.discovery.model.DefaultTag; import com.thinkbiganalytics.discovery.schema.Field; import com.thinkbiganalytics.discovery.schema.Tag; import com.thinkbiganalytics.feedmgr.rest.model.DomainType; import com.thinkbiganalytics.integration.IntegrationTestBase; import com.thinkbiganalytics.metadata.rest.model.data.JdbcDatasource; import com.thinkbiganalytics.policy.rest.model.FieldPolicy; import com.thinkbiganalytics.policy.rest.model.FieldStandardizationRule; import com.thinkbiganalytics.policy.rest.model.FieldValidationRule; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static org.junit.Assert.assertEquals; /** * Creates and updates a data source */ public class DomainTypeIT extends IntegrationTestBase { @Test public void testCreateAndUpdateDatasource() { FieldStandardizationRule toUpperCase = new FieldStandardizationRule(); FieldValidationRule email = new FieldValidationRule(); toUpperCase.setName("Uppercase"); toUpperCase.setDisplayName("Uppercase"); toUpperCase.setDescription("Convert string to uppercase"); toUpperCase.setObjectClassType("com.thinkbiganalytics.policy.standardization.UppercaseStandardizer"); toUpperCase.setObjectShortClassType("UppercaseStandardizer"); email.setName("email"); email.setDisplayName("Email"); email.setDescription("Valid email address"); email.setObjectClassType("com.thinkbiganalytics.policy.validation.EmailValidator"); email.setObjectShortClassType("EmailValidator"); DomainType[] initialDomainTypes = getDomainTypes(); //create new domain type DomainType dt = new DomainType(); dt.setTitle("Domain Type 1"); dt.setDescription("domain type created by integration tests"); DomainType response = createDomainType(dt); assertEquals(dt.getTitle(), response.getTitle()); assertEquals(dt.getDescription(), response.getDescription()); assertEquals(null, response.getIcon()); assertEquals(null, response.getIconColor()); //assert new domain type was added DomainType[] currentDomainTypes = getDomainTypes(); assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); //update existing domain type dt = getDomainType(response.getId()); dt.setTitle("Domain Type 1 with updated title"); dt.setDescription("domain type description updated by integration tests"); dt.setIcon("stars"); dt.setIconColor("green"); DefaultField field = new DefaultField(); Tag tag1 = new DefaultTag("tag1"); Tag tag2 = new DefaultTag("tag2"); field.setTags(Arrays.asList(tag1, tag2)); field.setName("field-name"); field.setDerivedDataType("decimal"); field.setPrecisionScale("9, 3"); dt.setField(field); dt.setFieldNamePattern("field-name-pattern"); dt.setFieldPolicy(newPolicyBuilder(null).withStandardisation(toUpperCase).withValidation(email).toPolicy()); dt.setRegexPattern("regex-pattern"); DomainType updated = createDomainType(dt); assertEquals(dt.getTitle(), updated.getTitle()); assertEquals(dt.getDescription(), updated.getDescription()); assertEquals("stars", updated.getIcon()); assertEquals("green", updated.getIconColor()); Field updatedField = updated.getField(); assertEquals(field.getName(), updatedField.getName()); assertEquals(field.getDerivedDataType(), updatedField.getDerivedDataType()); assertEquals(field.getPrecisionScale(), updatedField.getPrecisionScale()); assertEquals(field.getTags().size(), updatedField.getTags().size()); assertEquals(tag1.getName(), updatedField.getTags().get(0).getName()); assertEquals(tag2.getName(), updatedField.getTags().get(1).getName()); assertEquals(dt.getFieldNamePattern(), updated.getFieldNamePattern()); assertEquals(dt.getRegexPattern(), updated.getRegexPattern()); FieldStandardizationRule updatedStandardisation = updated.getFieldPolicy().getStandardization().get(0); assertEquals(toUpperCase.getName(), updatedStandardisation.getName()); assertEquals(toUpperCase.getObjectShortClassType(), updatedStandardisation.getObjectShortClassType()); FieldValidationRule updatedValidation = updated.getFieldPolicy().getValidation().get(0); assertEquals(email.getName(), updatedValidation.getName()); assertEquals(email.getObjectShortClassType(), updatedValidation.getObjectShortClassType()); //assert domain type was updated, rather than added currentDomainTypes = getDomainTypes(); assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); //delete domain type deleteDomainType(dt.getId()); currentDomainTypes = getDomainTypes(); assertEquals(initialDomainTypes.length , currentDomainTypes.length); //assert domain type was removed getDomainTypeExpectingStatus(dt.getId(), HTTP_NOT_FOUND); } }
services/service-app/src/test/java/com/thinkbiganalytics/integration/domaintype/DomainTypeIT.java
package com.thinkbiganalytics.integration.domaintype; /*- * #%L * kylo-service-app * %% * Copyright (C) 2017 - 2018 ThinkBig Analytics * %% * 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% */ import com.thinkbiganalytics.feedmgr.rest.model.DomainType; import com.thinkbiganalytics.integration.IntegrationTestBase; import com.thinkbiganalytics.metadata.rest.model.data.JdbcDatasource; import org.junit.Assert; import org.junit.Test; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; /** * Creates and updates a data source */ public class DomainTypeIT extends IntegrationTestBase { @Test public void testCreateAndUpdateDatasource() { DomainType[] initialDomainTypes = getDomainTypes(); //create new domain type DomainType dt = new DomainType(); dt.setTitle("Domain Type 1"); dt.setDescription("domain type created by integration tests"); DomainType response = createDomainType(dt); Assert.assertEquals(dt.getTitle(), response.getTitle()); Assert.assertEquals(dt.getDescription(), response.getDescription()); Assert.assertEquals(null, response.getIcon()); Assert.assertEquals(null, response.getIconColor()); //assert new domain type was added DomainType[] currentDomainTypes = getDomainTypes(); Assert.assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); //update existing domain type dt = getDomainType(response.getId()); dt.setTitle("Domain Type 1 with updated title"); dt.setDescription("domain type description updated by integration tests"); dt.setIcon("stars"); dt.setIconColor("green"); DomainType updated = createDomainType(dt); Assert.assertEquals(dt.getTitle(), updated.getTitle()); Assert.assertEquals(dt.getDescription(), updated.getDescription()); Assert.assertEquals("stars", updated.getIcon()); Assert.assertEquals("green", updated.getIconColor()); //assert domain type was updated, rather than added currentDomainTypes = getDomainTypes(); Assert.assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); //delete domain type deleteDomainType(dt.getId()); currentDomainTypes = getDomainTypes(); Assert.assertEquals(initialDomainTypes.length , currentDomainTypes.length); //assert domain type was removed getDomainTypeExpectingStatus(dt.getId(), HTTP_NOT_FOUND); } }
KYLO-1140 Integration tests for Domain Types, implementation for complete Domain Type definition
services/service-app/src/test/java/com/thinkbiganalytics/integration/domaintype/DomainTypeIT.java
KYLO-1140 Integration tests for Domain Types, implementation for complete Domain Type definition
<ide><path>ervices/service-app/src/test/java/com/thinkbiganalytics/integration/domaintype/DomainTypeIT.java <ide> * #L% <ide> */ <ide> <add>import com.thinkbiganalytics.discovery.model.DefaultField; <add>import com.thinkbiganalytics.discovery.model.DefaultTag; <add>import com.thinkbiganalytics.discovery.schema.Field; <add>import com.thinkbiganalytics.discovery.schema.Tag; <ide> import com.thinkbiganalytics.feedmgr.rest.model.DomainType; <ide> import com.thinkbiganalytics.integration.IntegrationTestBase; <ide> import com.thinkbiganalytics.metadata.rest.model.data.JdbcDatasource; <add>import com.thinkbiganalytics.policy.rest.model.FieldPolicy; <add>import com.thinkbiganalytics.policy.rest.model.FieldStandardizationRule; <add>import com.thinkbiganalytics.policy.rest.model.FieldValidationRule; <ide> <ide> import org.junit.Assert; <ide> import org.junit.Test; <ide> <add>import java.util.Arrays; <add> <ide> import static java.net.HttpURLConnection.HTTP_NOT_FOUND; <add>import static org.junit.Assert.assertEquals; <ide> <ide> /** <ide> * Creates and updates a data source <ide> <ide> @Test <ide> public void testCreateAndUpdateDatasource() { <add> FieldStandardizationRule toUpperCase = new FieldStandardizationRule(); <add> FieldValidationRule email = new FieldValidationRule(); <add> <add> toUpperCase.setName("Uppercase"); <add> toUpperCase.setDisplayName("Uppercase"); <add> toUpperCase.setDescription("Convert string to uppercase"); <add> toUpperCase.setObjectClassType("com.thinkbiganalytics.policy.standardization.UppercaseStandardizer"); <add> toUpperCase.setObjectShortClassType("UppercaseStandardizer"); <add> <add> email.setName("email"); <add> email.setDisplayName("Email"); <add> email.setDescription("Valid email address"); <add> email.setObjectClassType("com.thinkbiganalytics.policy.validation.EmailValidator"); <add> email.setObjectShortClassType("EmailValidator"); <add> <add> <ide> DomainType[] initialDomainTypes = getDomainTypes(); <ide> <ide> <ide> dt.setDescription("domain type created by integration tests"); <ide> <ide> DomainType response = createDomainType(dt); <del> Assert.assertEquals(dt.getTitle(), response.getTitle()); <del> Assert.assertEquals(dt.getDescription(), response.getDescription()); <del> Assert.assertEquals(null, response.getIcon()); <del> Assert.assertEquals(null, response.getIconColor()); <add> assertEquals(dt.getTitle(), response.getTitle()); <add> assertEquals(dt.getDescription(), response.getDescription()); <add> assertEquals(null, response.getIcon()); <add> assertEquals(null, response.getIconColor()); <ide> <ide> <ide> //assert new domain type was added <ide> DomainType[] currentDomainTypes = getDomainTypes(); <del> Assert.assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); <add> assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); <ide> <ide> <ide> //update existing domain type <ide> dt.setDescription("domain type description updated by integration tests"); <ide> dt.setIcon("stars"); <ide> dt.setIconColor("green"); <add> DefaultField field = new DefaultField(); <add> Tag tag1 = new DefaultTag("tag1"); <add> Tag tag2 = new DefaultTag("tag2"); <add> field.setTags(Arrays.asList(tag1, tag2)); <add> field.setName("field-name"); <add> field.setDerivedDataType("decimal"); <add> field.setPrecisionScale("9, 3"); <add> dt.setField(field); <add> dt.setFieldNamePattern("field-name-pattern"); <add> dt.setFieldPolicy(newPolicyBuilder(null).withStandardisation(toUpperCase).withValidation(email).toPolicy()); <add> dt.setRegexPattern("regex-pattern"); <add> <ide> <ide> DomainType updated = createDomainType(dt); <del> Assert.assertEquals(dt.getTitle(), updated.getTitle()); <del> Assert.assertEquals(dt.getDescription(), updated.getDescription()); <del> Assert.assertEquals("stars", updated.getIcon()); <del> Assert.assertEquals("green", updated.getIconColor()); <add> assertEquals(dt.getTitle(), updated.getTitle()); <add> assertEquals(dt.getDescription(), updated.getDescription()); <add> assertEquals("stars", updated.getIcon()); <add> assertEquals("green", updated.getIconColor()); <add> <add> Field updatedField = updated.getField(); <add> assertEquals(field.getName(), updatedField.getName()); <add> assertEquals(field.getDerivedDataType(), updatedField.getDerivedDataType()); <add> assertEquals(field.getPrecisionScale(), updatedField.getPrecisionScale()); <add> assertEquals(field.getTags().size(), updatedField.getTags().size()); <add> assertEquals(tag1.getName(), updatedField.getTags().get(0).getName()); <add> assertEquals(tag2.getName(), updatedField.getTags().get(1).getName()); <add> assertEquals(dt.getFieldNamePattern(), updated.getFieldNamePattern()); <add> assertEquals(dt.getRegexPattern(), updated.getRegexPattern()); <add> <add> FieldStandardizationRule updatedStandardisation = updated.getFieldPolicy().getStandardization().get(0); <add> assertEquals(toUpperCase.getName(), updatedStandardisation.getName()); <add> assertEquals(toUpperCase.getObjectShortClassType(), updatedStandardisation.getObjectShortClassType()); <add> <add> FieldValidationRule updatedValidation = updated.getFieldPolicy().getValidation().get(0); <add> assertEquals(email.getName(), updatedValidation.getName()); <add> assertEquals(email.getObjectShortClassType(), updatedValidation.getObjectShortClassType()); <ide> <ide> <ide> //assert domain type was updated, rather than added <ide> currentDomainTypes = getDomainTypes(); <del> Assert.assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); <del> <add> assertEquals(initialDomainTypes.length + 1, currentDomainTypes.length); <ide> <ide> //delete domain type <ide> deleteDomainType(dt.getId()); <ide> currentDomainTypes = getDomainTypes(); <del> Assert.assertEquals(initialDomainTypes.length , currentDomainTypes.length); <add> assertEquals(initialDomainTypes.length , currentDomainTypes.length); <ide> <ide> //assert domain type was removed <ide> getDomainTypeExpectingStatus(dt.getId(), HTTP_NOT_FOUND);
Java
lgpl-2.1
de2fd8e903be5e8d7d0c54f582b99994e59d8ae2
0
GNOME/java-atk-wrapper,GNOME/java-atk-wrapper,GNOME/java-atk-wrapper
/* * Java ATK Wrapper for GNOME * Copyright (C) 2009 Sun Microsystems Inc. * * 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.GNOME.Accessibility; import javax.accessibility.*; import java.text.*; import java.awt.Rectangle; import java.awt.Point; import java.lang.ref.WeakReference; public class AtkText { WeakReference<AccessibleContext> _ac; WeakReference<AccessibleText> _acc_text; WeakReference<AccessibleEditableText> _acc_edt_text; public class StringSequence { public String str; public int start_offset, end_offset; public StringSequence (String str, int start_offset, int end_offset) { this.str = str; this.start_offset = start_offset; this.end_offset = end_offset; } } public AtkText (AccessibleContext ac) { super(); this._ac = new WeakReference<AccessibleContext>(ac); this._acc_text = new WeakReference<AccessibleText>(ac.getAccessibleText()); this._acc_edt_text = new WeakReference<AccessibleEditableText>(ac.getAccessibleEditableText()); } public static AtkText createAtkText(AccessibleContext ac){ return AtkUtil.invokeInSwing ( () -> { return new AtkText(ac); }, null); } public static int getRightStart(int start) { if (start < 0) return 0; return start; } public static int getRightEnd(int start, int end, int count) { if (end < -1) return start; else if (end > count || end == -1) return count; else return end; } /* Return string from start, up to, but not including end */ public String get_text (int start, int end) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; return acc_ext_text.getTextRange(rightStart, rightEnd); } StringBuffer buf = new StringBuffer(); for (int i = rightStart; i <= rightEnd-1; i++) { String str = acc_text.getAtIndex(AccessibleText.CHARACTER, i); buf.append(str); } return buf.toString(); }, null); } public char get_character_at_offset (int offset) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return ' '; return AtkUtil.invokeInSwing ( () -> { String str = acc_text.getAtIndex(AccessibleText.CHARACTER, offset); if (str == null || str.length() == 0) return ' '; return str.charAt(0); }, ' '); } public StringSequence get_text_at_offset (int offset,int boundary_type) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; int part = getPartTypeFromBoundary(boundary_type); if (part == -1) return null; AccessibleTextSequence seq = acc_ext_text.getTextSequenceAt(part, offset); if (seq == null) return null; return new StringSequence(seq.text, seq.startIndex, seq.endIndex+1); } else { return private_get_text_at_offset(offset, boundary_type); } }, null); } public StringSequence get_text_before_offset (int offset,int boundary_type) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; int part = getPartTypeFromBoundary(boundary_type); if (part == -1) return null; AccessibleTextSequence seq = acc_ext_text.getTextSequenceBefore(part, offset); if (seq == null) return null; return new StringSequence(seq.text, seq.startIndex, seq.endIndex+1); } else { StringSequence seq = private_get_text_at_offset(offset, boundary_type); if (seq == null) return null; return private_get_text_at_offset(seq.start_offset-1, boundary_type); } }, null); } public StringSequence get_text_after_offset (int offset,int boundary_type) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; int part = getPartTypeFromBoundary(boundary_type); if (part == -1) return null; AccessibleTextSequence seq = acc_ext_text.getTextSequenceAfter(part, offset); if (seq == null) return null; return new StringSequence(seq.text, seq.startIndex, seq.endIndex+1); } else { StringSequence seq = private_get_text_at_offset(offset, boundary_type); if (seq == null) return null; return private_get_text_at_offset(seq.end_offset, boundary_type); } }, null); } public int get_caret_offset () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return 0; return AtkUtil.invokeInSwing ( () -> { return acc_text.getCaretPosition(); }, 0); } public Rectangle get_character_extents (int offset, int coord_type) { AccessibleContext ac = _ac.get(); if (ac == null) return null; AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { Rectangle rect = acc_text.getCharacterBounds(offset); if (rect == null) return null; AccessibleComponent component = ac.getAccessibleComponent(); if (component == null) return null; Point p = AtkComponent.getComponentOrigin(ac, component, coord_type); rect.x += p.x; rect.y += p.y; return rect; }, null); } public int get_character_count () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return 0; return AtkUtil.invokeInSwing ( () -> { return acc_text.getCharCount(); }, 0); } public int get_offset_at_point (int x, int y, int coord_type) { AccessibleContext ac = _ac.get(); if (ac == null) return -1; AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return -1; return AtkUtil.invokeInSwing ( () -> { AccessibleComponent component = ac.getAccessibleComponent(); if (component == null) return -1; Point p = AtkComponent.getComponentOrigin(ac, component, coord_type); return acc_text.getIndexAtPoint(new Point(x-p.x, y-p.y)); }, -1); } public Rectangle get_range_extents (int start, int end, int coord_type) { AccessibleContext ac = _ac.get(); if (ac == null) return null; AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; Rectangle rect = acc_ext_text.getTextBounds(rightStart, rightEnd); if (rect == null) return null; AccessibleComponent component = ac.getAccessibleComponent(); if (component == null) return null; Point p = AtkComponent.getComponentOrigin(ac, component, coord_type); rect.x += p.x; rect.y += p.y; return rect; } return null; }, null); } public int get_n_selections () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return 0; return AtkUtil.invokeInSwing ( () -> { String str = acc_text.getSelectedText(); if (str != null && str.length() > 0) return 1; return 0; }, 0); } public StringSequence get_selection () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { int start = acc_text.getSelectionStart(); int end = acc_text.getSelectionEnd(); String text = acc_text.getSelectedText(); if (text == null) return null; return new StringSequence(text, start, end); }, null); } public boolean add_selection (int start, int end) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return false; AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text == null || get_n_selections() > 0) return false; final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); return set_selection(0, rightStart, rightEnd); }, false); } public boolean remove_selection(int selection_num) { AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text == null || selection_num > 0) return false; acc_edt_text.selectText(0, 0); return true; }, false); } public boolean set_selection (int selection_num, int start, int end) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return false; AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text == null || selection_num > 0) return false; final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); acc_edt_text.selectText(rightStart, rightEnd); return true; }, false); } public boolean set_caret_offset (int offset) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return false; AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text != null) { final int rightOffset = getRightEnd(0, offset, acc_text.getCharCount()); acc_edt_text.selectText(offset, offset); return true; } return false; }, false); } private int getPartTypeFromBoundary (int boundary_type) { switch (boundary_type) { case AtkTextBoundary.CHAR : return AccessibleText.CHARACTER; case AtkTextBoundary.WORD_START : case AtkTextBoundary.WORD_END : return AccessibleText.WORD; case AtkTextBoundary.SENTENCE_START : case AtkTextBoundary.SENTENCE_END : return AccessibleText.SENTENCE; case AtkTextBoundary.LINE_START : case AtkTextBoundary.LINE_END : return AccessibleExtendedText.LINE; default : return -1; } } private int getNextWordStart (int offset, String str) { BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int start = words.following(offset); int end = words.next(); while (end != BreakIterator.DONE) { for (int i = start; i < end; i++) { if (Character.isLetter(str.codePointAt(i))) { return start; } } start = end; end = words.next(); } return BreakIterator.DONE; } private int getNextWordEnd (int offset, String str) { int start = getNextWordStart(offset, str); BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int next = words.following(offset); if (start == next) { return words.following(start); } else { return next; } } private int getPreviousWordStart (int offset, String str) { BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int start = words.preceding(offset); int end = words.next(); while (start != BreakIterator.DONE) { for (int i = start; i < end; i++) { if (Character.isLetter(str.codePointAt(i))) { return start; } } end = start; start = words.preceding(end); } return BreakIterator.DONE; } private int getPreviousWordEnd (int offset, String str) { int start = getPreviousWordStart(offset, str); BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int pre = words.preceding(offset); if (start == pre) { return words.preceding(start); } else { return pre; } } private int getNextSentenceStart (int offset, String str) { BreakIterator sentences = BreakIterator.getSentenceInstance(); sentences.setText(str); int start = sentences.following(offset); return start; } private int getNextSentenceEnd (int offset, String str) { int start = getNextSentenceStart(offset, str); if (start == BreakIterator.DONE) { return str.length(); } int index = start; do { index --; } while (index >= 0 && Character.isWhitespace(str.charAt(index))); index ++; if (index < offset) { start = getNextSentenceStart(start, str); if (start == BreakIterator.DONE) { return str.length(); } index = start; do { index --; } while (index >= 0 && Character.isWhitespace(str.charAt(index))); index ++; } return index; } private int getPreviousSentenceStart (int offset, String str) { BreakIterator sentences = BreakIterator.getSentenceInstance(); sentences.setText(str); int start = sentences.preceding(offset); return start; } private int getPreviousSentenceEnd (int offset, String str) { int start = getPreviousSentenceStart(offset, str); if (start == BreakIterator.DONE) { return 0; } int end = getNextSentenceEnd(start, str); if (offset < end) { start = getPreviousSentenceStart(start, str); if (start == BreakIterator.DONE) { return 0; } end = getNextSentenceEnd(start, str); } return end; } private StringSequence private_get_text_at_offset (int offset, int boundary_type) { int char_count = get_character_count(); if (offset < 0 || offset >= char_count) { return null; } switch (boundary_type) { case AtkTextBoundary.CHAR : { String str = get_text(offset, offset+1); return new StringSequence(str, offset, offset+1); } case AtkTextBoundary.WORD_START : { if (offset == char_count) return new StringSequence("", char_count, char_count); String s = get_text(0, char_count); int start = getPreviousWordStart(offset+1, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextWordStart(offset, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.WORD_END : { if (offset == 0) return new StringSequence("", 0, 0); String s = get_text(0, char_count); int start = getPreviousWordEnd(offset, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextWordEnd(offset-1, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.SENTENCE_START : { if (offset == char_count) return new StringSequence("", char_count, char_count); String s = get_text(0, char_count); int start = getPreviousSentenceStart(offset+1, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextSentenceStart(offset, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.SENTENCE_END : { if (offset == 0) return new StringSequence("", 0, 0); String s = get_text(0, char_count); int start = getPreviousSentenceEnd(offset, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextSentenceEnd(offset-1, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.LINE_START : case AtkTextBoundary.LINE_END : { BreakIterator lines = BreakIterator.getLineInstance(); String s = get_text(0, char_count); lines.setText(s); int start = lines.preceding(offset); if (start == BreakIterator.DONE) { start = 0; } int end = lines.following(offset); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } default : { return null; } } } }
wrapper/org/GNOME/Accessibility/AtkText.java
/* * Java ATK Wrapper for GNOME * Copyright (C) 2009 Sun Microsystems Inc. * * 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.GNOME.Accessibility; import javax.accessibility.*; import java.text.*; import java.awt.Rectangle; import java.awt.Point; import java.lang.ref.WeakReference; public class AtkText { WeakReference<AccessibleContext> _ac; WeakReference<AccessibleText> _acc_text; WeakReference<AccessibleEditableText> _acc_edt_text; public class StringSequence { public String str; public int start_offset, end_offset; public StringSequence (String str, int start_offset, int end_offset) { this.str = str; this.start_offset = start_offset; this.end_offset = end_offset; } } public AtkText (AccessibleContext ac) { super(); this._ac = new WeakReference<AccessibleContext>(ac); this._acc_text = new WeakReference<AccessibleText>(ac.getAccessibleText()); this._acc_edt_text = new WeakReference<AccessibleEditableText>(ac.getAccessibleEditableText()); } public static AtkText createAtkText(AccessibleContext ac){ return AtkUtil.invokeInSwing ( () -> { return new AtkText(ac); }, null); } public static int getRightStart(int start) { if (start < 0) return 0; return start; } public static int getRightEnd(int start, int end, int count) { if (end < -1) return start; else if (end > count || end == -1) return count; else return end; } /* Return string from start, up to, but not including end */ public String get_text (int start, int end) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; return acc_ext_text.getTextRange(rightStart, rightEnd); } StringBuffer buf = new StringBuffer(); for (int i = rightStart; i <= rightEnd-1; i++) { String str = acc_text.getAtIndex(AccessibleText.CHARACTER, i); buf.append(str); } return buf.toString(); }, null); } public char get_character_at_offset (int offset) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return ' '; return AtkUtil.invokeInSwing ( () -> { String str = acc_text.getAtIndex(AccessibleText.CHARACTER, offset); if (str == null || str.length() == 0) return ' '; return str.charAt(0); }, ' '); } public StringSequence get_text_at_offset (int offset,int boundary_type) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; int part = getPartTypeFromBoundary(boundary_type); if (part == -1) return null; AccessibleTextSequence seq = acc_ext_text.getTextSequenceAt(part, offset); if (seq == null) return null; return new StringSequence(seq.text, seq.startIndex, seq.endIndex+1); } else { return private_get_text_at_offset(offset, boundary_type); } }, null); } public StringSequence get_text_before_offset (int offset,int boundary_type) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; int part = getPartTypeFromBoundary(boundary_type); if (part == -1) return null; AccessibleTextSequence seq = acc_ext_text.getTextSequenceBefore(part, offset); if (seq == null) return null; return new StringSequence(seq.text, seq.startIndex, seq.endIndex+1); } else { StringSequence seq = private_get_text_at_offset(offset, boundary_type); if (seq == null) return null; return private_get_text_at_offset(seq.start_offset-1, boundary_type); } }, null); } public StringSequence get_text_after_offset (int offset,int boundary_type) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; int part = getPartTypeFromBoundary(boundary_type); if (part == -1) return null; AccessibleTextSequence seq = acc_ext_text.getTextSequenceAfter(part, offset); if (seq == null) return null; return new StringSequence(seq.text, seq.startIndex, seq.endIndex+1); } else { StringSequence seq = private_get_text_at_offset(offset, boundary_type); if (seq == null) return null; return private_get_text_at_offset(seq.end_offset, boundary_type); } }, null); } public int get_caret_offset () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return 0; return AtkUtil.invokeInSwing ( () -> { return acc_text.getCaretPosition(); }, 0); } public Rectangle get_character_extents (int offset, int coord_type) { AccessibleContext ac = _ac.get(); if (ac == null) return null; AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { Rectangle rect = acc_text.getCharacterBounds(offset); if (rect == null) return null; AccessibleComponent component = ac.getAccessibleComponent(); if (component == null) return null; Point p = AtkComponent.getComponentOrigin(ac, component, coord_type); rect.x += p.x; rect.y += p.y; return rect; }, null); } public int get_character_count () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return 0; return AtkUtil.invokeInSwing ( () -> { return acc_text.getCharCount(); }, 0); } public int get_offset_at_point (int x, int y, int coord_type) { AccessibleContext ac = _ac.get(); if (ac == null) return -1; AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return -1; return AtkUtil.invokeInSwing ( () -> { AccessibleComponent component = ac.getAccessibleComponent(); if (component == null) return -1; Point p = AtkComponent.getComponentOrigin(ac, component, coord_type); return acc_text.getIndexAtPoint(new Point(x-p.x, y-p.y)); }, -1); } public Rectangle get_range_extents (int start, int end, int coord_type) { AccessibleContext ac = _ac.get(); if (ac == null) return null; AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { if (acc_text instanceof AccessibleExtendedText) { final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); AccessibleExtendedText acc_ext_text = (AccessibleExtendedText)acc_text; Rectangle rect = acc_ext_text.getTextBounds(rightStart, rightEnd); if (rect == null) return null; AccessibleComponent component = ac.getAccessibleComponent(); if (component == null) return null; Point p = AtkComponent.getComponentOrigin(ac, component, coord_type); rect.x += p.x; rect.y += p.y; return rect; } return null; }, null); } public int get_n_selections () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return 0; return AtkUtil.invokeInSwing ( () -> { String str = acc_text.getSelectedText(); if (str != null && str.length() > 0) return 1; return 0; }, 0); } public StringSequence get_selection () { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return null; return AtkUtil.invokeInSwing ( () -> { int start = acc_text.getSelectionStart(); int end = acc_text.getSelectionEnd(); String text = acc_text.getSelectedText(); if (text == null) return null; return new StringSequence(text, start, end); }, null); } public boolean add_selection (int start, int end) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return false; AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text == null || get_n_selections() > 0) return false; final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); return set_selection(0, rightStart, rightEnd); }, false); } public boolean remove_selection(int selection_num) { AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text == null || selection_num > 0) return false; acc_edt_text.selectText(0, 0); return true; }, false); } public boolean set_selection (int selection_num, int start, int end) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return false; AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text == null || selection_num > 0) return false; final int rightStart = getRightStart(start);; final int rightEnd = getRightEnd(start, end, acc_text.getCharCount()); acc_edt_text.selectText(rightStart, rightEnd); return true; }, false); } public boolean set_caret_offset (int offset) { AccessibleText acc_text = _acc_text.get(); if (acc_text == null) return false; AccessibleEditableText acc_edt_text = _acc_edt_text.get(); if (acc_edt_text == null) return false; return AtkUtil.invokeInSwing ( () -> { if (acc_edt_text != null) { final int rightOffset = getRightEnd(0, offset, acc_text.getCharCount()); acc_edt_text.selectText(offset, offset); return true; } return false; }, false); } private int getPartTypeFromBoundary (int boundary_type) { switch (boundary_type) { case AtkTextBoundary.CHAR : return AccessibleText.CHARACTER; case AtkTextBoundary.WORD_START : case AtkTextBoundary.WORD_END : return AccessibleText.WORD; case AtkTextBoundary.SENTENCE_START : case AtkTextBoundary.SENTENCE_END : return AccessibleText.SENTENCE; case AtkTextBoundary.LINE_START : case AtkTextBoundary.LINE_END : return AccessibleExtendedText.LINE; default : return -1; } } private int getNextWordStart (int offset, String str) { BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int start = words.following(offset); int end = words.next(); while (end != BreakIterator.DONE) { for (int i = start; i < end; i++) { if (Character.isLetter(str.codePointAt(i))) { return start; } } start = end; end = words.next(); } return BreakIterator.DONE; } private int getNextWordEnd (int offset, String str) { int start = getNextWordStart(offset, str); BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int next = words.following(offset); if (start == next) { return words.following(start); } else { return next; } } private int getPreviousWordStart (int offset, String str) { BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int start = words.preceding(offset); int end = words.next(); while (start != BreakIterator.DONE) { for (int i = start; i < end; i++) { if (Character.isLetter(str.codePointAt(i))) { return start; } } end = start; start = words.preceding(end); } return BreakIterator.DONE; } private int getPreviousWordEnd (int offset, String str) { int start = getPreviousWordStart(offset, str); BreakIterator words = BreakIterator.getWordInstance(); words.setText(str); int pre = words.preceding(offset); if (start == pre) { return words.preceding(start); } else { return pre; } } private int getNextSentenceStart (int offset, String str) { BreakIterator sentences = BreakIterator.getSentenceInstance(); sentences.setText(str); int start = sentences.following(offset); return start; } private int getNextSentenceEnd (int offset, String str) { int start = getNextSentenceStart(offset, str); if (start == BreakIterator.DONE) { return str.length(); } int index = start; do { index --; } while (index >= 0 && Character.isWhitespace(str.charAt(index))); index ++; if (index < offset) { start = getNextSentenceStart(start, str); if (start == BreakIterator.DONE) { return str.length(); } index = start; do { index --; } while (index >= 0 && Character.isWhitespace(str.charAt(index))); index ++; } return index; } private int getPreviousSentenceStart (int offset, String str) { BreakIterator sentences = BreakIterator.getSentenceInstance(); sentences.setText(str); int start = sentences.preceding(offset); return start; } private int getPreviousSentenceEnd (int offset, String str) { int start = getPreviousSentenceStart(offset, str); if (start == BreakIterator.DONE) { return 0; } int end = getNextSentenceEnd(start, str); if (offset < end) { start = getPreviousSentenceStart(start, str); if (start == BreakIterator.DONE) { return 0; } end = getNextSentenceEnd(start, str); } return end; } private StringSequence private_get_text_at_offset (int offset, int boundary_type) { int char_count = get_character_count(); if (offset < 0 || offset >= char_count) { return null; } switch (boundary_type) { case AtkTextBoundary.CHAR : { String str = get_text(offset, offset+1); return new StringSequence(str, offset, offset+1); } case AtkTextBoundary.WORD_START : { if (offset == get_character_count()) return new StringSequence("", 0, 0); String s = get_text(0, get_character_count()); int start = getPreviousWordStart(offset+1, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextWordStart(offset, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.WORD_END : { if (offset == 0) return new StringSequence("", 0, 0); String s = get_text(0, get_character_count()); int start = getPreviousWordEnd(offset, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextWordEnd(offset-1, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.SENTENCE_START : { if (offset == get_character_count()) return new StringSequence("", 0, 0); String s = get_text(0, get_character_count()); int start = getPreviousSentenceStart(offset+1, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextSentenceStart(offset, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.SENTENCE_END : { if (offset == 0) return new StringSequence("", 0, 0); String s = get_text(0, get_character_count()); int start = getPreviousSentenceEnd(offset, s); if (start == BreakIterator.DONE) { start = 0; } int end = getNextSentenceEnd(offset-1, s); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } case AtkTextBoundary.LINE_START : case AtkTextBoundary.LINE_END : { BreakIterator lines = BreakIterator.getLineInstance(); String s = get_text(0, get_character_count()); lines.setText(s); int start = lines.preceding(offset); if (start == BreakIterator.DONE) { start = 0; } int end = lines.following(offset); if (end == BreakIterator.DONE) { end = s.length(); } String str = get_text(start, end); return new StringSequence(str, start, end); } default : { return null; } } } }
Text: reuse char_count
wrapper/org/GNOME/Accessibility/AtkText.java
Text: reuse char_count
<ide><path>rapper/org/GNOME/Accessibility/AtkText.java <ide> } <ide> case AtkTextBoundary.WORD_START : <ide> { <del> if (offset == get_character_count()) <del> return new StringSequence("", 0, 0); <del> <del> String s = get_text(0, get_character_count()); <add> if (offset == char_count) <add> return new StringSequence("", char_count, char_count); <add> <add> String s = get_text(0, char_count); <ide> int start = getPreviousWordStart(offset+1, s); <ide> if (start == BreakIterator.DONE) { <ide> start = 0; <ide> if (offset == 0) <ide> return new StringSequence("", 0, 0); <ide> <del> String s = get_text(0, get_character_count()); <add> String s = get_text(0, char_count); <ide> int start = getPreviousWordEnd(offset, s); <ide> if (start == BreakIterator.DONE) { <ide> start = 0; <ide> } <ide> case AtkTextBoundary.SENTENCE_START : <ide> { <del> if (offset == get_character_count()) <del> return new StringSequence("", 0, 0); <del> <del> String s = get_text(0, get_character_count()); <add> if (offset == char_count) <add> return new StringSequence("", char_count, char_count); <add> <add> String s = get_text(0, char_count); <ide> int start = getPreviousSentenceStart(offset+1, s); <ide> if (start == BreakIterator.DONE) { <ide> start = 0; <ide> if (offset == 0) <ide> return new StringSequence("", 0, 0); <ide> <del> String s = get_text(0, get_character_count()); <add> String s = get_text(0, char_count); <ide> int start = getPreviousSentenceEnd(offset, s); <ide> if (start == BreakIterator.DONE) { <ide> start = 0; <ide> case AtkTextBoundary.LINE_END : <ide> { <ide> BreakIterator lines = BreakIterator.getLineInstance(); <del> String s = get_text(0, get_character_count()); <add> String s = get_text(0, char_count); <ide> lines.setText(s); <ide> <ide> int start = lines.preceding(offset);
Java
mit
495ba85bff0e614a9c5ff04ce47a5e5ff269e6b7
0
delight-im/Android-AdvancedWebView
package im.delight.android.webview; /* * Android-AdvancedWebView (https://github.com/delight-im/Android-AdvancedWebView) * Copyright (c) delight.im (https://www.delight.im/) * Licensed under the MIT License (https://opensource.org/licenses/MIT) */ import android.view.ViewGroup; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.os.Environment; import android.webkit.CookieManager; import java.util.Arrays; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import java.util.HashMap; import android.net.http.SslError; import android.view.InputEvent; import android.view.KeyEvent; import android.webkit.ClientCertRequest; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; import android.webkit.URLUtil; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.os.Message; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions.Callback; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.PermissionRequest; import android.webkit.WebStorage.QuotaUpdater; import android.app.Fragment; import android.util.Base64; import android.os.Build; import android.webkit.DownloadListener; import android.graphics.Bitmap; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebViewClient; import android.webkit.WebSettings; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; import java.util.MissingResourceException; import java.util.Locale; import java.util.LinkedList; import java.util.Collection; import java.util.List; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.util.Map; /** Advanced WebView component for Android that works as intended out of the box */ @SuppressWarnings("deprecation") public class AdvancedWebView extends WebView { public interface Listener { void onPageStarted(String url, Bitmap favicon); void onPageFinished(String url); void onPageError(int errorCode, String description, String failingUrl); void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent); void onExternalPageRequest(String url); } public static final String PACKAGE_NAME_DOWNLOAD_MANAGER = "com.android.providers.downloads"; protected static final int REQUEST_CODE_FILE_PICKER = 51426; protected static final String DATABASES_SUB_FOLDER = "/databases"; protected static final String LANGUAGE_DEFAULT_ISO3 = "eng"; protected static final String CHARSET_DEFAULT = "UTF-8"; /** Alternative browsers that have their own rendering engine and *may* be installed on this device */ protected static final String[] ALTERNATIVE_BROWSERS = new String[] { "org.mozilla.firefox", "com.android.chrome", "com.opera.browser", "org.mozilla.firefox_beta", "com.chrome.beta", "com.opera.browser.beta" }; protected WeakReference<Activity> mActivity; protected WeakReference<Fragment> mFragment; protected Listener mListener; protected final List<String> mPermittedHostnames = new LinkedList<String>(); /** File upload callback for platform versions prior to Android 5.0 */ protected ValueCallback<Uri> mFileUploadCallbackFirst; /** File upload callback for Android 5.0+ */ protected ValueCallback<Uri[]> mFileUploadCallbackSecond; protected long mLastError; protected String mLanguageIso3; protected int mRequestCodeFilePicker = REQUEST_CODE_FILE_PICKER; protected WebViewClient mCustomWebViewClient; protected WebChromeClient mCustomWebChromeClient; protected boolean mGeolocationEnabled; protected String mUploadableFileTypes = "*/*"; protected final Map<String, String> mHttpHeaders = new HashMap<String, String>(); public AdvancedWebView(Context context) { super(context); init(context); } public AdvancedWebView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public AdvancedWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public void setListener(final Activity activity, final Listener listener) { setListener(activity, listener, REQUEST_CODE_FILE_PICKER); } public void setListener(final Activity activity, final Listener listener, final int requestCodeFilePicker) { if (activity != null) { mActivity = new WeakReference<Activity>(activity); } else { mActivity = null; } setListener(listener, requestCodeFilePicker); } public void setListener(final Fragment fragment, final Listener listener) { setListener(fragment, listener, REQUEST_CODE_FILE_PICKER); } public void setListener(final Fragment fragment, final Listener listener, final int requestCodeFilePicker) { if (fragment != null) { mFragment = new WeakReference<Fragment>(fragment); } else { mFragment = null; } setListener(listener, requestCodeFilePicker); } protected void setListener(final Listener listener, final int requestCodeFilePicker) { mListener = listener; mRequestCodeFilePicker = requestCodeFilePicker; } @Override public void setWebViewClient(final WebViewClient client) { mCustomWebViewClient = client; } @Override public void setWebChromeClient(final WebChromeClient client) { mCustomWebChromeClient = client; } @SuppressLint("SetJavaScriptEnabled") public void setGeolocationEnabled(final boolean enabled) { if (enabled) { getSettings().setJavaScriptEnabled(true); getSettings().setGeolocationEnabled(true); setGeolocationDatabasePath(); } mGeolocationEnabled = enabled; } @SuppressLint("NewApi") protected void setGeolocationDatabasePath() { final Activity activity; if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11 && mFragment.get().getActivity() != null) { activity = mFragment.get().getActivity(); } else if (mActivity != null && mActivity.get() != null) { activity = mActivity.get(); } else { return; } getSettings().setGeolocationDatabasePath(activity.getFilesDir().getPath()); } public void setUploadableFileTypes(final String mimeType) { mUploadableFileTypes = mimeType; } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load */ public void loadHtml(final String html) { loadHtml(html, null); } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load * @param baseUrl the URL to use as the page's base URL */ public void loadHtml(final String html, final String baseUrl) { loadHtml(html, baseUrl, null); } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load * @param baseUrl the URL to use as the page's base URL * @param historyUrl the URL to use for the page's history entry */ public void loadHtml(final String html, final String baseUrl, final String historyUrl) { loadHtml(html, baseUrl, historyUrl, "utf-8"); } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load * @param baseUrl the URL to use as the page's base URL * @param historyUrl the URL to use for the page's history entry * @param encoding the encoding or charset of the HTML source text */ public void loadHtml(final String html, final String baseUrl, final String historyUrl, final String encoding) { loadDataWithBaseURL(baseUrl, html, "text/html", encoding, historyUrl); } @SuppressLint("NewApi") @SuppressWarnings("all") public void onResume() { if (Build.VERSION.SDK_INT >= 11) { super.onResume(); } resumeTimers(); } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPause() { pauseTimers(); if (Build.VERSION.SDK_INT >= 11) { super.onPause(); } } public void onDestroy() { // try to remove this view from its parent first try { ((ViewGroup) getParent()).removeView(this); } catch (Exception ignored) { } // then try to remove all child views from this view try { removeAllViews(); } catch (Exception ignored) { } // and finally destroy this view destroy(); } public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode == mRequestCodeFilePicker) { if (resultCode == Activity.RESULT_OK) { if (intent != null) { if (mFileUploadCallbackFirst != null) { mFileUploadCallbackFirst.onReceiveValue(intent.getData()); mFileUploadCallbackFirst = null; } else if (mFileUploadCallbackSecond != null) { Uri[] dataUris = null; try { if (intent.getDataString() != null) { dataUris = new Uri[] { Uri.parse(intent.getDataString()) }; } else { if (Build.VERSION.SDK_INT >= 16) { if (intent.getClipData() != null) { final int numSelectedFiles = intent.getClipData().getItemCount(); dataUris = new Uri[numSelectedFiles]; for (int i = 0; i < numSelectedFiles; i++) { dataUris[i] = intent.getClipData().getItemAt(i).getUri(); } } } } } catch (Exception ignored) { } mFileUploadCallbackSecond.onReceiveValue(dataUris); mFileUploadCallbackSecond = null; } } } else { if (mFileUploadCallbackFirst != null) { mFileUploadCallbackFirst.onReceiveValue(null); mFileUploadCallbackFirst = null; } else if (mFileUploadCallbackSecond != null) { mFileUploadCallbackSecond.onReceiveValue(null); mFileUploadCallbackSecond = null; } } } } /** * Adds an additional HTTP header that will be sent along with every HTTP `GET` request * * This does only affect the main requests, not the requests to included resources (e.g. images) * * If you later want to delete an HTTP header that was previously added this way, call `removeHttpHeader()` * * The `WebView` implementation may in some cases overwrite headers that you set or unset * * @param name the name of the HTTP header to add * @param value the value of the HTTP header to send */ public void addHttpHeader(final String name, final String value) { mHttpHeaders.put(name, value); } /** * Removes one of the HTTP headers that have previously been added via `addHttpHeader()` * * If you want to unset a pre-defined header, set it to an empty string with `addHttpHeader()` instead * * The `WebView` implementation may in some cases overwrite headers that you set or unset * * @param name the name of the HTTP header to remove */ public void removeHttpHeader(final String name) { mHttpHeaders.remove(name); } public void addPermittedHostname(String hostname) { mPermittedHostnames.add(hostname); } public void addPermittedHostnames(Collection<? extends String> collection) { mPermittedHostnames.addAll(collection); } public List<String> getPermittedHostnames() { return mPermittedHostnames; } public void removePermittedHostname(String hostname) { mPermittedHostnames.remove(hostname); } public void clearPermittedHostnames() { mPermittedHostnames.clear(); } public boolean onBackPressed() { if (canGoBack()) { goBack(); return false; } else { return true; } } @SuppressLint("NewApi") protected static void setAllowAccessFromFileUrls(final WebSettings webSettings, final boolean allowed) { if (Build.VERSION.SDK_INT >= 16) { webSettings.setAllowFileAccessFromFileURLs(allowed); webSettings.setAllowUniversalAccessFromFileURLs(allowed); } } @SuppressWarnings("static-method") public void setCookiesEnabled(final boolean enabled) { CookieManager.getInstance().setAcceptCookie(enabled); } @SuppressLint("NewApi") public void setThirdPartyCookiesEnabled(final boolean enabled) { if (Build.VERSION.SDK_INT >= 21) { CookieManager.getInstance().setAcceptThirdPartyCookies(this, enabled); } } public void setMixedContentAllowed(final boolean allowed) { setMixedContentAllowed(getSettings(), allowed); } @SuppressWarnings("static-method") @SuppressLint("NewApi") protected void setMixedContentAllowed(final WebSettings webSettings, final boolean allowed) { if (Build.VERSION.SDK_INT >= 21) { webSettings.setMixedContentMode(allowed ? WebSettings.MIXED_CONTENT_ALWAYS_ALLOW : WebSettings.MIXED_CONTENT_NEVER_ALLOW); } } public void setDesktopMode(final boolean enabled) { final WebSettings webSettings = getSettings(); final String newUserAgent; if (enabled) { newUserAgent = webSettings.getUserAgentString().replace("Mobile", "eliboM").replace("Android", "diordnA"); } else { newUserAgent = webSettings.getUserAgentString().replace("eliboM", "Mobile").replace("diordnA", "Android"); } webSettings.setUserAgentString(newUserAgent); webSettings.setUseWideViewPort(enabled); webSettings.setLoadWithOverviewMode(enabled); webSettings.setSupportZoom(enabled); webSettings.setBuiltInZoomControls(enabled); } @SuppressLint({ "SetJavaScriptEnabled" }) protected void init(Context context) { // in IDE's preview mode if (isInEditMode()) { // do not run the code from this method return; } if (context instanceof Activity) { mActivity = new WeakReference<Activity>((Activity) context); } mLanguageIso3 = getLanguageIso3(); setFocusable(true); setFocusableInTouchMode(true); setSaveEnabled(true); final String filesDir = context.getFilesDir().getPath(); final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER; final WebSettings webSettings = getSettings(); webSettings.setAllowFileAccess(false); setAllowAccessFromFileUrls(webSettings, false); webSettings.setBuiltInZoomControls(false); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); if (Build.VERSION.SDK_INT < 18) { webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); } webSettings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT < 19) { webSettings.setDatabasePath(databaseDir); } setMixedContentAllowed(webSettings, true); setThirdPartyCookiesEnabled(true); super.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { if (!hasError()) { if (mListener != null) { mListener.onPageStarted(url, favicon); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageStarted(view, url, favicon); } } @Override public void onPageFinished(WebView view, String url) { if (!hasError()) { if (mListener != null) { mListener.onPageFinished(url); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageFinished(view, url); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { setLastError(); if (mListener != null) { mListener.onPageError(errorCode, description, failingUrl); } if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl); } } @Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { if (!isPermittedUrl(url)) { // if a listener is available if (mListener != null) { // inform the listener about the request mListener.onExternalPageRequest(url); } // cancel the original request return true; } // if there is a user-specified handler available if (mCustomWebViewClient != null) { // if the user-specified handler asks to override the request if (mCustomWebViewClient.shouldOverrideUrlLoading(view, url)) { // cancel the original request return true; } } // route the request through the custom URL loading method view.loadUrl(url); // cancel the original request return true; } @Override public void onLoadResource(WebView view, String url) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onLoadResource(view, url); } else { super.onLoadResource(view, url); } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (Build.VERSION.SDK_INT >= 11) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, url); } else { return super.shouldInterceptRequest(view, url); } } else { return null; } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, request); } else { return super.shouldInterceptRequest(view, request); } } else { return null; } } @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onFormResubmission(view, dontResend, resend); } else { super.onFormResubmission(view, dontResend, resend); } } @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { if (mCustomWebViewClient != null) { mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload); } else { super.doUpdateVisitedHistory(view, url, isReload); } } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedSslError(view, handler, error); } else { super.onReceivedSslError(view, handler, error); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedClientCertRequest(view, request); } else { super.onReceivedClientCertRequest(view, request); } } } @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); } else { super.onReceivedHttpAuthRequest(view, handler, host, realm); } } @Override public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldOverrideKeyEvent(view, event); } else { return super.shouldOverrideKeyEvent(view, event); } } @Override public void onUnhandledKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledKeyEvent(view, event); } else { super.onUnhandledKeyEvent(view, event); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onUnhandledInputEvent(WebView view, InputEvent event) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledInputEvent(view, event); } else { super.onUnhandledInputEvent(view, event); } } } @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onScaleChanged(view, oldScale, newScale); } else { super.onScaleChanged(view, oldScale, newScale); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { if (Build.VERSION.SDK_INT >= 12) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args); } else { super.onReceivedLoginRequest(view, realm, account, args); } } } }); super.setWebChromeClient(new WebChromeClient() { // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg) { openFileChooser(uploadMsg, null); } // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method) public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { openFileChooser(uploadMsg, acceptType, null); } // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { openFileInput(uploadMsg, null, false); } // file upload callback (Android 5.0 (API level 21) -- current) (public method) @SuppressWarnings("all") public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { if (Build.VERSION.SDK_INT >= 21) { final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE; openFileInput(null, filePathCallback, allowMultiple); return true; } else { return false; } } @Override public void onProgressChanged(WebView view, int newProgress) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onProgressChanged(view, newProgress); } else { super.onProgressChanged(view, newProgress); } } @Override public void onReceivedTitle(WebView view, String title) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTitle(view, title); } else { super.onReceivedTitle(view, title); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedIcon(view, icon); } else { super.onReceivedIcon(view, icon); } } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed); } else { super.onReceivedTouchIconUrl(view, url, precomposed); } } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, callback); } else { super.onShowCustomView(view, callback); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { if (Build.VERSION.SDK_INT >= 14) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback); } else { super.onShowCustomView(view, requestedOrientation, callback); } } } @Override public void onHideCustomView() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onHideCustomView(); } else { super.onHideCustomView(); } } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } else { return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } } @Override public void onRequestFocus(WebView view) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onRequestFocus(view); } else { super.onRequestFocus(view); } } @Override public void onCloseWindow(WebView window) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onCloseWindow(window); } else { super.onCloseWindow(window); } } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsAlert(view, url, message, result); } else { return super.onJsAlert(view, url, message, result); } } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsConfirm(view, url, message, result); } else { return super.onJsConfirm(view, url, message, result); } } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result); } else { return super.onJsPrompt(view, url, message, defaultValue, result); } } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result); } else { return super.onJsBeforeUnload(view, url, message, result); } } @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { if (mGeolocationEnabled) { callback.invoke(origin, true, false); } else { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback); } else { super.onGeolocationPermissionsShowPrompt(origin, callback); } } } @Override public void onGeolocationPermissionsHidePrompt() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsHidePrompt(); } else { super.onGeolocationPermissionsHidePrompt(); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequest(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequest(request); } else { super.onPermissionRequest(request); } } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequestCanceled(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequestCanceled(request); } else { super.onPermissionRequestCanceled(request); } } } @Override public boolean onJsTimeout() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsTimeout(); } else { return super.onJsTimeout(); } } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID); } else { super.onConsoleMessage(message, lineNumber, sourceID); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onConsoleMessage(consoleMessage); } else { return super.onConsoleMessage(consoleMessage); } } @Override public Bitmap getDefaultVideoPoster() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getDefaultVideoPoster(); } else { return super.getDefaultVideoPoster(); } } @Override public View getVideoLoadingProgressView() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getVideoLoadingProgressView(); } else { return super.getVideoLoadingProgressView(); } } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.getVisitedHistory(callback); } else { super.getVisitedHistory(callback); } } @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } else { super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } } @Override public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } else { super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } } }); setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(final String url, final String userAgent, final String contentDisposition, final String mimeType, final long contentLength) { final String suggestedFilename = URLUtil.guessFileName(url, contentDisposition, mimeType); if (mListener != null) { mListener.onDownloadRequested(url, suggestedFilename, mimeType, contentLength, contentDisposition, userAgent); } } }); } @Override public void loadUrl(final String url, Map<String, String> additionalHttpHeaders) { if (additionalHttpHeaders == null) { additionalHttpHeaders = mHttpHeaders; } else if (mHttpHeaders.size() > 0) { additionalHttpHeaders.putAll(mHttpHeaders); } super.loadUrl(url, additionalHttpHeaders); } @Override public void loadUrl(final String url) { if (mHttpHeaders.size() > 0) { super.loadUrl(url, mHttpHeaders); } else { super.loadUrl(url); } } public void loadUrl(String url, final boolean preventCaching) { if (preventCaching) { url = makeUrlUnique(url); } loadUrl(url); } public void loadUrl(String url, final boolean preventCaching, final Map<String,String> additionalHttpHeaders) { if (preventCaching) { url = makeUrlUnique(url); } loadUrl(url, additionalHttpHeaders); } protected static String makeUrlUnique(final String url) { StringBuilder unique = new StringBuilder(); unique.append(url); if (url.contains("?")) { unique.append('&'); } else { if (url.lastIndexOf('/') <= 7) { unique.append('/'); } unique.append('?'); } unique.append(System.currentTimeMillis()); unique.append('='); unique.append(1); return unique.toString(); } public boolean isPermittedUrl(final String url) { // if the permitted hostnames have not been restricted to a specific set if (mPermittedHostnames.size() == 0) { // all hostnames are allowed return true; } final Uri parsedUrl = Uri.parse(url); // get the hostname of the URL that is to be checked final String actualHost = parsedUrl.getHost(); // if the hostname could not be determined, usually because the URL has been invalid if (actualHost == null) { return false; } // if the host contains invalid characters (e.g. a backslash) if (!actualHost.matches("^[a-zA-Z0-9._!~*')(;:&=+$,%\\[\\]-]*$")) { // prevent mismatches between interpretations by `Uri` and `WebView`, e.g. for `http://evil.example.com\.good.example.com/` return false; } // get the user information from the authority part of the URL that is to be checked final String actualUserInformation = parsedUrl.getUserInfo(); // if the user information contains invalid characters (e.g. a backslash) if (actualUserInformation != null && !actualUserInformation.matches("^[a-zA-Z0-9._!~*')(;:&=+$,%-]*$")) { // prevent mismatches between interpretations by `Uri` and `WebView`, e.g. for `http://evil.example.com\@good.example.com/` return false; } // for every hostname in the set of permitted hosts for (String expectedHost : mPermittedHostnames) { // if the two hostnames match or if the actual host is a subdomain of the expected host if (actualHost.equals(expectedHost) || actualHost.endsWith("." + expectedHost)) { // the actual hostname of the URL to be checked is allowed return true; } } // the actual hostname of the URL to be checked is not allowed since there were no matches return false; } /** * @deprecated use `isPermittedUrl` instead */ protected boolean isHostnameAllowed(final String url) { return isPermittedUrl(url); } protected void setLastError() { mLastError = System.currentTimeMillis(); } protected boolean hasError() { return (mLastError + 500) >= System.currentTimeMillis(); } protected static String getLanguageIso3() { try { return Locale.getDefault().getISO3Language().toLowerCase(Locale.US); } catch (MissingResourceException e) { return LANGUAGE_DEFAULT_ISO3; } } /** * Provides localizations for the 25 most widely spoken languages that have a ISO 639-2/T code * * @return the label for the file upload prompts as a string */ protected String getFileUploadPromptLabel() { try { if (mLanguageIso3.equals("zho")) return decodeBase64("6YCJ5oup5LiA5Liq5paH5Lu2"); else if (mLanguageIso3.equals("spa")) return decodeBase64("RWxpamEgdW4gYXJjaGl2bw=="); else if (mLanguageIso3.equals("hin")) return decodeBase64("4KSP4KSVIOCkq+CkvOCkvuCkh+CksiDgpJrgpYHgpKjgpYfgpII="); else if (mLanguageIso3.equals("ben")) return decodeBase64("4KaP4KaV4Kaf4Ka/IOCmq+CmvuCmh+CmsiDgpqjgpr/gprDgp43gpqzgpr7gpprgpqg="); else if (mLanguageIso3.equals("ara")) return decodeBase64("2KfYrtiq2YrYp9ixINmF2YTZgSDZiNin2K3Yrw=="); else if (mLanguageIso3.equals("por")) return decodeBase64("RXNjb2xoYSB1bSBhcnF1aXZv"); else if (mLanguageIso3.equals("rus")) return decodeBase64("0JLRi9Cx0LXRgNC40YLQtSDQvtC00LjQvSDRhNCw0LnQuw=="); else if (mLanguageIso3.equals("jpn")) return decodeBase64("MeODleOCoeOCpOODq+OCkumBuOaKnuOBl+OBpuOBj+OBoOOBleOBhA=="); else if (mLanguageIso3.equals("pan")) return decodeBase64("4KiH4Kmx4KiVIOCoq+CovuCoh+CosiDgqJrgqYHgqKPgqYs="); else if (mLanguageIso3.equals("deu")) return decodeBase64("V8OkaGxlIGVpbmUgRGF0ZWk="); else if (mLanguageIso3.equals("jav")) return decodeBase64("UGlsaWggc2lqaSBiZXJrYXM="); else if (mLanguageIso3.equals("msa")) return decodeBase64("UGlsaWggc2F0dSBmYWls"); else if (mLanguageIso3.equals("tel")) return decodeBase64("4LCS4LCVIOCwq+CxhuCxluCwsuCxjeCwqOCxgSDgsI7gsILgsJrgsYHgsJXgsYvgsILgsKHgsL8="); else if (mLanguageIso3.equals("vie")) return decodeBase64("Q2jhu41uIG3hu5l0IHThuq1wIHRpbg=="); else if (mLanguageIso3.equals("kor")) return decodeBase64("7ZWY64KY7J2YIO2MjOydvOydhCDshKDtg50="); else if (mLanguageIso3.equals("fra")) return decodeBase64("Q2hvaXNpc3NleiB1biBmaWNoaWVy"); else if (mLanguageIso3.equals("mar")) return decodeBase64("4KSr4KS+4KSH4KSyIOCkqOCkv+CkteCkoeCkvg=="); else if (mLanguageIso3.equals("tam")) return decodeBase64("4K6S4K6w4K+BIOCuleCvh+CuvuCuquCvjeCuquCviCDgrqTgr4fgrrDgr43grrXgr4E="); else if (mLanguageIso3.equals("urd")) return decodeBase64("2KfbjNqpINmB2KfYptmEINmF24zauiDYs9uSINin2YbYqtiu2KfYqCDaqdix24zaug=="); else if (mLanguageIso3.equals("fas")) return decodeBase64("2LHYpyDYp9mG2KrYrtin2Kgg2qnZhtuM2K8g24zaqSDZgdin24zZhA=="); else if (mLanguageIso3.equals("tur")) return decodeBase64("QmlyIGRvc3lhIHNlw6dpbg=="); else if (mLanguageIso3.equals("ita")) return decodeBase64("U2NlZ2xpIHVuIGZpbGU="); else if (mLanguageIso3.equals("tha")) return decodeBase64("4LmA4Lil4Li34Lit4LiB4LmE4Lif4Lil4LmM4Lir4LiZ4Li24LmI4LiH"); else if (mLanguageIso3.equals("guj")) return decodeBase64("4KqP4KqVIOCqq+CqvuCqh+CqsuCqqOCrhyDgqqrgqrjgqoLgqqY="); } catch (Exception ignored) { } // return English translation by default return "Choose a file"; } protected static String decodeBase64(final String base64) throws IllegalArgumentException, UnsupportedEncodingException { final byte[] bytes = Base64.decode(base64, Base64.DEFAULT); return new String(bytes, CHARSET_DEFAULT); } @SuppressLint("NewApi") protected void openFileInput(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond, final boolean allowMultiple) { if (mFileUploadCallbackFirst != null) { mFileUploadCallbackFirst.onReceiveValue(null); } mFileUploadCallbackFirst = fileUploadCallbackFirst; if (mFileUploadCallbackSecond != null) { mFileUploadCallbackSecond.onReceiveValue(null); } mFileUploadCallbackSecond = fileUploadCallbackSecond; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); if (allowMultiple) { if (Build.VERSION.SDK_INT >= 18) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } i.setType(mUploadableFileTypes); if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11) { mFragment.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker); } else if (mActivity != null && mActivity.get() != null) { mActivity.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker); } } /** * Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) * * @return whether file uploads can be used */ public static boolean isFileUploadAvailable() { return isFileUploadAvailable(false); } /** * Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) * * On Android 4.4.3/4.4.4, file uploads may be possible but will come with a wrong MIME type * * @param needsCorrectMimeType whether a correct MIME type is required for file uploads or `application/octet-stream` is acceptable * @return whether file uploads can be used */ public static boolean isFileUploadAvailable(final boolean needsCorrectMimeType) { if (Build.VERSION.SDK_INT == 19) { final String platformVersion = (Build.VERSION.RELEASE == null) ? "" : Build.VERSION.RELEASE; return !needsCorrectMimeType && (platformVersion.startsWith("4.4.3") || platformVersion.startsWith("4.4.4")); } else { return true; } } /** * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage * * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE` * * Only supported on API level 9 (Android 2.3) and above * * @param context a valid `Context` reference * @param fromUrl the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)` * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg` * @return whether the download has been successfully handled or not * @throws IllegalStateException if the storage or the target directory could not be found or accessed */ @SuppressLint("NewApi") public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) { if (Build.VERSION.SDK_INT < 9) { throw new RuntimeException("Method requires API level 9 or above"); } final Request request = new Request(Uri.parse(fromUrl)); if (Build.VERSION.SDK_INT >= 11) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename); final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); try { try { dm.enqueue(request); } catch (SecurityException e) { if (Build.VERSION.SDK_INT >= 11) { request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); } dm.enqueue(request); } return true; } // if the download manager app has been disabled on the device catch (IllegalArgumentException e) { // show the settings screen where the user can enable the download manager app again openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER); return false; } } @SuppressLint("NewApi") private static boolean openAppSettings(final Context context, final String packageName) { if (Build.VERSION.SDK_INT < 9) { throw new RuntimeException("Method requires API level 9 or above"); } try { final Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + packageName)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return true; } catch (Exception e) { return false; } } /** Wrapper for methods related to alternative browsers that have their own rendering engines */ public static class Browsers { /** Package name of an alternative browser that is installed on this device */ private static String mAlternativePackage; /** * Returns whether there is an alternative browser with its own rendering engine currently installed * * @param context a valid `Context` reference * @return whether there is an alternative browser or not */ public static boolean hasAlternative(final Context context) { return getAlternative(context) != null; } /** * Returns the package name of an alternative browser with its own rendering engine or `null` * * @param context a valid `Context` reference * @return the package name or `null` */ public static String getAlternative(final Context context) { if (mAlternativePackage != null) { return mAlternativePackage; } final List<String> alternativeBrowsers = Arrays.asList(ALTERNATIVE_BROWSERS); final List<ApplicationInfo> apps = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo app : apps) { if (!app.enabled) { continue; } if (alternativeBrowsers.contains(app.packageName)) { mAlternativePackage = app.packageName; return app.packageName; } } return null; } /** * Opens the given URL in an alternative browser * * @param context a valid `Activity` reference * @param url the URL to open */ public static void openUrl(final Activity context, final String url) { openUrl(context, url, false); } /** * Opens the given URL in an alternative browser * * @param context a valid `Activity` reference * @param url the URL to open * @param withoutTransition whether to switch to the browser `Activity` without a transition */ public static void openUrl(final Activity context, final String url, final boolean withoutTransition) { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setPackage(getAlternative(context)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); if (withoutTransition) { context.overridePendingTransition(0, 0); } } } }
Source/library/src/main/java/im/delight/android/webview/AdvancedWebView.java
package im.delight.android.webview; /* * Android-AdvancedWebView (https://github.com/delight-im/Android-AdvancedWebView) * Copyright (c) delight.im (https://www.delight.im/) * Licensed under the MIT License (https://opensource.org/licenses/MIT) */ import android.view.ViewGroup; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.os.Environment; import android.webkit.CookieManager; import java.util.Arrays; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import java.util.HashMap; import android.net.http.SslError; import android.view.InputEvent; import android.view.KeyEvent; import android.webkit.ClientCertRequest; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; import android.webkit.URLUtil; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.os.Message; import android.view.View; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions.Callback; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.PermissionRequest; import android.webkit.WebStorage.QuotaUpdater; import android.app.Fragment; import android.util.Base64; import android.os.Build; import android.webkit.DownloadListener; import android.graphics.Bitmap; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebViewClient; import android.webkit.WebSettings; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; import java.util.MissingResourceException; import java.util.Locale; import java.util.LinkedList; import java.util.Collection; import java.util.List; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.util.Map; /** Advanced WebView component for Android that works as intended out of the box */ @SuppressWarnings("deprecation") public class AdvancedWebView extends WebView { public interface Listener { void onPageStarted(String url, Bitmap favicon); void onPageFinished(String url); void onPageError(int errorCode, String description, String failingUrl); void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent); void onExternalPageRequest(String url); } public static final String PACKAGE_NAME_DOWNLOAD_MANAGER = "com.android.providers.downloads"; protected static final int REQUEST_CODE_FILE_PICKER = 51426; protected static final String DATABASES_SUB_FOLDER = "/databases"; protected static final String LANGUAGE_DEFAULT_ISO3 = "eng"; protected static final String CHARSET_DEFAULT = "UTF-8"; /** Alternative browsers that have their own rendering engine and *may* be installed on this device */ protected static final String[] ALTERNATIVE_BROWSERS = new String[] { "org.mozilla.firefox", "com.android.chrome", "com.opera.browser", "org.mozilla.firefox_beta", "com.chrome.beta", "com.opera.browser.beta" }; protected WeakReference<Activity> mActivity; protected WeakReference<Fragment> mFragment; protected Listener mListener; protected final List<String> mPermittedHostnames = new LinkedList<String>(); /** File upload callback for platform versions prior to Android 5.0 */ protected ValueCallback<Uri> mFileUploadCallbackFirst; /** File upload callback for Android 5.0+ */ protected ValueCallback<Uri[]> mFileUploadCallbackSecond; protected long mLastError; protected String mLanguageIso3; protected int mRequestCodeFilePicker = REQUEST_CODE_FILE_PICKER; protected WebViewClient mCustomWebViewClient; protected WebChromeClient mCustomWebChromeClient; protected boolean mGeolocationEnabled; protected String mUploadableFileTypes = "*/*"; protected final Map<String, String> mHttpHeaders = new HashMap<String, String>(); public AdvancedWebView(Context context) { super(context); init(context); } public AdvancedWebView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public AdvancedWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } public void setListener(final Activity activity, final Listener listener) { setListener(activity, listener, REQUEST_CODE_FILE_PICKER); } public void setListener(final Activity activity, final Listener listener, final int requestCodeFilePicker) { if (activity != null) { mActivity = new WeakReference<Activity>(activity); } else { mActivity = null; } setListener(listener, requestCodeFilePicker); } public void setListener(final Fragment fragment, final Listener listener) { setListener(fragment, listener, REQUEST_CODE_FILE_PICKER); } public void setListener(final Fragment fragment, final Listener listener, final int requestCodeFilePicker) { if (fragment != null) { mFragment = new WeakReference<Fragment>(fragment); } else { mFragment = null; } setListener(listener, requestCodeFilePicker); } protected void setListener(final Listener listener, final int requestCodeFilePicker) { mListener = listener; mRequestCodeFilePicker = requestCodeFilePicker; } @Override public void setWebViewClient(final WebViewClient client) { mCustomWebViewClient = client; } @Override public void setWebChromeClient(final WebChromeClient client) { mCustomWebChromeClient = client; } @SuppressLint("SetJavaScriptEnabled") public void setGeolocationEnabled(final boolean enabled) { if (enabled) { getSettings().setJavaScriptEnabled(true); getSettings().setGeolocationEnabled(true); setGeolocationDatabasePath(); } mGeolocationEnabled = enabled; } @SuppressLint("NewApi") protected void setGeolocationDatabasePath() { final Activity activity; if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11 && mFragment.get().getActivity() != null) { activity = mFragment.get().getActivity(); } else if (mActivity != null && mActivity.get() != null) { activity = mActivity.get(); } else { return; } getSettings().setGeolocationDatabasePath(activity.getFilesDir().getPath()); } public void setUploadableFileTypes(final String mimeType) { mUploadableFileTypes = mimeType; } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load */ public void loadHtml(final String html) { loadHtml(html, null); } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load * @param baseUrl the URL to use as the page's base URL */ public void loadHtml(final String html, final String baseUrl) { loadHtml(html, baseUrl, null); } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load * @param baseUrl the URL to use as the page's base URL * @param historyUrl the URL to use for the page's history entry */ public void loadHtml(final String html, final String baseUrl, final String historyUrl) { loadHtml(html, baseUrl, historyUrl, "utf-8"); } /** * Loads and displays the provided HTML source text * * @param html the HTML source text to load * @param baseUrl the URL to use as the page's base URL * @param historyUrl the URL to use for the page's history entry * @param encoding the encoding or charset of the HTML source text */ public void loadHtml(final String html, final String baseUrl, final String historyUrl, final String encoding) { loadDataWithBaseURL(baseUrl, html, "text/html", encoding, historyUrl); } @SuppressLint("NewApi") @SuppressWarnings("all") public void onResume() { if (Build.VERSION.SDK_INT >= 11) { super.onResume(); } resumeTimers(); } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPause() { pauseTimers(); if (Build.VERSION.SDK_INT >= 11) { super.onPause(); } } public void onDestroy() { // try to remove this view from its parent first try { ((ViewGroup) getParent()).removeView(this); } catch (Exception ignored) { } // then try to remove all child views from this view try { removeAllViews(); } catch (Exception ignored) { } // and finally destroy this view destroy(); } public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode == mRequestCodeFilePicker) { if (resultCode == Activity.RESULT_OK) { if (intent != null) { if (mFileUploadCallbackFirst != null) { mFileUploadCallbackFirst.onReceiveValue(intent.getData()); mFileUploadCallbackFirst = null; } else if (mFileUploadCallbackSecond != null) { Uri[] dataUris = null; try { if (intent.getDataString() != null) { dataUris = new Uri[] { Uri.parse(intent.getDataString()) }; } else { if (Build.VERSION.SDK_INT >= 16) { if (intent.getClipData() != null) { final int numSelectedFiles = intent.getClipData().getItemCount(); dataUris = new Uri[numSelectedFiles]; for (int i = 0; i < numSelectedFiles; i++) { dataUris[i] = intent.getClipData().getItemAt(i).getUri(); } } } } } catch (Exception ignored) { } mFileUploadCallbackSecond.onReceiveValue(dataUris); mFileUploadCallbackSecond = null; } } } else { if (mFileUploadCallbackFirst != null) { mFileUploadCallbackFirst.onReceiveValue(null); mFileUploadCallbackFirst = null; } else if (mFileUploadCallbackSecond != null) { mFileUploadCallbackSecond.onReceiveValue(null); mFileUploadCallbackSecond = null; } } } } /** * Adds an additional HTTP header that will be sent along with every HTTP `GET` request * * This does only affect the main requests, not the requests to included resources (e.g. images) * * If you later want to delete an HTTP header that was previously added this way, call `removeHttpHeader()` * * The `WebView` implementation may in some cases overwrite headers that you set or unset * * @param name the name of the HTTP header to add * @param value the value of the HTTP header to send */ public void addHttpHeader(final String name, final String value) { mHttpHeaders.put(name, value); } /** * Removes one of the HTTP headers that have previously been added via `addHttpHeader()` * * If you want to unset a pre-defined header, set it to an empty string with `addHttpHeader()` instead * * The `WebView` implementation may in some cases overwrite headers that you set or unset * * @param name the name of the HTTP header to remove */ public void removeHttpHeader(final String name) { mHttpHeaders.remove(name); } public void addPermittedHostname(String hostname) { mPermittedHostnames.add(hostname); } public void addPermittedHostnames(Collection<? extends String> collection) { mPermittedHostnames.addAll(collection); } public List<String> getPermittedHostnames() { return mPermittedHostnames; } public void removePermittedHostname(String hostname) { mPermittedHostnames.remove(hostname); } public void clearPermittedHostnames() { mPermittedHostnames.clear(); } public boolean onBackPressed() { if (canGoBack()) { goBack(); return false; } else { return true; } } @SuppressLint("NewApi") protected static void setAllowAccessFromFileUrls(final WebSettings webSettings, final boolean allowed) { if (Build.VERSION.SDK_INT >= 16) { webSettings.setAllowFileAccessFromFileURLs(allowed); webSettings.setAllowUniversalAccessFromFileURLs(allowed); } } @SuppressWarnings("static-method") public void setCookiesEnabled(final boolean enabled) { CookieManager.getInstance().setAcceptCookie(enabled); } @SuppressLint("NewApi") public void setThirdPartyCookiesEnabled(final boolean enabled) { if (Build.VERSION.SDK_INT >= 21) { CookieManager.getInstance().setAcceptThirdPartyCookies(this, enabled); } } public void setMixedContentAllowed(final boolean allowed) { setMixedContentAllowed(getSettings(), allowed); } @SuppressWarnings("static-method") @SuppressLint("NewApi") protected void setMixedContentAllowed(final WebSettings webSettings, final boolean allowed) { if (Build.VERSION.SDK_INT >= 21) { webSettings.setMixedContentMode(allowed ? WebSettings.MIXED_CONTENT_ALWAYS_ALLOW : WebSettings.MIXED_CONTENT_NEVER_ALLOW); } } public void setDesktopMode(final boolean enabled) { final WebSettings webSettings = getSettings(); final String newUserAgent; if (enabled) { newUserAgent = webSettings.getUserAgentString().replace("Mobile", "eliboM").replace("Android", "diordnA"); } else { newUserAgent = webSettings.getUserAgentString().replace("eliboM", "Mobile").replace("diordnA", "Android"); } webSettings.setUserAgentString(newUserAgent); webSettings.setUseWideViewPort(enabled); webSettings.setLoadWithOverviewMode(enabled); webSettings.setSupportZoom(enabled); webSettings.setBuiltInZoomControls(enabled); } @SuppressLint({ "SetJavaScriptEnabled" }) protected void init(Context context) { // in IDE's preview mode if (isInEditMode()) { // do not run the code from this method return; } if (context instanceof Activity) { mActivity = new WeakReference<Activity>((Activity) context); } mLanguageIso3 = getLanguageIso3(); setFocusable(true); setFocusableInTouchMode(true); setSaveEnabled(true); final String filesDir = context.getFilesDir().getPath(); final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER; final WebSettings webSettings = getSettings(); webSettings.setAllowFileAccess(false); setAllowAccessFromFileUrls(webSettings, false); webSettings.setBuiltInZoomControls(false); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); if (Build.VERSION.SDK_INT < 18) { webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); } webSettings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT < 19) { webSettings.setDatabasePath(databaseDir); } setMixedContentAllowed(webSettings, true); setThirdPartyCookiesEnabled(true); super.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { if (!hasError()) { if (mListener != null) { mListener.onPageStarted(url, favicon); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageStarted(view, url, favicon); } } @Override public void onPageFinished(WebView view, String url) { if (!hasError()) { if (mListener != null) { mListener.onPageFinished(url); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageFinished(view, url); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { setLastError(); if (mListener != null) { mListener.onPageError(errorCode, description, failingUrl); } if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl); } } @Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { if (!isPermittedUrl(url)) { // if a listener is available if (mListener != null) { // inform the listener about the request mListener.onExternalPageRequest(url); } // cancel the original request return true; } // if there is a user-specified handler available if (mCustomWebViewClient != null) { // if the user-specified handler asks to override the request if (mCustomWebViewClient.shouldOverrideUrlLoading(view, url)) { // cancel the original request return true; } } // route the request through the custom URL loading method view.loadUrl(url); // cancel the original request return true; } @Override public void onLoadResource(WebView view, String url) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onLoadResource(view, url); } else { super.onLoadResource(view, url); } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (Build.VERSION.SDK_INT >= 11) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, url); } else { return super.shouldInterceptRequest(view, url); } } else { return null; } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, request); } else { return super.shouldInterceptRequest(view, request); } } else { return null; } } @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onFormResubmission(view, dontResend, resend); } else { super.onFormResubmission(view, dontResend, resend); } } @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { if (mCustomWebViewClient != null) { mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload); } else { super.doUpdateVisitedHistory(view, url, isReload); } } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedSslError(view, handler, error); } else { super.onReceivedSslError(view, handler, error); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedClientCertRequest(view, request); } else { super.onReceivedClientCertRequest(view, request); } } } @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); } else { super.onReceivedHttpAuthRequest(view, handler, host, realm); } } @Override public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldOverrideKeyEvent(view, event); } else { return super.shouldOverrideKeyEvent(view, event); } } @Override public void onUnhandledKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledKeyEvent(view, event); } else { super.onUnhandledKeyEvent(view, event); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onUnhandledInputEvent(WebView view, InputEvent event) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledInputEvent(view, event); } else { super.onUnhandledInputEvent(view, event); } } } @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onScaleChanged(view, oldScale, newScale); } else { super.onScaleChanged(view, oldScale, newScale); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { if (Build.VERSION.SDK_INT >= 12) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args); } else { super.onReceivedLoginRequest(view, realm, account, args); } } } }); super.setWebChromeClient(new WebChromeClient() { // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg) { openFileChooser(uploadMsg, null); } // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method) public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { openFileChooser(uploadMsg, acceptType, null); } // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { openFileInput(uploadMsg, null, false); } // file upload callback (Android 5.0 (API level 21) -- current) (public method) @SuppressWarnings("all") public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { if (Build.VERSION.SDK_INT >= 21) { final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE; openFileInput(null, filePathCallback, allowMultiple); return true; } else { return false; } } @Override public void onProgressChanged(WebView view, int newProgress) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onProgressChanged(view, newProgress); } else { super.onProgressChanged(view, newProgress); } } @Override public void onReceivedTitle(WebView view, String title) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTitle(view, title); } else { super.onReceivedTitle(view, title); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedIcon(view, icon); } else { super.onReceivedIcon(view, icon); } } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed); } else { super.onReceivedTouchIconUrl(view, url, precomposed); } } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, callback); } else { super.onShowCustomView(view, callback); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { if (Build.VERSION.SDK_INT >= 14) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback); } else { super.onShowCustomView(view, requestedOrientation, callback); } } } @Override public void onHideCustomView() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onHideCustomView(); } else { super.onHideCustomView(); } } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } else { return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } } @Override public void onRequestFocus(WebView view) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onRequestFocus(view); } else { super.onRequestFocus(view); } } @Override public void onCloseWindow(WebView window) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onCloseWindow(window); } else { super.onCloseWindow(window); } } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsAlert(view, url, message, result); } else { return super.onJsAlert(view, url, message, result); } } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsConfirm(view, url, message, result); } else { return super.onJsConfirm(view, url, message, result); } } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result); } else { return super.onJsPrompt(view, url, message, defaultValue, result); } } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result); } else { return super.onJsBeforeUnload(view, url, message, result); } } @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { if (mGeolocationEnabled) { callback.invoke(origin, true, false); } else { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback); } else { super.onGeolocationPermissionsShowPrompt(origin, callback); } } } @Override public void onGeolocationPermissionsHidePrompt() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsHidePrompt(); } else { super.onGeolocationPermissionsHidePrompt(); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequest(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequest(request); } else { super.onPermissionRequest(request); } } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequestCanceled(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequestCanceled(request); } else { super.onPermissionRequestCanceled(request); } } } @Override public boolean onJsTimeout() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsTimeout(); } else { return super.onJsTimeout(); } } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID); } else { super.onConsoleMessage(message, lineNumber, sourceID); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onConsoleMessage(consoleMessage); } else { return super.onConsoleMessage(consoleMessage); } } @Override public Bitmap getDefaultVideoPoster() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getDefaultVideoPoster(); } else { return super.getDefaultVideoPoster(); } } @Override public View getVideoLoadingProgressView() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getVideoLoadingProgressView(); } else { return super.getVideoLoadingProgressView(); } } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.getVisitedHistory(callback); } else { super.getVisitedHistory(callback); } } @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } else { super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } } @Override public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } else { super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } } }); setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(final String url, final String userAgent, final String contentDisposition, final String mimeType, final long contentLength) { final String suggestedFilename = URLUtil.guessFileName(url, contentDisposition, mimeType); if (mListener != null) { mListener.onDownloadRequested(url, suggestedFilename, mimeType, contentLength, contentDisposition, userAgent); } } }); } @Override public void loadUrl(final String url, Map<String, String> additionalHttpHeaders) { if (additionalHttpHeaders == null) { additionalHttpHeaders = mHttpHeaders; } else if (mHttpHeaders.size() > 0) { additionalHttpHeaders.putAll(mHttpHeaders); } super.loadUrl(url, additionalHttpHeaders); } @Override public void loadUrl(final String url) { if (mHttpHeaders.size() > 0) { super.loadUrl(url, mHttpHeaders); } else { super.loadUrl(url); } } public void loadUrl(String url, final boolean preventCaching) { if (preventCaching) { url = makeUrlUnique(url); } loadUrl(url); } public void loadUrl(String url, final boolean preventCaching, final Map<String,String> additionalHttpHeaders) { if (preventCaching) { url = makeUrlUnique(url); } loadUrl(url, additionalHttpHeaders); } protected static String makeUrlUnique(final String url) { StringBuilder unique = new StringBuilder(); unique.append(url); if (url.contains("?")) { unique.append('&'); } else { if (url.lastIndexOf('/') <= 7) { unique.append('/'); } unique.append('?'); } unique.append(System.currentTimeMillis()); unique.append('='); unique.append(1); return unique.toString(); } public boolean isPermittedUrl(final String url) { // if the permitted hostnames have not been restricted to a specific set if (mPermittedHostnames.size() == 0) { // all hostnames are allowed return true; } // get the actual hostname of the URL that is to be checked final String actualHost = Uri.parse(url).getHost(); // if the hostname could not be determined, usually because the URL has been invalid if (actualHost == null) { return false; } // for every hostname in the set of permitted hosts for (String expectedHost : mPermittedHostnames) { // if the two hostnames match or if the actual host is a subdomain of the expected host if (actualHost.equals(expectedHost) || actualHost.endsWith("." + expectedHost)) { // the actual hostname of the URL to be checked is allowed return true; } } // the actual hostname of the URL to be checked is not allowed since there were no matches return false; } /** * @deprecated use `isPermittedUrl` instead */ protected boolean isHostnameAllowed(final String url) { return isPermittedUrl(url); } protected void setLastError() { mLastError = System.currentTimeMillis(); } protected boolean hasError() { return (mLastError + 500) >= System.currentTimeMillis(); } protected static String getLanguageIso3() { try { return Locale.getDefault().getISO3Language().toLowerCase(Locale.US); } catch (MissingResourceException e) { return LANGUAGE_DEFAULT_ISO3; } } /** * Provides localizations for the 25 most widely spoken languages that have a ISO 639-2/T code * * @return the label for the file upload prompts as a string */ protected String getFileUploadPromptLabel() { try { if (mLanguageIso3.equals("zho")) return decodeBase64("6YCJ5oup5LiA5Liq5paH5Lu2"); else if (mLanguageIso3.equals("spa")) return decodeBase64("RWxpamEgdW4gYXJjaGl2bw=="); else if (mLanguageIso3.equals("hin")) return decodeBase64("4KSP4KSVIOCkq+CkvOCkvuCkh+CksiDgpJrgpYHgpKjgpYfgpII="); else if (mLanguageIso3.equals("ben")) return decodeBase64("4KaP4KaV4Kaf4Ka/IOCmq+CmvuCmh+CmsiDgpqjgpr/gprDgp43gpqzgpr7gpprgpqg="); else if (mLanguageIso3.equals("ara")) return decodeBase64("2KfYrtiq2YrYp9ixINmF2YTZgSDZiNin2K3Yrw=="); else if (mLanguageIso3.equals("por")) return decodeBase64("RXNjb2xoYSB1bSBhcnF1aXZv"); else if (mLanguageIso3.equals("rus")) return decodeBase64("0JLRi9Cx0LXRgNC40YLQtSDQvtC00LjQvSDRhNCw0LnQuw=="); else if (mLanguageIso3.equals("jpn")) return decodeBase64("MeODleOCoeOCpOODq+OCkumBuOaKnuOBl+OBpuOBj+OBoOOBleOBhA=="); else if (mLanguageIso3.equals("pan")) return decodeBase64("4KiH4Kmx4KiVIOCoq+CovuCoh+CosiDgqJrgqYHgqKPgqYs="); else if (mLanguageIso3.equals("deu")) return decodeBase64("V8OkaGxlIGVpbmUgRGF0ZWk="); else if (mLanguageIso3.equals("jav")) return decodeBase64("UGlsaWggc2lqaSBiZXJrYXM="); else if (mLanguageIso3.equals("msa")) return decodeBase64("UGlsaWggc2F0dSBmYWls"); else if (mLanguageIso3.equals("tel")) return decodeBase64("4LCS4LCVIOCwq+CxhuCxluCwsuCxjeCwqOCxgSDgsI7gsILgsJrgsYHgsJXgsYvgsILgsKHgsL8="); else if (mLanguageIso3.equals("vie")) return decodeBase64("Q2jhu41uIG3hu5l0IHThuq1wIHRpbg=="); else if (mLanguageIso3.equals("kor")) return decodeBase64("7ZWY64KY7J2YIO2MjOydvOydhCDshKDtg50="); else if (mLanguageIso3.equals("fra")) return decodeBase64("Q2hvaXNpc3NleiB1biBmaWNoaWVy"); else if (mLanguageIso3.equals("mar")) return decodeBase64("4KSr4KS+4KSH4KSyIOCkqOCkv+CkteCkoeCkvg=="); else if (mLanguageIso3.equals("tam")) return decodeBase64("4K6S4K6w4K+BIOCuleCvh+CuvuCuquCvjeCuquCviCDgrqTgr4fgrrDgr43grrXgr4E="); else if (mLanguageIso3.equals("urd")) return decodeBase64("2KfbjNqpINmB2KfYptmEINmF24zauiDYs9uSINin2YbYqtiu2KfYqCDaqdix24zaug=="); else if (mLanguageIso3.equals("fas")) return decodeBase64("2LHYpyDYp9mG2KrYrtin2Kgg2qnZhtuM2K8g24zaqSDZgdin24zZhA=="); else if (mLanguageIso3.equals("tur")) return decodeBase64("QmlyIGRvc3lhIHNlw6dpbg=="); else if (mLanguageIso3.equals("ita")) return decodeBase64("U2NlZ2xpIHVuIGZpbGU="); else if (mLanguageIso3.equals("tha")) return decodeBase64("4LmA4Lil4Li34Lit4LiB4LmE4Lif4Lil4LmM4Lir4LiZ4Li24LmI4LiH"); else if (mLanguageIso3.equals("guj")) return decodeBase64("4KqP4KqVIOCqq+CqvuCqh+CqsuCqqOCrhyDgqqrgqrjgqoLgqqY="); } catch (Exception ignored) { } // return English translation by default return "Choose a file"; } protected static String decodeBase64(final String base64) throws IllegalArgumentException, UnsupportedEncodingException { final byte[] bytes = Base64.decode(base64, Base64.DEFAULT); return new String(bytes, CHARSET_DEFAULT); } @SuppressLint("NewApi") protected void openFileInput(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond, final boolean allowMultiple) { if (mFileUploadCallbackFirst != null) { mFileUploadCallbackFirst.onReceiveValue(null); } mFileUploadCallbackFirst = fileUploadCallbackFirst; if (mFileUploadCallbackSecond != null) { mFileUploadCallbackSecond.onReceiveValue(null); } mFileUploadCallbackSecond = fileUploadCallbackSecond; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); if (allowMultiple) { if (Build.VERSION.SDK_INT >= 18) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } i.setType(mUploadableFileTypes); if (mFragment != null && mFragment.get() != null && Build.VERSION.SDK_INT >= 11) { mFragment.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker); } else if (mActivity != null && mActivity.get() != null) { mActivity.get().startActivityForResult(Intent.createChooser(i, getFileUploadPromptLabel()), mRequestCodeFilePicker); } } /** * Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) * * @return whether file uploads can be used */ public static boolean isFileUploadAvailable() { return isFileUploadAvailable(false); } /** * Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) * * On Android 4.4.3/4.4.4, file uploads may be possible but will come with a wrong MIME type * * @param needsCorrectMimeType whether a correct MIME type is required for file uploads or `application/octet-stream` is acceptable * @return whether file uploads can be used */ public static boolean isFileUploadAvailable(final boolean needsCorrectMimeType) { if (Build.VERSION.SDK_INT == 19) { final String platformVersion = (Build.VERSION.RELEASE == null) ? "" : Build.VERSION.RELEASE; return !needsCorrectMimeType && (platformVersion.startsWith("4.4.3") || platformVersion.startsWith("4.4.4")); } else { return true; } } /** * Handles a download by loading the file from `fromUrl` and saving it to `toFilename` on the external storage * * This requires the two permissions `android.permission.INTERNET` and `android.permission.WRITE_EXTERNAL_STORAGE` * * Only supported on API level 9 (Android 2.3) and above * * @param context a valid `Context` reference * @param fromUrl the URL of the file to download, e.g. the one from `AdvancedWebView.onDownloadRequested(...)` * @param toFilename the name of the destination file where the download should be saved, e.g. `myImage.jpg` * @return whether the download has been successfully handled or not * @throws IllegalStateException if the storage or the target directory could not be found or accessed */ @SuppressLint("NewApi") public static boolean handleDownload(final Context context, final String fromUrl, final String toFilename) { if (Build.VERSION.SDK_INT < 9) { throw new RuntimeException("Method requires API level 9 or above"); } final Request request = new Request(Uri.parse(fromUrl)); if (Build.VERSION.SDK_INT >= 11) { request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, toFilename); final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); try { try { dm.enqueue(request); } catch (SecurityException e) { if (Build.VERSION.SDK_INT >= 11) { request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); } dm.enqueue(request); } return true; } // if the download manager app has been disabled on the device catch (IllegalArgumentException e) { // show the settings screen where the user can enable the download manager app again openAppSettings(context, AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER); return false; } } @SuppressLint("NewApi") private static boolean openAppSettings(final Context context, final String packageName) { if (Build.VERSION.SDK_INT < 9) { throw new RuntimeException("Method requires API level 9 or above"); } try { final Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + packageName)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return true; } catch (Exception e) { return false; } } /** Wrapper for methods related to alternative browsers that have their own rendering engines */ public static class Browsers { /** Package name of an alternative browser that is installed on this device */ private static String mAlternativePackage; /** * Returns whether there is an alternative browser with its own rendering engine currently installed * * @param context a valid `Context` reference * @return whether there is an alternative browser or not */ public static boolean hasAlternative(final Context context) { return getAlternative(context) != null; } /** * Returns the package name of an alternative browser with its own rendering engine or `null` * * @param context a valid `Context` reference * @return the package name or `null` */ public static String getAlternative(final Context context) { if (mAlternativePackage != null) { return mAlternativePackage; } final List<String> alternativeBrowsers = Arrays.asList(ALTERNATIVE_BROWSERS); final List<ApplicationInfo> apps = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo app : apps) { if (!app.enabled) { continue; } if (alternativeBrowsers.contains(app.packageName)) { mAlternativePackage = app.packageName; return app.packageName; } } return null; } /** * Opens the given URL in an alternative browser * * @param context a valid `Activity` reference * @param url the URL to open */ public static void openUrl(final Activity context, final String url) { openUrl(context, url, false); } /** * Opens the given URL in an alternative browser * * @param context a valid `Activity` reference * @param url the URL to open * @param withoutTransition whether to switch to the browser `Activity` without a transition */ public static void openUrl(final Activity context, final String url, final boolean withoutTransition) { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setPackage(getAlternative(context)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); if (withoutTransition) { context.overridePendingTransition(0, 0); } } } }
Mitigate inconsistent interpretations of hosts by 'Uri' and 'WebView'
Source/library/src/main/java/im/delight/android/webview/AdvancedWebView.java
Mitigate inconsistent interpretations of hosts by 'Uri' and 'WebView'
<ide><path>ource/library/src/main/java/im/delight/android/webview/AdvancedWebView.java <ide> return true; <ide> } <ide> <del> // get the actual hostname of the URL that is to be checked <del> final String actualHost = Uri.parse(url).getHost(); <add> final Uri parsedUrl = Uri.parse(url); <add> <add> // get the hostname of the URL that is to be checked <add> final String actualHost = parsedUrl.getHost(); <ide> <ide> // if the hostname could not be determined, usually because the URL has been invalid <ide> if (actualHost == null) { <add> return false; <add> } <add> <add> // if the host contains invalid characters (e.g. a backslash) <add> if (!actualHost.matches("^[a-zA-Z0-9._!~*')(;:&=+$,%\\[\\]-]*$")) { <add> // prevent mismatches between interpretations by `Uri` and `WebView`, e.g. for `http://evil.example.com\.good.example.com/` <add> return false; <add> } <add> <add> // get the user information from the authority part of the URL that is to be checked <add> final String actualUserInformation = parsedUrl.getUserInfo(); <add> <add> // if the user information contains invalid characters (e.g. a backslash) <add> if (actualUserInformation != null && !actualUserInformation.matches("^[a-zA-Z0-9._!~*')(;:&=+$,%-]*$")) { <add> // prevent mismatches between interpretations by `Uri` and `WebView`, e.g. for `http://evil.example.com\@good.example.com/` <ide> return false; <ide> } <ide>
Java
epl-1.0
c03367adeeaec6b35166ed748447659e8cd0ae18
0
crapo/sadlos2,crapo/sadlos2,crapo/sadlos2,crapo/sadlos2,crapo/sadlos2,crapo/sadlos2
/************************************************************************ * Copyright © 2007-2017 - General Electric Company, All Rights Reserved * * Project: SADL * * Description: The Semantic Application Design Language (SADL) is a * language for building semantic models and expressing rules that * capture additional domain knowledge. The SADL-IDE (integrated * development environment) is a set of Eclipse plug-ins that * support the editing and testing of semantic models using the * SADL language. * * This software is distributed "AS-IS" without ANY WARRANTIES * and licensed under the Eclipse Public License - v 1.0 * which is available at http://www.eclipse.org/org/documents/epl-v10.php * ***********************************************************************/ package com.ge.research.sadl.jena; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.nodemodel.impl.CompositeNodeWithSemanticElement; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.resource.XtextResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ge.research.sadl.jena.JenaBasedSadlModelValidator.TypeCheckInfo; import com.ge.research.sadl.model.ConceptName; import com.ge.research.sadl.model.ConceptName.ConceptType; import com.ge.research.sadl.model.gp.BuiltinElement; import com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType; import com.ge.research.sadl.model.gp.ConstantNode; import com.ge.research.sadl.model.gp.GraphPatternElement; import com.ge.research.sadl.model.gp.Junction; import com.ge.research.sadl.model.gp.Junction.JunctionType; import com.ge.research.sadl.model.gp.Literal; import com.ge.research.sadl.model.gp.NamedNode; import com.ge.research.sadl.model.gp.NamedNode.NodeType; import com.ge.research.sadl.model.gp.Node; import com.ge.research.sadl.model.gp.ProxyNode; import com.ge.research.sadl.model.gp.RDFTypeNode; import com.ge.research.sadl.model.gp.Rule; import com.ge.research.sadl.model.gp.Test; import com.ge.research.sadl.model.gp.Test.ComparisonType; import com.ge.research.sadl.model.gp.TripleElement; import com.ge.research.sadl.model.gp.TripleElement.TripleModifierType; import com.ge.research.sadl.model.gp.TripleElement.TripleSourceType; import com.ge.research.sadl.model.gp.VariableNode; import com.ge.research.sadl.processing.SadlConstants; import com.ge.research.sadl.processing.SadlModelProcessor; import com.ge.research.sadl.reasoner.InvalidNameException; import com.ge.research.sadl.reasoner.InvalidTypeException; import com.ge.research.sadl.reasoner.TranslationException; import com.ge.research.sadl.reasoner.utils.SadlUtils; import com.ge.research.sadl.sADL.Expression; import com.ge.research.sadl.sADL.TestStatement; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.UnionClass; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.RDFS; /** * This class translates the output generated by parsing SADL queries, * rules, and tests into what is called the SADL Intermediate Form (IF). * The parser output is in the form of parse trees whose nodes are * instances of the class Expression or of one of its subclasses. * The IF uses the Java classes in the Graph Patterns package * (com.ge.research.sadl.model.gp). In the IF, each query or * rule part (given, if, or then) or test phrase consists of * a list of graph pattern elements. The graph pattern element * can be a triple pattern or it can be a built-in. This * Intermediate Form is passed to the reasoner-specific translator * to generate rules and queries in an optimized form and format * for the target reasoner. * * One of the primary contributions of SADL to the modeling process is * its English-like syntax. The translation accomplished by this class * goes from this English-like syntax to the IF. Among other things, this * involves the generation of "missing" variables to provide the * connectives between the individual graph pattern elements in a list. * * The translation process "walks" the Expression parse tree. At the * leaves of this parse tree are ExplicitValues, IntervalValues, * ValueTables, or built-ins. At each node higher in the parse tree, * if returning to the node represents the completion of a graph pattern * element then that element is placed in the list at the appropriate * location and if necessary a variable (Node) is identified to connect * this new graph pattern element to other graph pattern elements * in the list. * * 10/2011: * The approach of adding variables as the translation proceeds, bottom-up, * has issues as looking bottom up one can't always tell the context and * therefore make the right decision. Therefore the strategy is changed to * use a ProxyNode to encapsulate the lower-level constructs to replicate * the parse tree but in the IF structures. Then the expansion of ProxyNodes * can occur with a knowledge of context for proper decisioning. For example, * no information is available to know whether a rule built-in has zero, one, * or more output variables. However, usage will show that either the built-in * is used within a higher-level built-in or triple, in which case it must * generate an output other than boolean so in expand ProxyNodes it will be * property handled by adding a generated variable if a specified variable * was not given, which variable is also placed in * the higher-level construct. In the future built-ins might be allowed to * return multiple values but that would require a construct such as * * x,y,z is someBuiltin(input1, input2, ..) * * This extension of the grammar would provide the necessary information * about the number of output variables to add, but only with the contextual * knowledge of the whole statement. * * * @author crapo * */ public class IntermediateFormTranslator implements I_IntermediateFormTranslator { protected static final Logger logger = LoggerFactory.getLogger(IntermediateFormTranslator.class); private int vNum = 0; // used to create unique variables private List<IFTranslationError> errors = null; private Object target = null; // the instance of Rule, Query, or Test into which we are trying to put the translation private Object encapsulatingTarget = null; // when a query is in a test private GraphPatternElement firstOfPhrase = null; private List<ConceptName> namedNodes = null; private boolean collectNamedNodes = false; private List<String> userDefinedVariables = new ArrayList<String>(); private OntModel theJenaModel = null; private JenaBasedSadlModelProcessor modelProcessor = null; private List<VariableNode> cruleVariablesTypeOutput = null; // list of crule variables that have had type statements output (only do so once) /** * The constructor takes a ModelManager argument * @param ontModel * @param modmgr */ public IntermediateFormTranslator(OntModel ontModel) { setTheJenaModel(ontModel); } /** * The constructor takes a ModelManager argument * @param ontModel * @param modmgr */ public IntermediateFormTranslator(JenaBasedSadlModelProcessor processor, OntModel ontModel) { setModelProcessor(processor); setTheJenaModel(ontModel); } // the target can be a Test, a Query, or a Rule instance /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#setTarget(java.lang.Object) */ @Override public void setTarget(Object _target) { target = _target; } @Override public Object getTarget() { return target; } /** * Reset the translator for a new translation task */ protected void resetIFTranslator() { vNum = 0; if (errors != null) { errors.clear(); } setTarget(null); encapsulatingTarget = null; setFirstOfPhrase(null); } /** * Returns the bottom triple whose subject was replaced. * @param pattern * @param proxyFor * @param assignedNode * @return */ private TripleElement assignNullSubjectInProxies(TripleElement pattern, TripleElement proxyFor, Node assignedNode) { if (pattern.getSubject() instanceof ProxyNode) { Object proxy = ((ProxyNode)pattern.getSubject()).getProxyFor(); if (proxy instanceof TripleElement) { // ((ProxyNode)pattern.getSubject()).setReplacementNode(assignedNode); if (((TripleElement)proxy).getSubject() == null) { // this is the bottom of the recursion ((TripleElement)proxy).setSubject(assignedNode); return (TripleElement) proxy; } else { // recurse down TripleElement bottom = assignNullSubjectInProxies(((TripleElement)proxy), proxyFor, assignedNode); // make the proxy next and reassign this subject as assignedNode ((ProxyNode)((TripleElement)proxy).getSubject()).setReplacementNode(assignedNode); ((TripleElement)proxy).setSubject(assignedNode); if (bottom.getNext() == null) { bottom.setNext(pattern); } return bottom; } } } return null; } private TripleElement getProxyWithNullSubject(TripleElement pattern) { if (pattern.getSubject() instanceof ProxyNode) { Object proxy = ((ProxyNode)pattern.getSubject()).getProxyFor(); if (proxy instanceof TripleElement) { if (((TripleElement)proxy).getSubject() == null) { return (TripleElement)proxy; } else { return getProxyWithNullSubject(((TripleElement)proxy)); } } } return null; } private boolean isComparisonViaBuiltin(Object robj, Object lobj) { if (robj instanceof TripleElement && lobj instanceof Node && ((TripleElement)robj).getNext() instanceof BuiltinElement) { BuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext(); if (isComparisonBuiltin(be.getFuncName()) && be.getArguments().size() == 1) { return true; } } return false; } private boolean isModifiedTripleViaBuitin(Object robj) { if (robj instanceof TripleElement && ((TripleElement)robj).getNext() instanceof BuiltinElement) { BuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext(); if (((TripleElement)robj).getPredicate() instanceof RDFTypeNode) { if (isModifiedTriple(be.getFuncType())) { Node subj = ((TripleElement)robj).getSubject(); Node arg = (be.getArguments() != null && be.getArguments().size() > 0) ? be.getArguments().get(0) : null; if (subj == null && arg == null) { return true; } if (subj != null && arg != null && subj.equals(arg)) { return true; } } } else { if (isModifiedTriple(be.getFuncType()) && ((TripleElement)robj).getObject().equals(be.getArguments().get(0))) { return true; } } } return false; } private boolean hasCommonVariableSubject(Object robj) { if (robj instanceof TripleElement && (((TripleElement)robj).getSubject() instanceof VariableNode && (((TripleElement)robj).getSourceType().equals(TripleSourceType.SPV)) || ((TripleElement)robj).getSourceType().equals(TripleSourceType.ITC))) { VariableNode subjvar = (VariableNode) ((TripleElement)robj).getSubject(); Object trel = robj; while (trel != null && trel instanceof TripleElement) { if (!(trel instanceof TripleElement) || (((TripleElement)trel).getSubject() != null &&!(((TripleElement)trel).getSubject().equals(subjvar)))) { return false; } trel = ((TripleElement)trel).getNext(); } if (trel == null) { return true; } } return false; } public static boolean isModifiedTriple(BuiltinType type) { if (type.equals(BuiltinType.Not) || type.equals(BuiltinType.NotEqual) || type.equals(BuiltinType.Only)|| type.equals(BuiltinType.NotOnly)) { return true; } return false; } public String getSourceGrammarText(EObject po) { Object r = po.eResource(); if (r instanceof XtextResource) { INode root = ((XtextResource) r).getParseResult().getRootNode(); for(INode node : root.getAsTreeIterable()) { if (node instanceof CompositeNodeWithSemanticElement) { EObject semElt = ((CompositeNodeWithSemanticElement)node).getSemanticElement(); if (semElt.equals(po)) { // this is the one! String txt = NodeModelUtils.getTokenText(node); return txt.trim(); } } } org.eclipse.emf.common.util.TreeIterator<EObject> titr = po.eAllContents(); while (titr.hasNext()) { EObject el = titr.next(); // TODO what's supposed to happen here? int i = 0; } } return null; } /** * This method fills in missing information in a NamedNode: * the prefix, the namespace, the type * * @param namedNode * @return * @throws InvalidNameException */ protected Node validateNode(Node node) throws InvalidNameException { if (node instanceof NamedNode) { if (!((NamedNode)node).isValidated()) { if (node instanceof VariableNode) { ((VariableNode) node).setNodeType(NodeType.VariableNode); userDefinedVariables.add(((NamedNode) node).getName()); } else if (node instanceof RDFTypeNode) { ((RDFTypeNode) node).setNodeType(NodeType.PropertyNode); } else { ConceptName cname = null; ConceptType ctype = null; String name = ((NamedNode)node).toString(); //getName(); if (name == null) { throw new InvalidNameException("A NamedNode has a null name! Did ResourceByName resolution fail?"); } int colon = name.indexOf(':'); if (colon > 0 && colon < name.length() - 1) { String pfx = name.substring(0, colon); ((NamedNode)node).setPrefix(pfx); String lname = name.substring(colon + 1); ((NamedNode)node).setName(lname); // cname = modelManager.validateConceptName(new ConceptName(pfx, lname)); } else { // cname = modelManager.validateConceptName(new ConceptName(name)); } ctype = cname.getType(); ((NamedNode)node).setNamespace(cname.getNamespace()); ((NamedNode)node).setPrefix(cname.getPrefix()); if (ctype.equals(ConceptType.CONCEPT_NOT_FOUND_IN_MODEL)) { // modelManager.addToVariableNamesCache(cname); node = new VariableNode(((NamedNode)node).getName()); userDefinedVariables.add(((NamedNode) node).getName()); } else if (ctype.equals(ConceptType.ANNOTATIONPROPERTY)){ ((NamedNode)node).setNodeType(NodeType.PropertyNode); } else if (ctype.equals(ConceptType.DATATYPEPROPERTY)){ ((NamedNode)node).setNodeType(NodeType.PropertyNode); } else if (ctype.equals(ConceptType.OBJECTPROPERTY)){ ((NamedNode)node).setNodeType(NodeType.PropertyNode); } else if (ctype.equals(ConceptType.ONTCLASS)){ ((NamedNode)node).setNodeType(NodeType.ClassNode); } else if (ctype.equals(ConceptType.INDIVIDUAL)){ ((NamedNode)node).setNodeType(NodeType.InstanceNode); } else { logger.error("Unexpected ConceptType: " + ctype.toString()); addError(new IFTranslationError("Unexpected ConceptType: " + ctype.toString())); } if (isCollectNamedNodes()) { if (namedNodes == null) { namedNodes = new ArrayList<ConceptName>(); } if (!namedNodes.contains(cname)) { namedNodes.add(cname); } } } ((NamedNode)node).setValidated(true); } } return node; } private void addError(IFTranslationError error) { if (errors == null) { errors = new ArrayList<IFTranslationError>(); } errors.add(error); } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#getErrors() */ @Override public List<IFTranslationError> getErrors() { return errors; } private GraphPatternElement createBinaryBuiltin(Expression expr, String name, Object lobj, Object robj) throws InvalidNameException, InvalidTypeException, TranslationException { BuiltinElement builtin = new BuiltinElement(); builtin.setFuncName(name); if (lobj != null) { builtin.addArgument(SadlModelProcessor.nodeCheck(lobj)); } if (robj != null) { builtin.addArgument(SadlModelProcessor.nodeCheck(robj)); } return builtin; } private Junction createJunction(Expression expr, String name, Object lobj, Object robj) throws InvalidNameException, InvalidTypeException, TranslationException { Junction junction = new Junction(); junction.setJunctionName(name); junction.setLhs(SadlModelProcessor.nodeCheck(lobj)); junction.setRhs(SadlModelProcessor.nodeCheck(robj)); return junction; } private Object createUnaryBuiltin(Expression sexpr, String name, Object sobj) throws InvalidNameException, InvalidTypeException, TranslationException { if (sobj instanceof Literal && BuiltinType.getType(name).equals(BuiltinType.Minus)) { Object theVal = ((Literal)sobj).getValue(); if (theVal instanceof Integer) { theVal = ((Integer)theVal) * -1; } else if (theVal instanceof Long) { theVal = ((Long)theVal) * -1; } else if (theVal instanceof Float) { theVal = ((Float)theVal) * -1; } else if (theVal instanceof Double) { theVal = ((Double)theVal) * -1; } ((Literal)sobj).setValue(theVal); ((Literal)sobj).setOriginalText("-" + ((Literal)sobj).getOriginalText()); return sobj; } if (sobj instanceof Junction) { // If the junction has two literal values, apply the op to both of them. Junction junc = (Junction) sobj; Object lhs = junc.getLhs(); Object rhs = junc.getRhs(); if (lhs instanceof Literal && rhs instanceof Literal) { lhs = createUnaryBuiltin(sexpr, name, lhs); rhs = createUnaryBuiltin(sexpr, name, rhs); junc.setLhs(SadlModelProcessor.nodeCheck(lhs)); junc.setRhs(SadlModelProcessor.nodeCheck(rhs)); } return junc; } if (BuiltinType.getType(name).equals(BuiltinType.Equal)) { if (sobj instanceof BuiltinElement) { if (isComparisonBuiltin(((BuiltinElement)sobj).getFuncName())) { // this is a "is <comparison>"--translates to <comparsion> (ignore is) return sobj; } } else if (sobj instanceof Literal || sobj instanceof NamedNode) { // an "=" interval value of a value is just the value return sobj; } } BuiltinElement builtin = new BuiltinElement(); builtin.setFuncName(name); if (isModifiedTriple(builtin.getFuncType())) { if (sobj instanceof TripleElement) { ((TripleElement)sobj).setType(getModelProcessor().getTripleModifierType(builtin.getFuncType())); return sobj; } } if (sobj != null) { builtin.addArgument(SadlModelProcessor.nodeCheck(sobj)); } return builtin; } private TripleElement addGraphPatternElementAtEnd(GraphPatternElement head, Node subject, Node predicate, Node object, TripleSourceType sourceType) { TripleElement newTriple = new TripleElement(); newTriple.setSubject(subject); newTriple.setPredicate(predicate); newTriple.setObject(object); newTriple.setSourceType(sourceType); return newTriple; } private GraphPatternElement addGraphPatternElementAtEnd(GraphPatternElement head, GraphPatternElement newTail) { if (head != null) { GraphPatternElement lastElement = getLastGraphPatternElement(head); lastElement.setNext(newTail); } else { head = newTail; } return head; } private GraphPatternElement getLastGraphPatternElement(GraphPatternElement pattern) { while (pattern.getNext() != null) { pattern = pattern.getNext(); } return pattern; } /** * Method to find all of the variables in a graph pattern that might be the implied select variables of a query * @param pattern * @return */ public Set<VariableNode> getSelectVariables(List<GraphPatternElement> patterns) { Set<VariableNode> vars = getUnboundVariables(patterns); // If we don't find an unreferenced variable, see if the pattern defines // a typed b node and get its variable. if (vars.isEmpty()) { for (int i = 0; i < patterns.size(); i++) { GraphPatternElement pattern = patterns.get(i); Set<VariableNode> moreVars = getSelectVariables(pattern); if (moreVars != null && moreVars.size() > 0) { vars.addAll(moreVars); } } } return vars; } public Set<VariableNode> getSelectVariables(GraphPatternElement pattern) { Set<VariableNode> vars = new LinkedHashSet<VariableNode>(); if (pattern instanceof TripleElement) { TripleElement triple = (TripleElement) pattern; if (triple.getSubject() instanceof VariableNode && triple.getPredicate() instanceof RDFTypeNode) { VariableNode var = (VariableNode) triple.getSubject(); vars.add(var); } else if (triple.getSubject() instanceof VariableNode) { vars.add(((VariableNode)triple.getSubject())); } else if (triple.getObject() instanceof VariableNode) { vars.add(((VariableNode)triple.getObject())); } else if (triple.getPredicate() instanceof VariableNode) { vars.add(((VariableNode)triple.getPredicate())); } } else if (pattern instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)pattern).getArguments(); if (args != null) { // right now we have no mechanism to know which variables are unbound so // assume the last one is // TODO Node arg = args.get(args.size() - 1); if (arg instanceof VariableNode) { vars.add((VariableNode) arg); } } } else if (pattern instanceof Junction) { Object lhs = ((Junction)pattern).getLhs(); Object rhs = ((Junction)pattern).getRhs(); if (lhs instanceof GraphPatternElement) { Set<VariableNode> lhsvars = getSelectVariables((GraphPatternElement) lhs); if (lhsvars != null) { vars.addAll(lhsvars); } } if (rhs instanceof GraphPatternElement) { Set<VariableNode> rhsvars = getSelectVariables((GraphPatternElement) rhs); if (rhsvars != null) { vars.addAll(rhsvars); } } } return vars; } private Set<VariableNode> getUnboundVariables(List<GraphPatternElement> patterns) { Set<VariableNode> vars = new LinkedHashSet<VariableNode>(); // We need to find any unreferenced variables in the pattern. for (int i = 0; i < patterns.size(); i++) { GraphPatternElement gpe = patterns.get(i); if (gpe instanceof TripleElement) { // Check the object of each triple to see if it has a variable // node with zero references. TripleElement triple = (TripleElement) gpe; Node subjNode = triple.getSubject(); if (subjNode instanceof VariableNode) { VariableNode var = (VariableNode) subjNode; if (var.getNumReferences() == 0) { vars.add(var); } } else if (subjNode instanceof NamedNode && ((NamedNode)subjNode).getNodeType().equals(NodeType.VariableNode)) { vars.add(new VariableNode(((NamedNode)subjNode).getName())); } Node objNode = triple.getObject(); if (objNode instanceof VariableNode) { VariableNode var = (VariableNode) objNode; if (var.getNumReferences() == 0) { vars.add(var); } } else if (objNode instanceof NamedNode && ((NamedNode)objNode).getNodeType().equals(NodeType.VariableNode)) { vars.add(new VariableNode(((NamedNode)objNode).getName())); } } else if (gpe instanceof BuiltinElement) { // Check the arguments of each builtin to see if it has a // variable node with zero references. BuiltinElement builtin = (BuiltinElement) gpe; for (Node argument : builtin.getArguments()) { if (argument instanceof VariableNode) { VariableNode var = (VariableNode) argument; if (var.getNumReferences() == 0) { vars.add(var); } } } } } return vars; } /** * This method flattens out GraphPatternElement linked lists into a regular List * @param test * @param object */ public void postProcessTest(Test test, TestStatement object) { try { Object lhs = test.getLhs(); if (lhs instanceof List<?> && ((List<?>)lhs).size() > 0) { if (((List<?>)lhs).get(0) instanceof GraphPatternElement) { flattenLinkedList((List<GraphPatternElement>)lhs); } if (lhs instanceof List<?>) { if (((List<?>)lhs).size() == 1) { lhs = ((List<?>)lhs).get(0); test.setLhs(lhs); } else if (((List<?>)lhs).size() == 2 && ((List<?>)lhs).get(1) instanceof BuiltinElement && ((BuiltinElement)((List<?>)lhs).get(1)).isCreatedFromInterval()) { test.setLhs(((List<?>)lhs).get(0)); test.setCompName(((BuiltinElement)((List<?>)lhs).get(1)).getFuncType()); test.setRhs(((BuiltinElement)((List<?>)lhs).get(1)).getArguments().get(1)); } } } else if (lhs instanceof GraphPatternElement && ((GraphPatternElement)lhs).getNext() != null) { boolean done = false; if ((((GraphPatternElement)lhs).getNext() instanceof BuiltinElement)) { // there is a builtin next BuiltinElement be = (BuiltinElement) ((GraphPatternElement)lhs).getNext(); if (isComparisonBuiltin(be.getFuncName())) { ((GraphPatternElement)lhs).setNext(null); if (be.getArguments().size() > 1) { if (be.getArguments().get(0) instanceof VariableNode) { test.setRhs(be.getArguments().get(1)); } else { // this is of the form V is P of S so comparison must be reversed reverseBuiltinComparisonDirection(be); test.setRhs(be.getArguments().get(0)); } } else { addError(new IFTranslationError("A BuiltinElement in a Test is a comparison (" + be.getFuncName() + ") but has less than two arguemnts (" + be.toString() + ")")); } test.setCompName(be.getFuncName()); done = true; } } if (!done) { List<GraphPatternElement> newLhs = new ArrayList<GraphPatternElement>(); newLhs.add((GraphPatternElement) lhs); test.setLhs(flattenLinkedList(newLhs)); } } else if (lhs instanceof BuiltinElement && isModifiedTriple(((BuiltinElement)lhs).getFuncType())) { List<Node> args = ((BuiltinElement)lhs).getArguments(); if (args != null && args.size() == 2) { test.setLhs(args.get(1)); test.setRhs(args.get(0)); test.setCompName(((BuiltinElement)lhs).getFuncName()); } } if (test.getRhs() instanceof ProxyNode) { test.setRhs(((ProxyNode)test.getRhs()).getProxyFor()); } Object rhs = test.getRhs(); if (rhs instanceof List<?> && ((List<?>)rhs).size() > 0) { if (((List<?>)rhs).get(0) instanceof GraphPatternElement) { flattenLinkedList((List<GraphPatternElement>)rhs); } } else if (rhs instanceof GraphPatternElement && ((GraphPatternElement)rhs).getNext() != null) { boolean done = false; if ((((GraphPatternElement)rhs).getNext() instanceof BuiltinElement)) { BuiltinElement be = (BuiltinElement) ((GraphPatternElement)rhs).getNext(); if (isComparisonBuiltin(be.getFuncName())) { ((GraphPatternElement)rhs).setNext(null); test.setLhs(be.getArguments().get(1)); test.setCompName(be.getFuncName()); done = true; } } if (!done) { List<GraphPatternElement> newRhs = new ArrayList<GraphPatternElement>(); newRhs.add((GraphPatternElement) rhs); test.setRhs(flattenLinkedList(newRhs)); } } if (test.getLhs() instanceof ProxyNode) { test.setLhs(((ProxyNode)test.getLhs()).getProxyFor()); } if (test.getCompType() != null && test.getCompType().equals(ComparisonType.Eq) && test.getLhs() != null && test.getRhs() != null && test.getLhs() instanceof NamedNode && test.getRhs() instanceof List<?>) { if (test.getRhsVariables() != null && test.getRhsVariables().size() == 1) { String rhsvar = test.getRhsVariables().get(0).getName(); List<?> rhslist = (List<?>) test.getRhs(); boolean allPass = true; for (int i = 0; i < rhslist.size(); i++) { Object anrhs = rhslist.get(i); if (!(anrhs instanceof TripleElement)) { allPass = false; break; } else { Node subj = ((TripleElement)anrhs).getSubject(); if (!(subj instanceof VariableNode) || !(((VariableNode)subj).getName().equals(rhsvar))) { allPass = false; break; } } } if (allPass) { for (int i = 0; i < rhslist.size(); i++) { TripleElement triple = (TripleElement) rhslist.get(i); triple.setSubject((Node) test.getLhs()); } test.setLhs(test.getRhs()); test.setRhs(null); test.setRhsVariables(null); test.setCompName((String)null); } } } // this is a validity checking section TripleElement singleTriple = null; if (test.getLhs() instanceof TripleElement && test.getRhs() == null && ((TripleElement)test.getLhs()).getNext() == null) { singleTriple = (TripleElement) test.getLhs(); } else if (test.getRhs() instanceof TripleElement && test.getLhs() == null && ((TripleElement)test.getRhs()).getNext() == null) { singleTriple = (TripleElement) test.getRhs(); } if (singleTriple != null) { // a single triple test should not have any variables in it if (singleTriple.getSubject() instanceof VariableNode || singleTriple.getPredicate() instanceof VariableNode || singleTriple.getObject() instanceof VariableNode) { addError(new IFTranslationError("Test is a single triple to be matched; should not contain variables.", object)); } else { try { // modelManager.validateStatement(singleTriple.getSubject(), singleTriple.getPredicate(), singleTriple.getObject()); } catch (Throwable t) { // try to validate but don't do anything on Exception } } } } catch (Exception e) { e.printStackTrace(); } } public static void reverseBuiltinComparisonDirection(BuiltinElement be) { if (be.getFuncType().equals(BuiltinType.LT)) { be.setFuncName(">"); } else if (be.getFuncType().equals(BuiltinType.LTE)) { be.setFuncName(">="); } else if (be.getFuncType().equals(BuiltinType.GT)){ be.setFuncName("<"); } else if (be.getFuncType().equals(BuiltinType.GTE)) { be.setFuncName("<="); } } public static void builtinComparisonComplement(BuiltinElement be) { if (be.getFuncType().equals(BuiltinType.LT)) { be.setFuncName(">="); } else if (be.getFuncType().equals(BuiltinType.LTE)) { be.setFuncName(">"); } else if (be.getFuncType().equals(BuiltinType.GT)){ be.setFuncName("<="); } else if (be.getFuncType().equals(BuiltinType.GTE)) { be.setFuncName("<"); } } public static boolean isComparisonBuiltin(String builtinName) { ComparisonType[] types = ComparisonType.values(); for (ComparisonType type : types) { if (type.matches(builtinName)) { return true; } } return false; } public Rule postProcessRule(Rule rule, EObject object) throws TranslationException { clearCruleVariableTypedOutput(); try { // do this first so that the arguments don't change before these are applied addImpliedAndExpandedProperties(rule); // now do this before any null subjects that are the same variable get replaced with different variables. addMissingCommonVariables(rule); // now add other missing patterns, if needed // addMissingTriplePatterns(rule); } catch (InvalidNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InvalidTypeException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (TranslationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // convert givens linked list to array; expand conjunctions List<GraphPatternElement> givens = flattenRuleJunctions(rule.getGivens()); if (givens != null) { Object results; try { results = expandProxyNodes(givens, false, true); if (results instanceof List<?>) { if (((List<?>)results).size() == 1 && ((List<?>)results).get(0) instanceof Junction) { results = junctionToList((Junction) ((List<?>)results).get(0)); } rule.setGivens((List<GraphPatternElement>) results); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { retiredProxyNodes.clear(); } // convert ifs linked list to array; expand conjunctions List<GraphPatternElement> ifs = flattenRuleJunctions(rule.getIfs()); if (ifs != null) { Object results; try { results = expandProxyNodes(ifs, false, false); if (results instanceof List<?>) { if (((List<?>)results).size() == 1 && ((List<?>)results).get(0) instanceof Junction) { results = junctionToList((Junction) ((List<?>)results).get(0)); } rule.setIfs((List<GraphPatternElement>) results); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // now process conclusions List<GraphPatternElement> thens = flattenRuleJunctions(rule.getThens()); if (thens != null) { Object results; try { results = expandProxyNodes(thens, true, false); if (results instanceof List<?>) { if (((List<?>)results).size() == 1 && ((List<?>)results).get(0) instanceof Junction) { results = junctionToList((Junction) ((List<?>)results).get(0)); } for (int i = 0; i < ((List<?>)results).size(); i++) { GraphPatternElement tgpe = (GraphPatternElement) ((List<?>)results).get(i); results = moveEmbeddedGPEsToIfs(rule, (List<?>) results, tgpe); } rule.setThens((List<GraphPatternElement>) results); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { throw e; } } try { removeDuplicateElements(rule); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rule; } private void addMissingCommonVariables(Rule rule) throws TranslationException { // Find triples with null subjects List<TripleElement> nullSubjects = null; if (rule.getGivens() != null) { nullSubjects = getNullSubjectTriples(rule.getGivens(), nullSubjects); } if (rule.getIfs() != null) { nullSubjects = getNullSubjectTriples(rule.getIfs(), nullSubjects); } if (rule.getThens() != null) { nullSubjects = getNullSubjectTriples(rule.getThens(), nullSubjects); } if (nullSubjects != null) { Map<NamedNode,List<Resource>> cache = new HashMap<NamedNode, List<Resource>>(); for (int i = 0; i < nullSubjects.size(); i++) { Node prop = nullSubjects.get(i).getPredicate(); if (prop instanceof NamedNode) { Property p = getTheJenaModel().getProperty(((NamedNode)prop).toFullyQualifiedString()); StmtIterator dmnitr = getTheJenaModel().listStatements(p, RDFS.domain, (RDFNode)null); if (dmnitr.hasNext()) { List<Resource> dmnclses = new ArrayList<Resource>(); while (dmnitr.hasNext()) { RDFNode dmn = dmnitr.nextStatement().getObject(); if (dmn.isURIResource()) { dmnclses.add((Resource) dmn); } else if (dmn.canAs(OntClass.class)&& dmn.as(OntClass.class).isUnionClass()) { dmnclses.addAll(getUnionClassMembers(dmn.as(OntClass.class).asUnionClass())); } else { throw new TranslationException("Unhandled case"); } } cache.put((NamedNode)prop, dmnclses); } } } for (int i = 0; i < nullSubjects.size(); i++) { List<Resource> dmns1 = cache.get(nullSubjects.get(i).getPredicate()); for (int j = i +1; j < nullSubjects.size(); j++) { boolean matched = false; List<Resource> dmns2 = cache.get(nullSubjects.get(j).getPredicate()); for (int k = 0; k < dmns2.size(); k++) { Resource dmn2 = dmns2.get(k); if (dmns1.contains(dmn2)) { // there's a match--connect them VariableNode cmnvar = new VariableNode(getNewVar()); nullSubjects.get(i).setSubject(cmnvar); nullSubjects.get(j).setSubject(cmnvar); matched = true; break; } else if (dmn2.canAs(OntClass.class)) { for (int l = 0; l < dmns1.size(); l++) { Resource dmn1 = dmns1.get(l); if (dmn1.canAs(OntClass.class)) { if (SadlUtils.classIsSuperClassOf(dmn1.as(OntClass.class), dmn2.as(OntClass.class))) { VariableNode cmnvar = new VariableNode(getNewVar()); nullSubjects.get(i).setSubject(cmnvar); nullSubjects.get(j).setSubject(cmnvar); matched = true; break; } else if (SadlUtils.classIsSuperClassOf(dmn2.as(OntClass.class), dmn1.as(OntClass.class))) { VariableNode cmnvar = new VariableNode(getNewVar()); nullSubjects.get(i).setSubject(cmnvar); nullSubjects.get(j).setSubject(cmnvar); matched = true; break; } } } } } if (matched) { continue; } } } } } private List<OntClass> getUnionClassMembers(UnionClass unionClass) { List<OntClass> members = new ArrayList<OntClass>(); ExtendedIterator<? extends OntClass> ucitr = unionClass.listOperands(); while (ucitr.hasNext()) { OntClass uccls = ucitr.next(); if (uccls.isURIResource()) { members.add(uccls); } else if (uccls.isUnionClass()) { members.addAll(getUnionClassMembers(uccls.asUnionClass())); } } return members; } private List<TripleElement> getNullSubjectTriples(List<GraphPatternElement> gpes, List<TripleElement> nullSubjects) { for (int i = 0; i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); nullSubjects = getNullSubjectTriples(nullSubjects, gpe); } return nullSubjects; } private List<TripleElement> getNullSubjectTriples(List<TripleElement> nullSubjects, GraphPatternElement gpe) { if (gpe instanceof TripleElement && ((TripleElement)gpe).getSubject() == null) { if (nullSubjects == null) { nullSubjects = new ArrayList<TripleElement>(); } nullSubjects.add((TripleElement) gpe); } else { if (gpe instanceof TripleElement && ((TripleElement)gpe).getSubject() instanceof ProxyNode) { nullSubjects = getNullSubjectTriples(nullSubjects, (GraphPatternElement)((ProxyNode)((TripleElement)gpe).getSubject()).getProxyFor()); } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int i = 0; args != null && i < args.size(); i++) { if (args.get(i) instanceof ProxyNode) { nullSubjects = getNullSubjectTriples(nullSubjects, (GraphPatternElement)((ProxyNode)args.get(i)).getProxyFor()); } } } } return nullSubjects; } private Rule addImpliedAndExpandedProperties(Rule rule) throws InvalidNameException, InvalidTypeException, TranslationException { boolean clearPreviouslyRetired = true; // must clear on first call List<GraphPatternElement> gvns = rule.getGivens(); if (gvns != null) { addImpliedAndExpandedProperties(gvns); clearPreviouslyRetired = false; } List<GraphPatternElement> ifs = rule.getIfs(); if (ifs != null) { addImpliedAndExpandedProperties(ifs); clearPreviouslyRetired = false; } List<GraphPatternElement> thens = rule.getThens(); if (thens != null) { addImpliedAndExpandedProperties(thens); } return rule; } protected void addImpliedAndExpandedProperties(List<GraphPatternElement> fgpes) throws InvalidNameException, InvalidTypeException, TranslationException { // List<GraphPatternElement> fgpes = flattenLinkedList(gpes); for (int i = 0; i < fgpes.size(); i++) { GraphPatternElement gpeback = addImpliedAndExpandedProperties(fgpes.get(i)); fgpes.set(i, gpeback); } } protected GraphPatternElement addImpliedAndExpandedProperties(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { boolean processed = false; if (gpe.getExpandedPropertiesToBeUsed() != null) { gpe = applyExpandedProperties(gpe); processed = true; } if (!processed) { if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int i = 0; args != null && i < args.size(); i++ ) { Node arg = args.get(i); if (arg instanceof ProxyNode) { GraphPatternElement gpeback = addImpliedAndExpandedProperties((GraphPatternElement)((ProxyNode)arg).getProxyFor()); ((ProxyNode)arg).setProxyFor(gpeback); } } } else if (gpe instanceof TripleElement) { Node pred = ((TripleElement)gpe).getPredicate(); if (pred instanceof NamedNode && ((NamedNode)pred).getImpliedPropertyNode() != null) { TripleElement newTriple = new TripleElement(null, ((TripleElement)gpe).getPredicate(), null); newTriple.setPredicate(((NamedNode)pred).getImpliedPropertyNode()); newTriple.setObject(((TripleElement)gpe).getObject()); ((TripleElement)gpe).setObject(SadlModelProcessor.nodeCheck(newTriple)); ((NamedNode)pred).setImpliedPropertyNode(null); } } else if (gpe instanceof Junction) { Object lhs = ((Junction) gpe).getLhs(); if (lhs instanceof ProxyNode) { ((Junction)gpe).setLhs(SadlModelProcessor.nodeCheck(addImpliedAndExpandedProperties(((ProxyNode)lhs).getProxyFor()))); } else { throw new TranslationException("Junction must contain only ProxyNode as left and right."); } Object rhs = ((Junction) gpe).getRhs(); if (rhs instanceof ProxyNode) { ((Junction)gpe).setRhs(SadlModelProcessor.nodeCheck(addImpliedAndExpandedProperties(((ProxyNode)rhs).getProxyFor()))); } else { throw new TranslationException("Junction must contain only ProxyNode as left and right."); } } } return gpe; } //Need to update for implied properties being moved off graph pattern elements? private void applyLeftImpliedProperty(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { NamedNode lip = null; //gpe.getLeftImpliedPropertyUsed(); if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() == null || ((BuiltinElement)gpe).getArguments().size() != 2) { throw new TranslationException("Implied properties can't be applied to a BuiltinElement with other than 2 arguments"); } Node arg0 = ((BuiltinElement)gpe).getArguments().get(0); if (arg0 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg0))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg0); arg0 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple = new TripleElement(arg0, lip, null); arg0 = SadlModelProcessor.nodeCheck(newTriple); ((BuiltinElement)gpe).getArguments().set(0, arg0); for (int i = 0; i < ((BuiltinElement)gpe).getArguments().size(); i++) { Node agi = ((BuiltinElement)gpe).getArguments().get(i); if (agi instanceof ProxyNode && ((ProxyNode)agi).getProxyFor() instanceof BuiltinElement) { addImpliedAndExpandedProperties((BuiltinElement)((ProxyNode)agi).getProxyFor()); } } //((BuiltinElement)gpe).setLeftImpliedPropertyUsed(null); } else if (gpe instanceof TripleElement) { TripleElement newTriple = new TripleElement(((TripleElement)gpe).getSubject(), ((TripleElement)gpe).getPredicate(), null); ((TripleElement)gpe).setSubject(SadlModelProcessor.nodeCheck(newTriple)); ((TripleElement)gpe).setPredicate(lip); //gpe.setRightImpliedPropertyUsed(null); } else { throw new TranslationException("Unexpected GraphPatternElement (" + gpe.getClass().getCanonicalName() + ") encountered applying implied property"); } } //Need to update for implied properties being moved off graph pattern elements? private void applyRightImpliedProperty(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { NamedNode rip = null; //gpe.getRightImpliedPropertyUsed(); if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() == null || ((BuiltinElement)gpe).getArguments().size() != 2) { throw new TranslationException("Implied properties can't be applied to a BuiltinElement with other than 2 arguments"); } Node arg1 = ((BuiltinElement)gpe).getArguments().get(1); if (arg1 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg1))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg1); arg1 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple = new TripleElement(arg1, rip, null); arg1 = SadlModelProcessor.nodeCheck(newTriple); ((BuiltinElement)gpe).getArguments().set(1, arg1); for (int i = 0; i < ((BuiltinElement)gpe).getArguments().size(); i++) { Node agi = ((BuiltinElement)gpe).getArguments().get(i); if (agi instanceof ProxyNode && ((ProxyNode)agi).getProxyFor() instanceof BuiltinElement) { addImpliedAndExpandedProperties((BuiltinElement)((ProxyNode)agi).getProxyFor()); } } //gpe.setRightImpliedPropertyUsed(null); } else if (gpe instanceof TripleElement) { Node objNode = ((TripleElement)gpe).getObject(); TripleElement newTriple = new TripleElement(objNode, rip, null); ((TripleElement)gpe).setObject(SadlModelProcessor.nodeCheck(newTriple)); //gpe.setRightImpliedPropertyUsed(null); } else { throw new TranslationException("Unexpected GraphPatternElement (" + gpe.getClass().getCanonicalName() + ") encountered applying implied property"); } } private GraphPatternElement applyExpandedProperties(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { List<NamedNode> eps = gpe.getExpandedPropertiesToBeUsed(); List<GraphPatternElement> junctionMembers = null; JunctionType jcttype = JunctionType.Conj; if (gpe instanceof BuiltinElement && eps.size() > 1) { if (((BuiltinElement)gpe).getFuncType().equals(BuiltinType.NotEqual)) { if (((BuiltinElement)gpe).getFuncName().equals("assign")) { throw new TranslationException("Can't have disjunction in assignment"); } jcttype = JunctionType.Disj; } junctionMembers = new ArrayList<GraphPatternElement>(); } if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() == null || ((BuiltinElement)gpe).getArguments().size() != 2) { throw new TranslationException("Expanded properties can't be applied to a BuiltinElement with other than 2 arguments"); } int expPropCntr = 0; List<Node> originalArgs = new ArrayList<Node>(); for (NamedNode ep : eps) { BuiltinElement workingGpe = (BuiltinElement) gpe; if (expPropCntr == 0) { for (int i = 0; i < ((BuiltinElement)workingGpe).getArguments().size(); i++) { Node agi = ((BuiltinElement)workingGpe).getArguments().get(i); if (agi instanceof ProxyNode && ((ProxyNode)agi).getProxyFor() instanceof BuiltinElement) { addImpliedAndExpandedProperties((BuiltinElement)((ProxyNode)agi).getProxyFor()); } originalArgs.add(agi); } } else { workingGpe = new BuiltinElement(); workingGpe.setFuncName(((BuiltinElement) gpe).getFuncName()); workingGpe.setFuncType(((BuiltinElement) gpe).getFuncType()); for (int i = 0; i < ((BuiltinElement) gpe).getArguments().size(); i++) { workingGpe.addArgument(originalArgs.get(i)); } } Node arg0 = ((BuiltinElement)workingGpe).getArguments().get(0); if (arg0 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg0))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg0); arg0 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple1 = new TripleElement(arg0, ep, null); arg0 = SadlModelProcessor.nodeCheck(newTriple1); ((BuiltinElement)workingGpe).getArguments().set(0, arg0); Node arg1 = ((BuiltinElement)workingGpe).getArguments().get(1); if (arg1 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg1))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg1); arg1 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple2 = new TripleElement(arg1, ep, null); arg1 = SadlModelProcessor.nodeCheck(newTriple2); ((BuiltinElement)workingGpe).getArguments().set(1, arg1); ((BuiltinElement)workingGpe).setExpandedPropertiesToBeUsed(null); if (junctionMembers != null) { junctionMembers.add(workingGpe); } expPropCntr++; } if (junctionMembers != null) { if (jcttype.equals(JunctionType.Conj)) { gpe = (GraphPatternElement) listToAnd(junctionMembers).get(0); } else { gpe = listToOr(junctionMembers); } } } else if (gpe instanceof TripleElement) { Node objNode = ((TripleElement)gpe).getObject(); if (!(objNode instanceof ConstantNode && ((ConstantNode)objNode).getName().equals(SadlConstants.CONSTANT_NONE))) { int i = 0; } } else { // expanded properties can only apply to equality/inequality and assignment, so no other GraphPatternElement type should be encountered throw new TranslationException("Unexpeced non-BuiltinElement has expanded properties"); } gpe.setExpandedPropertiesToBeUsed(null); return gpe; } private TripleElement singlePropertyToTriple(NamedNode prop) { VariableNode nvar = null; //new VariableNode(getNewVar()); TripleElement newTriple = new TripleElement(nvar, prop, null); return newTriple; } private List<NamedNode> getNamedNodeList(List<NamedNode> found, GraphPatternElement gpe) { if (gpe instanceof TripleElement) { found = addNamedNode(found, ((TripleElement)gpe).getSubject()); found = addNamedNode(found, ((TripleElement)gpe).getObject()); } else if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() != null) { for (int i = 0; i < ((BuiltinElement)gpe).getArguments().size(); i++) { found = addNamedNode(found, ((BuiltinElement)gpe).getArguments().get(i)); } } } else if (gpe instanceof Junction) { Object lhs = ((Junction)gpe).getLhs(); if (lhs instanceof Node) { found = addNamedNode(found, (Node) lhs); } Object rhs = ((Junction)gpe).getRhs(); if (rhs instanceof Node) { found = addNamedNode(found, (Node) rhs); } } return found; } private List<NamedNode> addNamedNode(List<NamedNode> found, Node node) { if (node instanceof NamedNode && !(node instanceof VariableNode)) { if (found == null) found = new ArrayList<NamedNode>(); found.add((NamedNode)node); } return found; } private List<GraphPatternElement> decorateCRuleVariables(List<GraphPatternElement> gpes, boolean isRuleThen) { for (int i = 0; i < gpes.size(); i++) { Object premise = gpes.get(i); if (premise instanceof BuiltinElement) { if (((BuiltinElement)premise).getArguments() != null) { for (Node n: ((BuiltinElement)premise).getArguments()) { if (n instanceof VariableNode && ((VariableNode)n).isCRulesVariable() && ((VariableNode)n).getType() != null && !isCruleVariableInTypeOutput((VariableNode) n)) { TripleElement newTypeTriple = new TripleElement(n, new RDFTypeNode(), ((VariableNode)n).getType()); gpes.add(++i, newTypeTriple); addCruleVariableToTypeOutput((VariableNode) n); if (!isRuleThen) { try { i = addNotEqualsBuiltinsForNewCruleVariable(gpes, i, (VariableNode) n); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } else if (premise instanceof TripleElement) { try { TripleElement gpe = (TripleElement) premise; Node subj = gpe.getSubject(); Node obj = gpe.getObject(); if (subj instanceof VariableNode && ((VariableNode)subj).isCRulesVariable() && ((VariableNode)subj).getType() != null && !isCruleVariableInTypeOutput((VariableNode) subj)) { TripleElement newTypeTriple = new TripleElement(subj, new RDFTypeNode(), ((VariableNode)subj).getType()); gpes.add(i++, newTypeTriple); addCruleVariableToTypeOutput((VariableNode) subj); if (!isRuleThen) { i = addNotEqualsBuiltinsForNewCruleVariable(gpes, i, (VariableNode) subj); } } if (obj instanceof VariableNode && ((VariableNode)obj).isCRulesVariable() && ((VariableNode)obj).getType() != null && !isCruleVariableInTypeOutput((VariableNode) obj)) { TripleElement newTypeTriple = new TripleElement(obj, new RDFTypeNode(), ((VariableNode)obj).getType()); gpes.add(++i, newTypeTriple); addCruleVariableToTypeOutput((VariableNode) obj); if (!isRuleThen) { i = addNotEqualsBuiltinsForNewCruleVariable(gpes, i, (VariableNode) obj); } } } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return gpes; } private List<GraphPatternElement> flattenRuleJunctions(List<GraphPatternElement> lst) { if (lst == null) return null; List<GraphPatternElement> results = new ArrayList<GraphPatternElement>(); for (int i = 0; i < lst.size(); i++) { GraphPatternElement gpe = lst.get(i); if (gpe instanceof Junction) { if (((Junction)gpe).getJunctionType().equals(JunctionType.Conj)) { try { results.addAll(flattenRuleJunction((Junction) gpe)); } catch (TranslationException e) { addError(new IFTranslationError(e.getMessage(), e)); } } else { // addError(new IFTranslationError("Disjunction not supported in rules at this time")); // leave this error checking for the final translations step--some rules may support disjunction results.add(gpe); } } // else if (gpe instanceof BuiltinElement && // ((BuiltinElement)gpe).getFuncName() != null && ((BuiltinElement)gpe).getFuncName().equals("and")) { // List<Node> args = ((BuiltinElement)gpe).getArguments(); // for (int j = 0; j <= args.size(); j++) { // Node nj = args.get(j); // } // } else { results.add(gpe); } } return results; } private List<GraphPatternElement> flattenRuleJunction(Junction jct) throws TranslationException { List<GraphPatternElement>results = new ArrayList<GraphPatternElement>(); if (!jct.getJunctionType().equals(JunctionType.Conj)) { // addError(new IFTranslationError("Disjunction not supported in rules at this time")); // this is up to the target translator to decide, not the Intermediate Form Translator results.add(jct); return results; } Object lhs = jct.getLhs(); if (lhs instanceof ProxyNode) { lhs = ((ProxyNode)lhs).getProxyFor(); } if (lhs instanceof Junction) { results.addAll(flattenRuleJunction((Junction)lhs)); } else if (lhs instanceof GraphPatternElement){ results.add((GraphPatternElement) lhs); } else if (lhs instanceof List<?>) { for (int i = 0; i < ((List<?>)lhs).size(); i++) { results.add((GraphPatternElement) ((List<?>)lhs).get(i)); } } else { throw new TranslationException("Encountered non-GraphPatternElement during rule translation"); } Object rhs = jct.getRhs(); if (rhs instanceof ProxyNode) { rhs = ((ProxyNode)rhs).getProxyFor(); } if (rhs instanceof Junction) { results.addAll(flattenRuleJunction((Junction)rhs)); } else if (rhs instanceof GraphPatternElement) { results.add((GraphPatternElement)rhs); } else if (rhs instanceof List<?>) { for (int i = 0; i < ((List<?>)rhs).size(); i++) { results.add((GraphPatternElement) ((List<?>)rhs).get(i)); } } else { throw new TranslationException("Encountered non-GraphPatternElement during rule translation"); } return results; } /** * Method to remove GPE's with isEmbedded true from thens to ifs * * @param rule * @param results * @param tgpe * @return * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ private List<?> moveEmbeddedGPEsToIfs(Rule rule, List<?> results, GraphPatternElement tgpe) throws InvalidNameException, InvalidTypeException, TranslationException { if (tgpe.isEmbedded()) { results.remove(tgpe); rule.getIfs().add(tgpe); } else { if (tgpe instanceof Junction) { int idx = results.indexOf(tgpe); GraphPatternElement newtgpe = moveEmbeddedFromJunction(rule, (Junction)tgpe); if (newtgpe == null) { results.remove(idx); } else if (newtgpe != tgpe) { ((List<GraphPatternElement>)results).set(idx, newtgpe); } } } return results; } /** * Method to move all embedded GPEs in a Junction to the rule ifs and return whatever should be put in * the Junction's place or null if nothing. * * @param rule * @param tgpe * @return * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ private GraphPatternElement moveEmbeddedFromJunction(Rule rule, Junction tgpe) throws InvalidNameException, InvalidTypeException, TranslationException { boolean lhsRemoved = false; boolean rhsRemoved = false; Object lhs = ((Junction)tgpe).getLhs(); Object rhs = ((Junction)tgpe).getRhs(); if (lhs instanceof GraphPatternElement && ((GraphPatternElement)lhs).isEmbedded()) { rule.getIfs().add((GraphPatternElement) lhs); lhsRemoved = true; } else if (lhs instanceof Junction) { lhs = moveEmbeddedFromJunction(rule, (Junction) lhs); } if (rhs instanceof GraphPatternElement && ((GraphPatternElement)rhs).isEmbedded()) { rule.getIfs().add((GraphPatternElement) rhs); rhsRemoved = true; } else if (rhs instanceof Junction) { rhs = moveEmbeddedFromJunction(rule, (Junction) rhs); } if (lhsRemoved && rhsRemoved) { return null; } if (lhsRemoved) { return (GraphPatternElement) rhs; } if (rhsRemoved) { return (GraphPatternElement) lhs; } tgpe.setLhs(SadlModelProcessor.nodeCheck(lhs)); tgpe.setRhs(SadlModelProcessor.nodeCheck(rhs)); return tgpe; } /** * This Map keeps track of the ProxyNodes that have been retired by GraphPatternElements, allowing the retired * ProxyNode and its associated variable to be reused when that GraphPatternElement is revisited in another ProxyNode. */ private Map<GraphPatternElement, ProxyNode> retiredProxyNodes = new HashMap<GraphPatternElement, ProxyNode>(); /** * Top-level method for expanding ProxyNodes * * @param pattern * @param clearPreviousRetired TODO * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ public Object expandProxyNodes(Object pattern, boolean isRuleThen, boolean clearPreviousRetired) throws InvalidNameException, InvalidTypeException, TranslationException { if (clearPreviousRetired) { retiredProxyNodes.clear(); } List<GraphPatternElement> patterns = new ArrayList<GraphPatternElement>(); if (pattern instanceof List<?>) { for (int i = 0; i < ((List<?>)pattern).size(); i++) { expandProxyNodes(patterns, ((List<?>)pattern).get(i), isRuleThen); } } else { Object result = expandProxyNodes(patterns, pattern, isRuleThen); if (patterns.size() == 0) { return result; } } if (patterns.size() > 0) { patterns = decorateCRuleVariables((List<GraphPatternElement>) patterns, isRuleThen); if (!(getTarget() instanceof Test) && patterns.size() > 1) { patterns = listToAnd(patterns); } } return patterns; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#listToAnd(java.util.List) */ @Override public List<GraphPatternElement> listToAnd( List<GraphPatternElement> patterns) throws InvalidNameException, InvalidTypeException, TranslationException { if (patterns == null || patterns.size() == 0) { return null; } if (patterns.size() == 1) { return patterns; } GraphPatternElement lhs = patterns.remove(0); if (lhs instanceof List<?>) { lhs = listToAnd((List<GraphPatternElement>) lhs).get(0); } Junction jand = new Junction(); jand.setJunctionName("and"); jand.setLhs(SadlModelProcessor.nodeCheck(lhs)); if (patterns.size() > 1) { patterns = listToAnd(patterns); } GraphPatternElement rhs = patterns.get(0); if (rhs instanceof List<?>) { rhs = listToAnd((List<GraphPatternElement>) rhs).get(0); } jand.setRhs(SadlModelProcessor.nodeCheck(rhs)); patterns.set(0, jand); return patterns; } private GraphPatternElement listToOr(List<GraphPatternElement> patterns) throws InvalidNameException, InvalidTypeException, TranslationException { if (patterns == null || patterns.size() == 0) { return null; } if (patterns.size() == 1) { return patterns.get(0); } GraphPatternElement lhs = patterns.remove(0); Junction jor = new Junction(); jor.setJunctionName("or"); jor.setLhs(SadlModelProcessor.nodeCheck(lhs)); GraphPatternElement rhs = listToOr(patterns); jor.setRhs(SadlModelProcessor.nodeCheck(rhs)); return jor; } /** * Second-level method for expanding ProxyNodes--this one has a list of the results passed in as an argument * @param patterns * @param pattern * @param isRuleThen * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ protected Object expandProxyNodes(List<GraphPatternElement> patterns, Object pattern, boolean isRuleThen) throws InvalidNameException, InvalidTypeException, TranslationException { if (pattern instanceof ProxyNode) { return expandProxyNodes(patterns, ((ProxyNode)pattern).getProxyFor(), isRuleThen); } if (pattern instanceof TripleElement) { return expandProxyNodes(patterns,(TripleElement)pattern, isRuleThen); } else if (pattern instanceof BuiltinElement) { return expandProxyNodes(patterns, (BuiltinElement)pattern, isRuleThen); } else if (pattern instanceof Literal) { return pattern; } else if (pattern instanceof Junction) { Object retval = null; // remember what we have so far and create a new pattern list for each side of the Junction List<GraphPatternElement> existingPatterns = patterns; List<GraphPatternElement> lhsPatterns = new ArrayList<GraphPatternElement>(); List<GraphPatternElement> rhsPatterns = new ArrayList<GraphPatternElement>(); // get the two sides Object lhs = ((Junction)pattern).getLhs(); Object rhs = ((Junction)pattern).getRhs(); // at least handle the interesting special case where they are literals if (lhs instanceof Literal) { BuiltinElement lhsbe = new BuiltinElement(); lhsbe.setFuncName("=="); lhsbe.setCreatedFromInterval(true); lhsbe.addArgument(SadlModelProcessor.nodeCheck(lhs)); ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(lhsbe)); } else { expandProxyNodes(lhsPatterns, lhs, isRuleThen); if (lhsPatterns.size() == 1) { ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(lhsPatterns.get(0))); } else if (lhsPatterns.size() < 1) { ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(lhs)); } else { ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(listToAnd(lhsPatterns).get(0))); // throw new TranslationException("LHS of a Junction should be a single GraphPatternElement: " + jctPatterns.toString()); } } if (rhs instanceof Literal) { BuiltinElement rhsbe = new BuiltinElement(); rhsbe.setFuncName("=="); rhsbe.setCreatedFromInterval(true); rhsbe.addArgument(SadlModelProcessor.nodeCheck(rhs)); retval = SadlModelProcessor.nodeCheck(rhsbe); ((Junction)pattern).setRhs(retval); } else { retval = expandProxyNodes(rhsPatterns, rhs, isRuleThen); if (rhsPatterns.size() == 1) { ((Junction)pattern).setRhs(SadlModelProcessor.nodeCheck(rhsPatterns.get(0))); } else if (rhsPatterns.size() < 1) { ((Junction)pattern).setRhs(SadlModelProcessor.nodeCheck(rhs)); } else { ((Junction)pattern).setRhs(SadlModelProcessor.nodeCheck(listToAnd(rhsPatterns).get(0))); // throw new TranslationException("RHS of a Junction should be a single GraphPatternElement: " + jctPatterns.toString()); } } patterns = existingPatterns; patterns.add((Junction)pattern); return retval; } return patterns; } /** * If a triple has a null, fill it with a variable (search the patterns list first to avoid duplicates), * add the triple to the patterns list, and return the variable. The variable also replaces the proxy node * that contained this triple. * @param patterns * @param te * @param expType * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ protected Object expandProxyNodes(List<GraphPatternElement> patterns, TripleElement te, boolean isRuleThen) throws InvalidNameException, InvalidTypeException, TranslationException { Node returnNode = null; Node retiredNode = findMatchingElementInRetiredProxyNodes(te); if (retiredNode != null && retiredNode instanceof ProxyNode) { retiredNode = ((ProxyNode)retiredNode).getReplacementNode(); } Node subj = te.getSubject(); if (subj instanceof ProxyNode) { if (retiredNode != null) { subj = returnNode = retiredNode; } else if (((ProxyNode)subj).getReplacementNode() != null) { if (!patterns.contains(((ProxyNode)subj).getProxyFor())) { patterns.add((GraphPatternElement) ((ProxyNode)subj).getProxyFor()); retiredProxyNodes.put((GraphPatternElement)((ProxyNode)subj).getProxyFor(), (ProxyNode) subj); } subj = returnNode = ((ProxyNode)subj).getReplacementNode(); } else { Object realSubj = ((ProxyNode)subj).getProxyFor(); Object subjNode = expandProxyNodes(patterns, realSubj, isRuleThen); if (subjNode == null && realSubj instanceof TripleElement) { if (((TripleElement)realSubj).getObject() instanceof VariableNode) { subjNode = ((TripleElement)realSubj).getObject(); } else if (te.getSourceType() != null && te.getSourceType().equals(TripleSourceType.SPV)) { subjNode = ((TripleElement)realSubj).getSubject(); } } ((ProxyNode)subj).setReplacementNode(SadlModelProcessor.nodeCheck(subjNode)); retiredProxyNodes.put((GraphPatternElement) realSubj, (ProxyNode)subj); subj = SadlModelProcessor.nodeCheck(subjNode); if (realSubj instanceof TripleElement && ((TripleElement)realSubj).getSourceType() != null && ((TripleElement)realSubj).getSourceType().equals(TripleSourceType.ITC)) { returnNode = subj; } } te.setSubject(subj); patterns.add(te); } else if (subj == null) { // this is a triple with a need for a variable for subject returnNode = retiredNode != null ? retiredNode : getVariableNode(subj, te.getPredicate(), te.getObject(), true); te.setSubject(returnNode); // TODO when this is nested the triple (te) needs to be inserted before the returnNode is used patterns.add(te); } Node obj = te.getObject(); if (obj instanceof ProxyNode) { int initialPatternLength = patterns == null ? 0 : patterns.size(); if (retiredNode != null) { obj = returnNode = retiredNode; } else if (((ProxyNode)obj).getReplacementNode() != null) { if (!patterns.contains(((ProxyNode)obj).getProxyFor())) { patterns.add((GraphPatternElement) ((ProxyNode)obj).getProxyFor()); retiredProxyNodes.put((GraphPatternElement)((ProxyNode)obj).getProxyFor(), (ProxyNode) obj); } obj = returnNode = ((ProxyNode)obj).getReplacementNode(); } else { Object realObj = ((ProxyNode)obj).getProxyFor(); List<GraphPatternElement> rememberedPatterns = null; if (realObj instanceof BuiltinElement && isRuleThen) { rememberedPatterns = patterns; patterns = new ArrayList<GraphPatternElement>(); } Object objNode = expandProxyNodes(patterns, realObj, isRuleThen); if (objNode == null && ((ProxyNode)obj).getReplacementNode() != null) { // This can happen because the proxy node gets processed but not returned objNode = ((ProxyNode)obj).getReplacementNode(); } if (objNode == null && (realObj instanceof BuiltinElement || (realObj instanceof Junction && ((Junction)realObj).getLhs() instanceof BuiltinElement && ((Junction)realObj).getRhs() instanceof BuiltinElement))) { List<BuiltinElement> builtins = new ArrayList<BuiltinElement>(); Node newNode = null; if (realObj instanceof BuiltinElement) { builtins.add((BuiltinElement)realObj); newNode = getVariableNode((BuiltinElement)realObj); } else { builtins.add((BuiltinElement)((Junction)realObj).getLhs()); newNode = getVariableNode(builtins.get(0)); builtins.add((BuiltinElement)((Junction)realObj).getRhs()); } for (int i = 0; i < builtins.size(); i++) { BuiltinElement bi = builtins.get(i); if (bi.isCreatedFromInterval()) { bi.addArgument(0, newNode); } else { bi.addArgument(newNode); } } objNode = newNode; if (isRuleThen) { addToPremises(patterns); patterns = rememberedPatterns; } } if (objNode == null) { addError(new IFTranslationError("Translation to Intermediate Form failed: " + te.toString())); } ((ProxyNode)obj).setReplacementNode(SadlModelProcessor.nodeCheck(objNode)); // TODO this has a problem, run on TestSadlIde/Sandbox/UnionClassInRule.sadl retiredProxyNodes.put((GraphPatternElement) ((ProxyNode)obj).getProxyFor(), (ProxyNode)obj); obj = SadlModelProcessor.nodeCheck(objNode); } te.setObject(obj); if (!patterns.contains(te)) { if (getTarget() instanceof Rule) { patterns.add(te); } else { patterns.add(Math.max(0, initialPatternLength - 1), te); } } } else if (obj == null && returnNode == null) { // if the subject was null, so returnNode is not null, don't create a variable for object and return that as // it will mess up what's up the stack returnNode = retiredNode != null ? retiredNode : getVariableNode(subj, te.getPredicate(), obj, false); te.setObject(returnNode); if (!patterns.contains(te)) { patterns.add(te); } } if (te.getNext() != null) { GraphPatternElement nextGpe = te.getNext(); te.setNext(null); if (!patterns.contains(te)) { patterns.add(te); } Object nextResult = expandProxyNodes(patterns, nextGpe, isRuleThen); // TODO we don't need to do anything with this, right? } // Special case: a pivot triple ( something type something): return the subject if (te instanceof TripleElement && (((TripleElement)te).getPredicate()) instanceof RDFTypeNode) { // this is an embedded type triple; only the subject can be a subject of the higher-level pattern if (!patterns.contains(te)) { patterns.add(te); } return ((TripleElement)te).getSubject(); } // This is to make sure that complete, self-contained triple elements are still added to the output if (!patterns.contains(te)) { patterns.add(te); } if (retiredNode != null) { return retiredNode; } return returnNode; } /** * This method is currently just a placeholder for finding variables for reuse in built-in patterns. * Currently it just creates a new variable with a new name. * @param bltin * @return */ protected VariableNode getVariableNode(BuiltinElement bltin) { if (getTarget() != null) { } return new VariableNode(getNewVar()); } /** * This method looks in the clauses of a Rule to see if there is already a triple matching the given pattern. If there is * a new variable of the same name is created (to make sure the count is right) and returned. If not a rule or no match * a new variable (new name) is created and returned. * @param subject * @param predicate * @param object * @param varIsSubject * @return */ protected VariableNode getVariableNode(Node subject, Node predicate, Node object, boolean varIsSubject) { VariableNode var = findVariableInTargetForReuse(subject, predicate, object); if (var != null) { // return new VariableNode(var.getName()); return var; } if (predicate != null) { var = new VariableNode(getNewVar()); Property prop = this.getTheJenaModel().getProperty(predicate.toFullyQualifiedString()); try { ConceptName propcn = new ConceptName(predicate.toFullyQualifiedString()); propcn.setType(ConceptType.RDFPROPERTY); // assume the most general if (varIsSubject) { // type is domain TypeCheckInfo dtci = getModelValidator().getTypeInfoFromDomain(propcn, prop, null); if (dtci != null && dtci.getTypeCheckType() != null) { Node tcitype = dtci.getTypeCheckType(); if (tcitype instanceof NamedNode) { NamedNode defn; defn = new NamedNode(((NamedNode)tcitype).toFullyQualifiedString(), ((NamedNode)tcitype).getNodeType()); var.setType(modelProcessor.validateNode(defn)); } else { addError(new IFTranslationError("Domain type did not return a ConceptName.")); } } } else { // type is range TypeCheckInfo dtci; dtci = getModelValidator().getTypeInfoFromRange(propcn, prop, null); if (dtci != null && dtci.getTypeCheckType() != null) { Node tcitype = dtci.getTypeCheckType(); if (tcitype instanceof NamedNode) { NamedNode defn; defn = new NamedNode(((NamedNode)tcitype).toFullyQualifiedString(), ((NamedNode)tcitype).getNodeType()); var.setType(modelProcessor.validateNode(defn)); } else { addError(new IFTranslationError("Range type did not return a ConceptName.")); } } } } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DontTypeCheckException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return var; } protected VariableNode findVariableInTargetForReuse(Node subject, Node predicate, Node object) { // Note: when we find a match we still create a new VariableNode with the same name in order to have the right reference counts for the new VariableNode if (getTarget() instanceof Rule) { VariableNode var = findVariableInTripleForReuse(((Rule)getTarget()).getGivens(), subject, predicate, object); if (var != null) { return var; } var = findVariableInTripleForReuse(((Rule)getTarget()).getIfs(), subject, predicate, object); if (var != null) { return var; } var = findVariableInTripleForReuse(((Rule)getTarget()).getThens(), subject, predicate, object); if (var != null) { return var; } } return null; } private JenaBasedSadlModelValidator getModelValidator() throws TranslationException { if (getModelProcessor() != null) { return getModelProcessor().getModelValidator(); } return null; } /** * Supporting method for the method above (getVariableNode(Node, Node, Node)) * @param gpes * @param subject * @param predicate * @param object * @return */ protected VariableNode findVariableInTripleForReuse(List<GraphPatternElement> gpes, Node subject, Node predicate, Node object) { if (gpes != null) { Iterator<GraphPatternElement> itr = gpes.iterator(); while (itr.hasNext()) { GraphPatternElement gpe = itr.next(); VariableNode var = findVariableInTargetForReuse(gpe, subject, predicate, object); if (var != null) { return var; } } } return null; } private VariableNode findVariableInTargetForReuse(GraphPatternElement gpe, Node subject, Node predicate, Node object) { while (gpe != null) { if (gpe instanceof TripleElement) { VariableNode var = findVariableInTripleForReuse((TripleElement)gpe, subject, predicate, object); if (var != null) { return var; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); if (args != null) { for (Node arg: args) { if (arg instanceof ProxyNode && ((ProxyNode)arg).getProxyFor() instanceof GraphPatternElement) { VariableNode var = findVariableInTargetForReuse((GraphPatternElement)((ProxyNode)arg).getProxyFor(), subject, predicate, object); if (var != null) { return var; } } } } } else if (gpe instanceof Junction) { Object lhs = ((Junction)gpe).getLhs(); if (lhs instanceof GraphPatternElement) { VariableNode var = findVariableInTargetForReuse((GraphPatternElement)lhs, subject, predicate, object); if (var != null) { return var; } } Object rhs = ((Junction)gpe).getRhs(); if (rhs instanceof GraphPatternElement) { VariableNode var = findVariableInTargetForReuse((GraphPatternElement)rhs, subject, predicate, object); if (var != null) { return var; } } } gpe = gpe.getNext(); } return null; } protected VariableNode findVariableInTripleForReuse(TripleElement tr, Node subject, Node predicate, Node object) { Node tsn = tr.getSubject(); Node tpn = tr.getPredicate(); Node ton = tr.getObject(); if (subject == null && tsn instanceof VariableNode) { if (predicate != null && predicate.equals(tpn) && object != null && object.equals(ton)) { return (VariableNode) tsn; } } if (predicate == null && tpn instanceof VariableNode) { if (subject != null && subject.equals(tsn) && object != null && object.equals(ton)) { return (VariableNode) tpn; } } if (object == null && ton instanceof VariableNode) { if (subject != null && subject.equals(tsn) && predicate != null && predicate.equals(tpn)) { return (VariableNode) ton; } } return null; } protected String getNewVar() { String proposedName = "v" + vNum; while (userDefinedVariables.contains(proposedName) // || // !modelManager.getConceptType(proposedName).equals(ConceptType.CONCEPT_NOT_FOUND_IN_MODEL) ) { vNum++; proposedName = "v" + vNum; } vNum++; return proposedName; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#setStartingVariableNumber(int) */ @Override public void setStartingVariableNumber(int vn) { vNum = vn; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#getVariableNumber() */ @Override public int getVariableNumber() { return vNum; } private Node findMatchingElementInRetiredProxyNodes(GraphPatternElement ge) { if (retiredProxyNodes != null) { if (retiredProxyNodes.get(ge) != null) { return retiredProxyNodes.get(ge); } else { if (ge instanceof TripleElement && !(((TripleElement)ge).getPredicate() instanceof RDFTypeNode)) { TripleElement te = (TripleElement) ge; Iterator<GraphPatternElement> itr = retiredProxyNodes.keySet().iterator(); while (itr.hasNext()) { GraphPatternElement gpe = itr.next(); if (gpe instanceof TripleElement && !(((TripleElement)gpe).getPredicate() instanceof RDFTypeNode)) { if ((te.getSubject() == null || te.getSubject().equals(((TripleElement)gpe).getSubject())) && (te.getPredicate() == null || te.getPredicate().equals(((TripleElement)gpe).getPredicate())) && (te.getObject() == null || te.getObject().equals(((TripleElement)gpe).getObject()))) { ProxyNode pn = retiredProxyNodes.get(gpe); return pn.getReplacementNode(); } } } } } } return null; } /** * Method to handle BuiltinElements--if the * @param patterns * @param be * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ protected Object expandProxyNodes(List<GraphPatternElement> patterns, BuiltinElement be, boolean isRuleThen) throws InvalidNameException, InvalidTypeException, TranslationException { int patternsSize = patterns != null ? patterns.size() : 0; Node returnNode = null; Node retiredNode = findMatchingElementInRetiredProxyNodes(be); boolean isNotOfEqual = false; if (isRuleThen && (be.getFuncType().equals(BuiltinType.Equal) || be.getFuncType().equals(BuiltinType.Assign)) && be.getArguments() != null && be.getArguments().size() == 2 && be.getArguments().get(0) instanceof ProxyNode && be.getArguments().get(1) instanceof ProxyNode) { ProxyNode arg1PN = (ProxyNode) be.getArguments().get(0); ProxyNode arg2PN = (ProxyNode) be.getArguments().get(1); Object realArgForThen = arg1PN.getProxyFor(); Object realArgForIfs = arg2PN.getProxyFor(); int tripleWithObjectNullCount = 0; if (realArgForThen instanceof TripleElement && realArgForIfs instanceof TripleElement) { // // args can be TripleElement only if both are and objects are both null if (((TripleElement)realArgForThen).getObject() == null) { tripleWithObjectNullCount++; } if (((TripleElement)realArgForIfs).getObject() == null) { tripleWithObjectNullCount++; } if (tripleWithObjectNullCount == 1) { addError(new IFTranslationError("Translation to Intermediate Form encountered error (" + be.toString() + "); try separating rule elements with ands.")); } } List<GraphPatternElement> moveToIfts = new ArrayList<GraphPatternElement>(); Object finalIfsVar = expandProxyNodes(moveToIfts, realArgForIfs, false); if (finalIfsVar == null && realArgForIfs instanceof BuiltinElement) { Node newNode = getVariableNode((BuiltinElement)realArgForIfs); ((BuiltinElement)realArgForIfs).addArgument(newNode); finalIfsVar = newNode; ((ProxyNode)arg1PN).setReplacementNode(SadlModelProcessor.nodeCheck(finalIfsVar)); retiredProxyNodes.put((GraphPatternElement) realArgForIfs, arg1PN); } if (realArgForThen instanceof TripleElement && ((TripleElement)realArgForThen).getObject() == null) { Object finalThensVar = expandProxyNodes(patterns, realArgForThen, isRuleThen); ((TripleElement)realArgForThen).setObject(SadlModelProcessor.nodeCheck(finalIfsVar)); if (!patterns.contains((TripleElement)realArgForThen)) { patterns.add((TripleElement)realArgForThen); } if (be.getFuncName().equals("assign")) { ((TripleElement)realArgForThen).setType(TripleModifierType.Assignment); } } else if (realArgForThen instanceof BuiltinElement && ((BuiltinElement)realArgForThen).getArguments() != null) { if (((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1) == null) { ((BuiltinElement)realArgForThen).getArguments().set(((BuiltinElement)realArgForThen).getArguments().size() - 1, SadlModelProcessor.nodeCheck(finalIfsVar)); } else if (((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1) instanceof ProxyNode && ((ProxyNode)((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1)).getProxyFor() instanceof TripleElement && ((TripleElement)((ProxyNode)((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1)).getProxyFor()).getObject() == null) { ((TripleElement)((ProxyNode)((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1)).getProxyFor()).setObject(SadlModelProcessor.nodeCheck(finalIfsVar)); } else { throw new TranslationException("Unhandled condition, LHS of Equal in Then isn't a BuiltinElement that needs an argument: " + realArgForThen.toString()); } } else if (realArgForThen instanceof Junction) { List<GraphPatternElement> lst = junctionToList((Junction)realArgForThen); GraphPatternElement last = lst.remove(lst.size() - 1); moveToIfts.addAll(lst); patterns.add(last); } else if (realArgForThen instanceof GraphPatternElement){ moveToIfts.add((GraphPatternElement) realArgForThen); } if (!addToPremises(moveToIfts)) { patterns.addAll(patternsSize, moveToIfts); } return null; } else if (getTarget() instanceof Rule && (be.getFuncType().equals(BuiltinType.Equal) || be.getFuncType().equals(BuiltinType.Assign))) { if (be.getArguments().size() == 2) { // this should always be true if (be.getArguments().get(0) instanceof VariableNode && be.getArguments().get(1) instanceof ProxyNode) { Object realArg2 = ((ProxyNode)be.getArguments().get(1)).getProxyFor(); if (realArg2 instanceof BuiltinElement) { ((BuiltinElement)realArg2).addArgument(be.getArguments().get(0)); // the variable goes to return from arg 2 builtin and this builtin goes away return expandProxyNodes(patterns, realArg2, isRuleThen); } else if (realArg2 instanceof TripleElement && ((TripleElement)realArg2).getObject() == null) { ((TripleElement)realArg2).setObject(be.getArguments().get(0)); // the variable goes to the object of the arg 2 triple and this builtin goes away return expandProxyNodes(patterns, realArg2, isRuleThen); } } else if ((be.getArguments().get(1) instanceof Literal || be.getArguments().get(1) instanceof ConstantNode || (be.getArguments().get(1) instanceof NamedNode && ((NamedNode)be.getArguments().get(1)).getNodeType().equals(NodeType.InstanceNode)) || be.getArguments().get(1) instanceof VariableNode) && be.getArguments().get(0) instanceof ProxyNode && ((ProxyNode)be.getArguments().get(0)).getProxyFor() instanceof TripleElement && ((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).getObject() == null) { ((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).setObject(be.getArguments().get(1)); patterns.add(((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor())); if (be.getFuncName().equals("assign")) { ((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).setType(TripleModifierType.Assignment); } return null; } } } else if (getTarget() instanceof Rule && be.getFuncType().equals(BuiltinType.Not) && be.getArguments().get(0) instanceof ProxyNode && ((ProxyNode)be.getArguments().get(0)).getProxyFor() instanceof BuiltinElement && ((BuiltinElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).getFuncType().equals(BuiltinType.Equal)) { BuiltinElement eqb = ((BuiltinElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()); Node arg0 = eqb.getArguments().get(0); Node arg1 = eqb.getArguments().get(1); if (arg0 instanceof ProxyNode && ((ProxyNode)arg0).getProxyFor() instanceof TripleElement && ((arg1 instanceof ProxyNode && ((ProxyNode)arg1).getProxyFor() instanceof TripleElement && ((TripleElement)((ProxyNode)arg1).getProxyFor()).getObject() == null)) || arg1 instanceof NamedNode){ // this is of the form: not(is(rdf(s1,p1,v1), rdf(s2,p2,null))) where v1 might also be null // so we want to transform into: rdf(s1,p1,v1), not(rdf(s2,p2,v1)) isNotOfEqual = true; } } if (retiredNode != null && retiredNode instanceof ProxyNode) { retiredNode = ((ProxyNode)retiredNode).getReplacementNode(); } List<Node> args = be.getArguments(); for (int i = 0; args != null && i < args.size(); i++) { Node arg = args.get(i); if (arg == null) { VariableNode var = new VariableNode(getNewVar()); args.set(i, var); returnNode = var; } else if (arg instanceof ProxyNode) { if (retiredNode != null) { args.set(i, retiredNode); } else { Object realArg = ((ProxyNode)arg).getProxyFor(); Object argNode = expandProxyNodes(patterns, realArg, isRuleThen); if (argNode == null) { if (realArg instanceof BuiltinElement) { if (be.getFuncType().equals(BuiltinType.Not)) { if (patterns.get(patterns.size() - 1).equals(realArg)) { // don't put in an intermediate variable for negation of a builtin--if needed the language-specific translator will need to do that // the call above to expandProxyNodes might have put the argNode into the patterns; if so remove it patterns.remove(patterns.size() - 1); if (isNotOfEqual) { TripleElement firstTriple = (TripleElement) patterns.get(patterns.size() - 2); TripleElement secondTriple = (TripleElement) patterns.get(patterns.size() - 1); if (!isRuleThen && !ruleThensContainsTriple(secondTriple)) { if (retiredProxyNodes.containsKey(secondTriple)) { retiredProxyNodes.remove(secondTriple); } secondTriple.setObject(firstTriple.getObject()); secondTriple.setType(TripleModifierType.Not); } else { TripleElement newTriple = new TripleElement(secondTriple.getSubject(), secondTriple.getPredicate(), firstTriple.getObject()); newTriple.setType(TripleModifierType.Not); patterns.add(newTriple); } } } else if (isNotOfEqual && patterns.get(patterns.size() - 1) instanceof TripleElement) { ((TripleElement)patterns.get(patterns.size() - 1)).setType(TripleModifierType.Not); } } else if (((BuiltinElement)realArg).getArguments() != null && getModelProcessor().isBuiltinMissingArgument(((BuiltinElement)realArg).getFuncName(), ((BuiltinElement)realArg).getArguments().size())){ Node newNode = getVariableNode((BuiltinElement)realArg); ((BuiltinElement)realArg).addArgument(newNode); argNode = newNode; ((ProxyNode)arg).setReplacementNode(SadlModelProcessor.nodeCheck(argNode)); retiredProxyNodes.put((GraphPatternElement) realArg, (ProxyNode)arg); args.set(i, SadlModelProcessor.nodeCheck(argNode)); } } else if (realArg instanceof TripleElement) { // don't do anything--keep proxy if triple, negate triple if "not" builtin if (patterns.get(patterns.size() - 1).equals(realArg)) { if (be.getFuncType().equals(BuiltinType.Not)) { ((TripleElement)realArg).setType(TripleModifierType.Not); return realArg; // "not" is a unary operator, so it is safe to assume this is the only argument } else if (be.getFuncName().equals(JenaBasedSadlModelProcessor.THERE_EXISTS) && ((TripleElement)realArg).getSubject() instanceof VariableNode){ be.getArguments().set(0, ((TripleElement)realArg).getSubject()); patterns.add(patterns.size() - 1, be); return null; } } } else if (realArg instanceof Junction) { patterns.remove(patterns.size() - 1); } else { throw new TranslationException("Unexpected real argument"); } } else { ((ProxyNode)arg).setReplacementNode(SadlModelProcessor.nodeCheck(argNode)); if (realArg instanceof GraphPatternElement) { retiredProxyNodes.put((GraphPatternElement) realArg, (ProxyNode)arg); } else { throw new TranslationException("Expected GraphPatternElement in ProxyNode but got " + realArg.getClass().getCanonicalName()); } args.set(i, SadlModelProcessor.nodeCheck(argNode)); } } } } if (be.getFuncName().equals(JenaBasedSadlModelProcessor.THERE_EXISTS)) { if (patterns.size() == 0) { patterns.add(be); } else { // patterns.add(patterns.size() - 1, be); patterns.add(be); } returnNode = be.getArguments() != null ? be.getArguments().get(0) : null; // this can occur during editing } else if (!isNotOfEqual) { removeArgsFromPatterns(patterns, be); patterns.add(be); } return returnNode; } private boolean ruleThensContainsTriple(TripleElement triple) { if (getTarget() instanceof Rule) { List<GraphPatternElement> thens = ((Rule)getTarget()).getThens(); for (GraphPatternElement then : thens) { if (graphPatternsMatch(then, triple)) { return true; } } } return false; } private boolean graphPatternsMatch(GraphPatternElement gp, TripleElement tr) { if (gp instanceof TripleElement) { if (((TripleElement)gp).getSubject().equals(tr.getSubject()) && ((TripleElement)gp).getPredicate().equals(tr.getPredicate())) { return true; } } else if (gp instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gp).getArguments(); for (Node arg : args) { if (arg instanceof ProxyNode) { GraphPatternElement argGp = ((ProxyNode)arg).getProxyFor(); if (graphPatternsMatch(argGp, tr)) { return true; } } } } else if (gp instanceof Junction) { Object lhs = ((Junction)gp).getLhs(); if (lhs instanceof ProxyNode) { if (graphPatternsMatch(((ProxyNode)lhs).getProxyFor(), tr)) { return true; } } Object rhs = ((Junction)gp).getRhs(); if (rhs instanceof ProxyNode) { if (graphPatternsMatch(((ProxyNode)rhs).getProxyFor(), tr)) { return true; } } } return false; } //Removed implied properties from graph pattern element /*private Object applyExpandedAndImpliedProperties(List<GraphPatternElement> patterns, BuiltinElement be, Object realArgForThen, List<GraphPatternElement> moveToIfts, Object finalIfsVar) throws TranslationException, InvalidNameException, InvalidTypeException { if (be.getExpandedPropertiesToBeUsed() != null) { // create a new VariableNode of the same type as finalIfsVar VariableNode thereExistsVar = getVariableNode(be); thereExistsVar.setType(((VariableNode)finalIfsVar).getType()); ((TripleElement)realArgForThen).setObject(thereExistsVar); BuiltinElement thereExistsBe = new BuiltinElement(); thereExistsBe.setFuncName(JenaBasedSadlModelProcessor.THERE_EXISTS); thereExistsBe.addArgument(thereExistsVar); patterns.add(patterns.size() - 1, thereExistsBe); for (NamedNode ep: be.getExpandedPropertiesToBeUsed()) { VariableNode newVar = null; boolean createTriple = false; if (finalIfsVar instanceof Node) { newVar = findVariableInTargetForReuse((Node)finalIfsVar, ep, null); if (newVar == null) { createTriple = true; newVar = getVariableNode(be); } } TripleElement epTriple = new TripleElement(SadlModelProcessor.nodeCheck(thereExistsVar), ep, newVar); patterns.add(epTriple); if (createTriple) { TripleElement epTriple2 = new TripleElement(SadlModelProcessor.nodeCheck(finalIfsVar), ep, newVar); moveToIfts.add(epTriple2); } } } else if (be.getLeftImpliedPropertyUsed() != null) { VariableNode newVar = null; boolean createTriple = false; if (finalIfsVar instanceof Node) { newVar = findVariableInTargetForReuse((Node) finalIfsVar, be.getLeftImpliedPropertyUsed(), null); if (newVar == null) { createTriple = true; newVar = getVariableNode((Node) finalIfsVar, be.getLeftImpliedPropertyUsed(), null, false); } } if (createTriple) { TripleElement epTriple = new TripleElement(SadlModelProcessor.nodeCheck(finalIfsVar), SadlModelProcessor.nodeCheck(be.getLeftImpliedPropertyUsed()), newVar); patterns.add(epTriple); } return newVar; } else if (be.getRightImpliedPropertyUsed() != null) { VariableNode newVar = null; boolean createTriple = false; if (finalIfsVar instanceof Node) { newVar = findVariableInTargetForReuse((Node)finalIfsVar, be.getRightImpliedPropertyUsed(), null); if (newVar == null) { createTriple = true; newVar =getVariableNode((Node) finalIfsVar, be.getRightImpliedPropertyUsed(), null, false); } } if (createTriple) { TripleElement epTriple = new TripleElement(SadlModelProcessor.nodeCheck(finalIfsVar), SadlModelProcessor.nodeCheck(be.getRightImpliedPropertyUsed()), newVar); moveToIfts.add(epTriple); } return newVar; } return null; } */ private void removeArgsFromPatterns(List<GraphPatternElement> patterns, BuiltinElement be) { if (patterns != null && patterns.size() > 0) { List<Node> args = be.getArguments(); if (args != null) { for (Node arg:args) { Object effectiveArg = arg; if (arg instanceof ProxyNode) { effectiveArg = ((ProxyNode)arg).getProxyFor(); } if (effectiveArg instanceof GraphPatternElement) { if (patterns.contains((GraphPatternElement)effectiveArg)) { patterns.remove((GraphPatternElement)effectiveArg); } if (effectiveArg instanceof BuiltinElement) { removeArgsFromPatterns(patterns, (BuiltinElement)effectiveArg); } } } } } } /** * Combine the argument elements with the existing Rule Ifs elements * @param moveToIfts * @throws TranslationException */ protected boolean addToPremises(List<GraphPatternElement> moveToIfts) throws TranslationException { if (getTarget() instanceof Rule) { List<GraphPatternElement> ifts = ((Rule)getTarget()).getIfs(); if (ifts == null) { ((Rule)getTarget()).setIfs(moveToIfts); } else { ifts.addAll(moveToIfts); } return true; } return false; } /** * This method flattens out the GraphPatternElement List so that there are no * next pointers within the list. * * @param list - input GraphPatternElement List that may have chained elements inside it * @return - the transformed list * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ private List<GraphPatternElement> flattenLinkedList(List<GraphPatternElement> list) throws InvalidNameException, InvalidTypeException, TranslationException { // go backwards through list so that the i index will remain valid for (int i = list.size() -1; i >= 0; i--) { GraphPatternElement element = list.get(i); if (element instanceof Junction) { flattenJunction((Junction)element); } GraphPatternElement nextElement = element.getNext(); // an internal chain int j = 0; while (nextElement != null) { element.setNext(null); list.add((1+i+(j++)),nextElement); element = nextElement; nextElement = element.getNext(); } } return list; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#flattenJunction(com.ge.research.sadl.model.gp.Junction) */ @Override public void flattenJunction(Junction element) throws InvalidNameException, InvalidTypeException, TranslationException { Object lhs = element.getLhs(); if (lhs instanceof Junction) { flattenJunction((Junction)lhs); } else if (lhs instanceof GraphPatternElement && ((GraphPatternElement)lhs).getNext() != null) { element.setLhs(SadlModelProcessor.nodeCheck(flattenJunctionSide((GraphPatternElement) lhs))); } Object rhs = element.getRhs(); if (rhs instanceof Junction) { flattenJunction((Junction)rhs); } else if (rhs instanceof GraphPatternElement && ((GraphPatternElement)rhs).getNext() != null) { element.setRhs(SadlModelProcessor.nodeCheck(flattenJunctionSide((GraphPatternElement) rhs))); } } private Object flattenJunctionSide(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { if (gpe.getNext() != null) { List<GraphPatternElement> lst = new ArrayList<GraphPatternElement>(); lst.add(gpe); lst = flattenLinkedList(lst); return lst; } return gpe; } private void removeDuplicateElements(Rule rule) throws InvalidNameException, InvalidTypeException, TranslationException { List<GraphPatternElement> givens = rule.getGivens(); List<GraphPatternElement> ifs = rule.getIfs(); List<GraphPatternElement> thens = rule.getThens(); removeDuplicates(thens, thens, true); // remove anything duplicated in thens // removeDuplicates(thens, ifs, false); // remove anything in ifs from thens // removeDuplicates(thens, givens, false); // remove anything in givens from thens removeDuplicates(ifs, ifs, true); // remove anything duplicated in ifs removeDuplicates(ifs, givens, false); // remove anything in givens from ifs removeDuplicates(givens, givens, true); // remove anything duplicated in givens } /** * If an element in list1 is also in list2, remove the element from list1 * * @param list1 * @param list2 * @param bRetainFirst -- true if same lists; if same lists leave first occurance * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ protected int removeDuplicates(List<GraphPatternElement> list1, List<GraphPatternElement> list2, boolean bRetainFirst) throws InvalidNameException, InvalidTypeException, TranslationException { if (list1 == null || list2 == null || list1.size() < 1 || list2.size() < 1) { return 0; } List<GraphPatternElement> flatList2 = getAllGPEs(list2); int removalCnt = 0; List<Integer> toBeRemoved = null; for (int idx2 = 0; idx2 < flatList2.size(); idx2++) { GraphPatternElement gpeToMatch = flatList2.get(idx2); // this is the element we are considering for duplicate removals boolean foundFirst = false; for (int idx1 = 0; idx1 < list1.size(); idx1++) { GraphPatternElement gpe = list1.get(idx1); if (gpe.equals(gpeToMatch)) { if (!bRetainFirst || foundFirst) { if (toBeRemoved == null) { toBeRemoved = new ArrayList<Integer>(); } if (!toBeRemoved.contains(idx1)) { toBeRemoved.add(idx1); removalCnt++; } } foundFirst = true; } else if (gpe instanceof Junction && ((Junction)gpe).getJunctionType().equals(JunctionType.Conj)) { Object[] results = removeJunctionDuplicates((Junction)gpe, gpeToMatch, bRetainFirst, foundFirst, removalCnt); GraphPatternElement processedGpe = (GraphPatternElement) results[0]; foundFirst = ((Boolean)results[1]).booleanValue(); removalCnt = ((Integer)results[2]).intValue(); if (!processedGpe.equals(gpe)) { list1.set(idx1, processedGpe); } } } } if (toBeRemoved != null) { Collections.sort(toBeRemoved); for (int i = (toBeRemoved.size() - 1); i >= 0; i--) { list1.remove(toBeRemoved.get(i).intValue()); } } return removalCnt; } private Object[] removeJunctionDuplicates(Junction gpe, GraphPatternElement gpeToMatch, boolean bRetainFirst, boolean foundFirst, int removalCnt) throws InvalidNameException, InvalidTypeException, TranslationException { boolean lhsDuplicate = false; boolean rhsDuplicate = false; Object lhs = gpe.getLhs(); if (lhs.equals(gpeToMatch)) { if(!bRetainFirst || foundFirst){ lhsDuplicate = true; } foundFirst = true; } else if (lhs instanceof Junction && ((Junction)lhs).getJunctionType().equals(JunctionType.Conj)) { Object[] lhsResults = removeJunctionDuplicates((Junction)lhs, gpeToMatch, bRetainFirst, foundFirst, removalCnt); GraphPatternElement newLhs = (GraphPatternElement) lhsResults[0]; foundFirst = ((Boolean)lhsResults[1]).booleanValue(); removalCnt = ((Integer)lhsResults[2]).intValue(); if (!newLhs.equals(lhs)) { gpe.setLhs(SadlModelProcessor.nodeCheck(newLhs)); } } Object rhs = gpe.getRhs(); if (rhs != null && rhs.equals(gpeToMatch)) { if (!bRetainFirst || foundFirst) { rhsDuplicate = true; } foundFirst = true; } else if (rhs instanceof Junction && ((Junction)rhs).getJunctionType().equals(JunctionType.Conj)) { Object[] rhsResults = removeJunctionDuplicates((Junction)rhs, gpeToMatch, bRetainFirst, foundFirst, removalCnt); GraphPatternElement newrhs = (GraphPatternElement) rhsResults[0]; foundFirst = ((Boolean)rhsResults[1]).booleanValue(); removalCnt = ((Integer)rhsResults[2]).intValue(); if (!newrhs.equals(rhs)) { gpe.setRhs(SadlModelProcessor.nodeCheck(newrhs)); } } Object[] results = new Object[3]; if (lhsDuplicate) { results[0] = gpe.getRhs(); } else if (rhsDuplicate) { results[0] = gpe.getLhs(); } else { results[0] = gpe; } results[1] = new Boolean(foundFirst); results[2] = new Integer(removalCnt); return results; } private List<GraphPatternElement> getAllGPEs(List<GraphPatternElement> list) throws TranslationException { List<GraphPatternElement> results = null; for (int i = 0; list != null && i < list.size(); i++) { GraphPatternElement gpe = list.get(i); if (gpe instanceof Junction && ((Junction)gpe).getJunctionType().equals(JunctionType.Conj)) { if (results != null) { results.addAll(junctionToList((Junction) gpe)); } else { results = junctionToList((Junction) gpe); } } else { if (results == null) { results = new ArrayList<GraphPatternElement>(); } results.add(gpe); } } if (results != null) { return results; } return list; } /** * Method to convert a Junction to a List<GraphPatternElement>. Note that this method will either handle * conjunction or disjunction at the top level but once the type is set the other type will not be converted * to a list as if both were converted the results would be non-functional. * @param gpe * @return * @throws TranslationException */ public static List<GraphPatternElement> junctionToList(Junction gpe) throws TranslationException { List<GraphPatternElement> lResult = new ArrayList<>(); List<Node> lProxies = junctionToNodeList(gpe); for( Node lProxy : lProxies ) { if( lProxy instanceof ProxyNode ) { lResult.add(((ProxyNode)lProxy).getProxyFor()); } else { throw new TranslationException("junctionToGraphPatternList called on junction which includes a non-GraphPatternElement; this is not supported."); } } return lResult; } /** * Method to convert a Junction to a List<Node>. Note that this method will either handle * conjunction or disjunction at the top level but once the type is set the other type will not be converted * to a list as if both were converted the results would be non-functional. * @param gpe * @return */ public static List<Node> junctionToNodeList(Junction gpe) { List<Node> lResult = new ArrayList<>(1); if ( JunctionType.Conj.equals(gpe.getJunctionType()) ) { lResult = conjunctionToList(gpe); } else if ( JunctionType.Disj.equals(gpe.getJunctionType()) ) { lResult = disjunctionToList(gpe); } else { try { lResult.add(new ProxyNode(gpe)); } catch ( InvalidTypeException e ) {} } return lResult; } public static List<Node> conjunctionToList(Junction gpe) { List<Node> lResult = new ArrayList<>(); Node lhs = (Node)gpe.getLhs(); if (lhs instanceof ProxyNode) { GraphPatternElement lhsProxy = ((ProxyNode)lhs).getProxyFor(); if (lhsProxy instanceof Junction && JunctionType.Conj.equals(((Junction)lhsProxy).getJunctionType())) { lResult.addAll( conjunctionToList((Junction)lhsProxy) ); } else { lResult.add(lhs); } } else { lResult.add(lhs); } Node rhs = (Node)gpe.getRhs(); if (rhs instanceof ProxyNode) { GraphPatternElement rhsProxy = ((ProxyNode)rhs).getProxyFor(); if (rhsProxy instanceof Junction && JunctionType.Conj.equals(((Junction)rhsProxy).getJunctionType())) { lResult.addAll( conjunctionToList((Junction)rhsProxy) ); } else { lResult.add(rhs); } } else { lResult.add(rhs); } return lResult; } public static List<Node> disjunctionToList(Junction gpe) { List<Node> lResult = new ArrayList<>(); Node lhs = (Node)gpe.getLhs(); if (lhs instanceof ProxyNode) { GraphPatternElement lhsProxy = ((ProxyNode)lhs).getProxyFor(); if (lhsProxy instanceof Junction && JunctionType.Disj.equals(((Junction)lhsProxy).getJunctionType())) { lResult.addAll( disjunctionToList((Junction)lhsProxy) ); } else { lResult.add(lhs); } } else { lResult.add(lhs); } Node rhs = (Node)gpe.getRhs(); if (rhs instanceof ProxyNode) { GraphPatternElement rhsProxy = ((ProxyNode)rhs).getProxyFor(); if (rhsProxy instanceof Junction && JunctionType.Disj.equals(((Junction)rhsProxy).getJunctionType())) { lResult.addAll( disjunctionToList((Junction)rhsProxy) ); } else { lResult.add(rhs); } } else { lResult.add(rhs); } return lResult; } /** * This method returns true only if all variables in the element are bound in other rule elements * * @param rule * @param gpe * @return */ private boolean allElementVariablesBound(Rule rule, GraphPatternElement gpe) { if (gpe instanceof TripleElement) { Node subject = ((TripleElement)gpe).getSubject(); if ((subject instanceof VariableNode || subject instanceof NamedNode) && !variableIsBound(rule, gpe, subject)) { return false; } Node object = ((TripleElement)gpe).getObject(); if ((object instanceof VariableNode || object instanceof NamedNode) && !variableIsBound(rule, gpe, object)) { return false; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int i = 0; args != null && i < args.size(); i++) { Node arg = args.get(i); if ((arg instanceof VariableNode || arg instanceof NamedNode) && !variableIsBound(rule, gpe, arg)) { return false; } } } return true; } /** * This method returns true if the argument node is bound in some other element of the rule * * @param rule * @param gpe * @param v * @return */ public static boolean variableIsBound(Rule rule, GraphPatternElement gpe, Node v) { if (v instanceof NamedNode) { if (((NamedNode)v).getNodeType() != null && !(((NamedNode)v).getNodeType().equals(NodeType.VariableNode))) { return true; } } // Variable is bound if it appears in a triple or as the return argument of a built-in List<GraphPatternElement> givens = rule.getGivens(); if (variableIsBoundInOtherElement(givens, 0, gpe, true, false, v)) { return true; } List<GraphPatternElement> ifs = rule.getIfs(); if (variableIsBoundInOtherElement(ifs, 0, gpe, true, false, v)) { return true; } List<GraphPatternElement> thens = rule.getThens(); if (variableIsBoundInOtherElement(thens, 0, gpe, false, true, v)) { return true; } return false; } /** * This method checks the list of GraphPatternElements to see if the specified variable is bound in these elements * * @param gpes - list of GraphPatternElements to check * @param startingIndex - where to start in the list * @param gp - the element in which this variable appears * @param boundIfEqual - use the current element for test? * @param matchMustBeAfter - must the binding be after the current element * @param v - the variable Node being checked * @return - true if the variable is bound else false */ public static boolean variableIsBoundInOtherElement(List<GraphPatternElement> gpes, int startingIndex, GraphPatternElement gp, boolean boundIfEqual, boolean matchMustBeAfter, Node v) { boolean reachedSame = false; for (int i = startingIndex; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); while (gpe != null) { boolean same = gp == null ? false : gp.equals(gpe); if (same) { reachedSame = true; } boolean okToTest = false; if (matchMustBeAfter && reachedSame && !same) { okToTest = true; } if (!matchMustBeAfter && (!same || (same && boundIfEqual))) { okToTest = true; } if (okToTest && variableIsBound(gpe, v)) { return true; } gpe = gpe.getNext(); } } return false; } private static boolean variableIsBound(GraphPatternElement gpe, Node v) { if (gpe instanceof TripleElement) { if ((((TripleElement)gpe).getSubject() != null &&((TripleElement)gpe).getSubject().equals(v)) || (((TripleElement)gpe).getObject() != null && ((TripleElement)gpe).getObject().equals(v))) { return true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); // TODO built-ins can actually have more than the last argument as output, but we can only tell this // if we have special knowledge of the builtin. Current SADL grammar doesn't allow this to occur. if (args != null && args.get(args.size() - 1) != null && args.get(args.size() - 1).equals(v)) { return true; } } else if (gpe instanceof Junction) { Object lhsobj = ((Junction)gpe).getLhs(); if (lhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)lhsobj, v)) { return true; } else if (lhsobj instanceof VariableNode && ((VariableNode)lhsobj).equals(v)) { return true; } Object rhsobj = ((Junction)gpe).getRhs(); if (rhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)rhsobj, v)) { return true; } else if (rhsobj instanceof VariableNode && ((VariableNode)rhsobj).equals(v)) { return true; } } return false; } private boolean doVariableSubstitution(List<GraphPatternElement> gpes, VariableNode v1, VariableNode v2) { boolean retval = false; for (int i = 0; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); if (gpe instanceof TripleElement) { if (((TripleElement)gpe).getSubject().equals(v1)) { ((TripleElement)gpe).setSubject(v2); retval = true; } else if (((TripleElement)gpe).getObject().equals(v1)) { ((TripleElement)gpe).setObject(v2); retval = true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int j = 0; j < args.size(); j++) { if (args.get(j).equals(v1)) { args.set(j, v2); retval = true; } } } else if (gpe instanceof Junction) { logger.error("Not yet handled"); } } return retval; } private boolean doVariableSubstitution(GraphPatternElement gpe, VariableNode v1, VariableNode v2) { boolean retval = false; do { if (gpe instanceof TripleElement) { if (((TripleElement)gpe).getSubject().equals(v1)) { ((TripleElement)gpe).setSubject(v2); retval = true; } else if (((TripleElement)gpe).getObject().equals(v1)) { ((TripleElement)gpe).setObject(v2); retval = true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int j = 0; j < args.size(); j++) { if (args.get(j).equals(v1)) { args.set(j, v2); retval = true; } } } else if (gpe instanceof Junction) { logger.error("Not yet handled"); } gpe = gpe.getNext(); } while (gpe != null); return retval; } private void setFirstOfPhrase(GraphPatternElement firstOfPhrase) { this.firstOfPhrase = firstOfPhrase; } protected GraphPatternElement getFirstOfPhrase() { return firstOfPhrase; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#setEncapsulatingTarget(java.lang.Object) */ @Override public void setEncapsulatingTarget(Object _encapsulatingTarget) { encapsulatingTarget = _encapsulatingTarget; } public boolean isCollectNamedNodes() { return collectNamedNodes; } public void setCollectNamedNodes(boolean collectNamedNodes) { this.collectNamedNodes = collectNamedNodes; } /** * This method can be called only once for a given set of translations; calling it clears the list of ConceptNames * @return */ public List<ConceptName> getNamedNodes() { if (namedNodes != null) { List<ConceptName> x = new ArrayList<ConceptName>(namedNodes); namedNodes.clear(); return x; } return null; } private void setNamedNodes(List<ConceptName> namedNodes) { this.namedNodes = namedNodes; } private boolean isCruleVariableInTypeOutput(VariableNode cruleVariable) { if (cruleVariablesTypeOutput == null) return false; return cruleVariablesTypeOutput.contains(cruleVariable); } private void addCruleVariableToTypeOutput(VariableNode cruleVariable) { if (cruleVariablesTypeOutput == null) { cruleVariablesTypeOutput = new ArrayList<VariableNode>(); } cruleVariablesTypeOutput.add(cruleVariable); } private void clearCruleVariableTypedOutput() { if (cruleVariablesTypeOutput != null) { cruleVariablesTypeOutput.clear(); } } private int addNotEqualsBuiltinsForNewCruleVariable(List<GraphPatternElement> gpes, int currentIdx, VariableNode node) throws TranslationException { if (cruleVariablesTypeOutput == null) { throw new TranslationException("This should never happen! Please report."); } int crvSize = cruleVariablesTypeOutput.size(); if (!cruleVariablesTypeOutput.get(crvSize - 1).equals(node)) { throw new TranslationException("This method should always be called immediately after creating a Crules variable."); } if (crvSize == 1) { return currentIdx; } for (int i = crvSize - 2; i >= 0; i--) { VariableNode otherVar = cruleVariablesTypeOutput.get(i); if (otherVar.getType().equals(node.getType())) { if (!notEqualAlreadyPresent(gpes, otherVar, node)) { BuiltinElement newBi = new BuiltinElement(); newBi.setFuncName("!="); newBi.setFuncType(BuiltinType.NotEqual); newBi.addArgument(otherVar); newBi.addArgument(node); gpes.add(++currentIdx, newBi); } } } return currentIdx; } private boolean notEqualAlreadyPresent(List<GraphPatternElement> gpes, VariableNode var1, VariableNode var2) { for (int i = 0; i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); if (gpe instanceof BuiltinElement && ((BuiltinElement)gpe).getFuncType().equals(BuiltinType.NotEqual)) { List<Node> args = ((BuiltinElement)gpe).getArguments(); int found = 0; for (int j =0; args != null && j < args.size(); j++) { if (args.get(j).equals(var1)) { found++; } if (args.get(j).equals(var2)) { found++; } } if (found == 2) { return true; } } } return false; } @Override public JenaBasedSadlModelProcessor getModelProcessor() { return modelProcessor; } private void setModelProcessor(JenaBasedSadlModelProcessor modelProcessor) { this.modelProcessor = modelProcessor; } @Override public Object cook(Object obj) throws TranslationException, InvalidNameException, InvalidTypeException { if (obj instanceof Rule) { return cook((Rule)obj); } resetIFTranslator(); setStartingVariableNumber(getVariableNumber() + getModelProcessor().getVariableNumber()); return expandProxyNodes(obj, false, true); } @Override public Object cook(Object obj, boolean treatAsConclusion) throws TranslationException, InvalidNameException, InvalidTypeException { if (obj instanceof Rule) { return cook((Rule)obj); } resetIFTranslator(); setStartingVariableNumber(getVariableNumber() + getModelProcessor().getVariableNumber()); return expandProxyNodes(obj, treatAsConclusion, true); } public Rule cook(Rule rule) { try { rule = addImpliedAndExpandedProperties(rule); // rule = addMissingTriplePatterns(rule); } catch (Exception e) { addError(new IFTranslationError("Translation to Intermediate Form encountered error (" + e.toString() + ")while 'cooking' IntermediateForm.")); e.printStackTrace(); } return rule; } protected OntModel getTheJenaModel() { return theJenaModel; } protected void setTheJenaModel(OntModel theJenaModel) { this.theJenaModel = theJenaModel; } @Override public boolean graphPatternElementMustBeInConclusions(GraphPatternElement gpe) { if (gpe instanceof BuiltinElement && ((BuiltinElement)gpe).getFuncName().equals("assign")) { return true; } return false; } /** * Method to return the type of element returned by a list element extraction built-in * @param bi * @return */ public NamedNode listElementIdentifierListType(BuiltinElement bi) { if (bi.getFuncName().equals("lastElement") || bi.getFuncName().equals("firstElement") || bi.getFuncName().equals("elementBefore") || bi.getFuncName().equals("elementAfter") || bi.getFuncName().equals("elementInList") || bi.getFuncName().equals("sublist")) { Node listArg = bi.getArguments().get(0); if (listArg instanceof NamedNode) { return (NamedNode) listArg; } else if (listArg instanceof ProxyNode) { Object pf = ((ProxyNode)listArg).getProxyFor(); if (pf instanceof TripleElement) { Node pred = ((TripleElement) pf).getPredicate(); if (pred instanceof NamedNode) { Property p = theJenaModel.getProperty(((NamedNode)pred).toFullyQualifiedString()); try { ConceptName pcn = getModelProcessor().namedNodeToConceptName((NamedNode)pred); TypeCheckInfo tci = getModelValidator().getTypeInfoFromRange(pcn, p, null); Node lsttype = tci.getTypeCheckType(); if (lsttype instanceof NamedNode) { return (NamedNode) lsttype; } } catch (DontTypeCheckException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } return null; } return null; } @Override public void reset() { // nothing needed in this class } }
sadl3/com.ge.research.sadl.parent/com.ge.research.sadl.jena/src/com/ge/research/sadl/jena/IntermediateFormTranslator.java
/************************************************************************ * Copyright © 2007-2017 - General Electric Company, All Rights Reserved * * Project: SADL * * Description: The Semantic Application Design Language (SADL) is a * language for building semantic models and expressing rules that * capture additional domain knowledge. The SADL-IDE (integrated * development environment) is a set of Eclipse plug-ins that * support the editing and testing of semantic models using the * SADL language. * * This software is distributed "AS-IS" without ANY WARRANTIES * and licensed under the Eclipse Public License - v 1.0 * which is available at http://www.eclipse.org/org/documents/epl-v10.php * ***********************************************************************/ package com.ge.research.sadl.jena; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.nodemodel.INode; import org.eclipse.xtext.nodemodel.impl.CompositeNodeWithSemanticElement; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.resource.XtextResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ge.research.sadl.jena.JenaBasedSadlModelValidator.TypeCheckInfo; import com.ge.research.sadl.model.ConceptName; import com.ge.research.sadl.model.ConceptName.ConceptType; import com.ge.research.sadl.model.gp.BuiltinElement; import com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType; import com.ge.research.sadl.model.gp.ConstantNode; import com.ge.research.sadl.model.gp.GraphPatternElement; import com.ge.research.sadl.model.gp.Junction; import com.ge.research.sadl.model.gp.Junction.JunctionType; import com.ge.research.sadl.model.gp.Literal; import com.ge.research.sadl.model.gp.NamedNode; import com.ge.research.sadl.model.gp.NamedNode.NodeType; import com.ge.research.sadl.model.gp.Node; import com.ge.research.sadl.model.gp.ProxyNode; import com.ge.research.sadl.model.gp.RDFTypeNode; import com.ge.research.sadl.model.gp.Rule; import com.ge.research.sadl.model.gp.Test; import com.ge.research.sadl.model.gp.Test.ComparisonType; import com.ge.research.sadl.model.gp.TripleElement; import com.ge.research.sadl.model.gp.TripleElement.TripleModifierType; import com.ge.research.sadl.model.gp.TripleElement.TripleSourceType; import com.ge.research.sadl.model.gp.VariableNode; import com.ge.research.sadl.processing.SadlConstants; import com.ge.research.sadl.processing.SadlModelProcessor; import com.ge.research.sadl.reasoner.InvalidNameException; import com.ge.research.sadl.reasoner.InvalidTypeException; import com.ge.research.sadl.reasoner.TranslationException; import com.ge.research.sadl.reasoner.utils.SadlUtils; import com.ge.research.sadl.sADL.Expression; import com.ge.research.sadl.sADL.TestStatement; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.UnionClass; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.RDFS; /** * This class translates the output generated by parsing SADL queries, * rules, and tests into what is called the SADL Intermediate Form (IF). * The parser output is in the form of parse trees whose nodes are * instances of the class Expression or of one of its subclasses. * The IF uses the Java classes in the Graph Patterns package * (com.ge.research.sadl.model.gp). In the IF, each query or * rule part (given, if, or then) or test phrase consists of * a list of graph pattern elements. The graph pattern element * can be a triple pattern or it can be a built-in. This * Intermediate Form is passed to the reasoner-specific translator * to generate rules and queries in an optimized form and format * for the target reasoner. * * One of the primary contributions of SADL to the modeling process is * its English-like syntax. The translation accomplished by this class * goes from this English-like syntax to the IF. Among other things, this * involves the generation of "missing" variables to provide the * connectives between the individual graph pattern elements in a list. * * The translation process "walks" the Expression parse tree. At the * leaves of this parse tree are ExplicitValues, IntervalValues, * ValueTables, or built-ins. At each node higher in the parse tree, * if returning to the node represents the completion of a graph pattern * element then that element is placed in the list at the appropriate * location and if necessary a variable (Node) is identified to connect * this new graph pattern element to other graph pattern elements * in the list. * * 10/2011: * The approach of adding variables as the translation proceeds, bottom-up, * has issues as looking bottom up one can't always tell the context and * therefore make the right decision. Therefore the strategy is changed to * use a ProxyNode to encapsulate the lower-level constructs to replicate * the parse tree but in the IF structures. Then the expansion of ProxyNodes * can occur with a knowledge of context for proper decisioning. For example, * no information is available to know whether a rule built-in has zero, one, * or more output variables. However, usage will show that either the built-in * is used within a higher-level built-in or triple, in which case it must * generate an output other than boolean so in expand ProxyNodes it will be * property handled by adding a generated variable if a specified variable * was not given, which variable is also placed in * the higher-level construct. In the future built-ins might be allowed to * return multiple values but that would require a construct such as * * x,y,z is someBuiltin(input1, input2, ..) * * This extension of the grammar would provide the necessary information * about the number of output variables to add, but only with the contextual * knowledge of the whole statement. * * * @author crapo * */ public class IntermediateFormTranslator implements I_IntermediateFormTranslator { protected static final Logger logger = LoggerFactory.getLogger(IntermediateFormTranslator.class); private int vNum = 0; // used to create unique variables private List<IFTranslationError> errors = null; private Object target = null; // the instance of Rule, Query, or Test into which we are trying to put the translation private Object encapsulatingTarget = null; // when a query is in a test private GraphPatternElement firstOfPhrase = null; private List<ConceptName> namedNodes = null; private boolean collectNamedNodes = false; private List<String> userDefinedVariables = new ArrayList<String>(); private OntModel theJenaModel = null; private JenaBasedSadlModelProcessor modelProcessor = null; private List<VariableNode> cruleVariablesTypeOutput = null; // list of crule variables that have had type statements output (only do so once) /** * The constructor takes a ModelManager argument * @param ontModel * @param modmgr */ public IntermediateFormTranslator(OntModel ontModel) { setTheJenaModel(ontModel); } /** * The constructor takes a ModelManager argument * @param ontModel * @param modmgr */ public IntermediateFormTranslator(JenaBasedSadlModelProcessor processor, OntModel ontModel) { setModelProcessor(processor); setTheJenaModel(ontModel); } // the target can be a Test, a Query, or a Rule instance /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#setTarget(java.lang.Object) */ @Override public void setTarget(Object _target) { target = _target; } @Override public Object getTarget() { return target; } /** * Reset the translator for a new translation task */ protected void resetIFTranslator() { vNum = 0; if (errors != null) { errors.clear(); } setTarget(null); encapsulatingTarget = null; setFirstOfPhrase(null); } /** * Returns the bottom triple whose subject was replaced. * @param pattern * @param proxyFor * @param assignedNode * @return */ private TripleElement assignNullSubjectInProxies(TripleElement pattern, TripleElement proxyFor, Node assignedNode) { if (pattern.getSubject() instanceof ProxyNode) { Object proxy = ((ProxyNode)pattern.getSubject()).getProxyFor(); if (proxy instanceof TripleElement) { // ((ProxyNode)pattern.getSubject()).setReplacementNode(assignedNode); if (((TripleElement)proxy).getSubject() == null) { // this is the bottom of the recursion ((TripleElement)proxy).setSubject(assignedNode); return (TripleElement) proxy; } else { // recurse down TripleElement bottom = assignNullSubjectInProxies(((TripleElement)proxy), proxyFor, assignedNode); // make the proxy next and reassign this subject as assignedNode ((ProxyNode)((TripleElement)proxy).getSubject()).setReplacementNode(assignedNode); ((TripleElement)proxy).setSubject(assignedNode); if (bottom.getNext() == null) { bottom.setNext(pattern); } return bottom; } } } return null; } private TripleElement getProxyWithNullSubject(TripleElement pattern) { if (pattern.getSubject() instanceof ProxyNode) { Object proxy = ((ProxyNode)pattern.getSubject()).getProxyFor(); if (proxy instanceof TripleElement) { if (((TripleElement)proxy).getSubject() == null) { return (TripleElement)proxy; } else { return getProxyWithNullSubject(((TripleElement)proxy)); } } } return null; } private boolean isComparisonViaBuiltin(Object robj, Object lobj) { if (robj instanceof TripleElement && lobj instanceof Node && ((TripleElement)robj).getNext() instanceof BuiltinElement) { BuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext(); if (isComparisonBuiltin(be.getFuncName()) && be.getArguments().size() == 1) { return true; } } return false; } private boolean isModifiedTripleViaBuitin(Object robj) { if (robj instanceof TripleElement && ((TripleElement)robj).getNext() instanceof BuiltinElement) { BuiltinElement be = (BuiltinElement) ((TripleElement)robj).getNext(); if (((TripleElement)robj).getPredicate() instanceof RDFTypeNode) { if (isModifiedTriple(be.getFuncType())) { Node subj = ((TripleElement)robj).getSubject(); Node arg = (be.getArguments() != null && be.getArguments().size() > 0) ? be.getArguments().get(0) : null; if (subj == null && arg == null) { return true; } if (subj != null && arg != null && subj.equals(arg)) { return true; } } } else { if (isModifiedTriple(be.getFuncType()) && ((TripleElement)robj).getObject().equals(be.getArguments().get(0))) { return true; } } } return false; } private boolean hasCommonVariableSubject(Object robj) { if (robj instanceof TripleElement && (((TripleElement)robj).getSubject() instanceof VariableNode && (((TripleElement)robj).getSourceType().equals(TripleSourceType.SPV)) || ((TripleElement)robj).getSourceType().equals(TripleSourceType.ITC))) { VariableNode subjvar = (VariableNode) ((TripleElement)robj).getSubject(); Object trel = robj; while (trel != null && trel instanceof TripleElement) { if (!(trel instanceof TripleElement) || (((TripleElement)trel).getSubject() != null &&!(((TripleElement)trel).getSubject().equals(subjvar)))) { return false; } trel = ((TripleElement)trel).getNext(); } if (trel == null) { return true; } } return false; } public static boolean isModifiedTriple(BuiltinType type) { if (type.equals(BuiltinType.Not) || type.equals(BuiltinType.NotEqual) || type.equals(BuiltinType.Only)|| type.equals(BuiltinType.NotOnly)) { return true; } return false; } public String getSourceGrammarText(EObject po) { Object r = po.eResource(); if (r instanceof XtextResource) { INode root = ((XtextResource) r).getParseResult().getRootNode(); for(INode node : root.getAsTreeIterable()) { if (node instanceof CompositeNodeWithSemanticElement) { EObject semElt = ((CompositeNodeWithSemanticElement)node).getSemanticElement(); if (semElt.equals(po)) { // this is the one! String txt = NodeModelUtils.getTokenText(node); return txt.trim(); } } } org.eclipse.emf.common.util.TreeIterator<EObject> titr = po.eAllContents(); while (titr.hasNext()) { EObject el = titr.next(); // TODO what's supposed to happen here? int i = 0; } } return null; } /** * This method fills in missing information in a NamedNode: * the prefix, the namespace, the type * * @param namedNode * @return * @throws InvalidNameException */ protected Node validateNode(Node node) throws InvalidNameException { if (node instanceof NamedNode) { if (!((NamedNode)node).isValidated()) { if (node instanceof VariableNode) { ((VariableNode) node).setNodeType(NodeType.VariableNode); userDefinedVariables.add(((NamedNode) node).getName()); } else if (node instanceof RDFTypeNode) { ((RDFTypeNode) node).setNodeType(NodeType.PropertyNode); } else { ConceptName cname = null; ConceptType ctype = null; String name = ((NamedNode)node).toString(); //getName(); if (name == null) { throw new InvalidNameException("A NamedNode has a null name! Did ResourceByName resolution fail?"); } int colon = name.indexOf(':'); if (colon > 0 && colon < name.length() - 1) { String pfx = name.substring(0, colon); ((NamedNode)node).setPrefix(pfx); String lname = name.substring(colon + 1); ((NamedNode)node).setName(lname); // cname = modelManager.validateConceptName(new ConceptName(pfx, lname)); } else { // cname = modelManager.validateConceptName(new ConceptName(name)); } ctype = cname.getType(); ((NamedNode)node).setNamespace(cname.getNamespace()); ((NamedNode)node).setPrefix(cname.getPrefix()); if (ctype.equals(ConceptType.CONCEPT_NOT_FOUND_IN_MODEL)) { // modelManager.addToVariableNamesCache(cname); node = new VariableNode(((NamedNode)node).getName()); userDefinedVariables.add(((NamedNode) node).getName()); } else if (ctype.equals(ConceptType.ANNOTATIONPROPERTY)){ ((NamedNode)node).setNodeType(NodeType.PropertyNode); } else if (ctype.equals(ConceptType.DATATYPEPROPERTY)){ ((NamedNode)node).setNodeType(NodeType.PropertyNode); } else if (ctype.equals(ConceptType.OBJECTPROPERTY)){ ((NamedNode)node).setNodeType(NodeType.PropertyNode); } else if (ctype.equals(ConceptType.ONTCLASS)){ ((NamedNode)node).setNodeType(NodeType.ClassNode); } else if (ctype.equals(ConceptType.INDIVIDUAL)){ ((NamedNode)node).setNodeType(NodeType.InstanceNode); } else { logger.error("Unexpected ConceptType: " + ctype.toString()); addError(new IFTranslationError("Unexpected ConceptType: " + ctype.toString())); } if (isCollectNamedNodes()) { if (namedNodes == null) { namedNodes = new ArrayList<ConceptName>(); } if (!namedNodes.contains(cname)) { namedNodes.add(cname); } } } ((NamedNode)node).setValidated(true); } } return node; } private void addError(IFTranslationError error) { if (errors == null) { errors = new ArrayList<IFTranslationError>(); } errors.add(error); } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#getErrors() */ @Override public List<IFTranslationError> getErrors() { return errors; } private GraphPatternElement createBinaryBuiltin(Expression expr, String name, Object lobj, Object robj) throws InvalidNameException, InvalidTypeException, TranslationException { BuiltinElement builtin = new BuiltinElement(); builtin.setFuncName(name); if (lobj != null) { builtin.addArgument(SadlModelProcessor.nodeCheck(lobj)); } if (robj != null) { builtin.addArgument(SadlModelProcessor.nodeCheck(robj)); } return builtin; } private Junction createJunction(Expression expr, String name, Object lobj, Object robj) throws InvalidNameException, InvalidTypeException, TranslationException { Junction junction = new Junction(); junction.setJunctionName(name); junction.setLhs(SadlModelProcessor.nodeCheck(lobj)); junction.setRhs(SadlModelProcessor.nodeCheck(robj)); return junction; } private Object createUnaryBuiltin(Expression sexpr, String name, Object sobj) throws InvalidNameException, InvalidTypeException, TranslationException { if (sobj instanceof Literal && BuiltinType.getType(name).equals(BuiltinType.Minus)) { Object theVal = ((Literal)sobj).getValue(); if (theVal instanceof Integer) { theVal = ((Integer)theVal) * -1; } else if (theVal instanceof Long) { theVal = ((Long)theVal) * -1; } else if (theVal instanceof Float) { theVal = ((Float)theVal) * -1; } else if (theVal instanceof Double) { theVal = ((Double)theVal) * -1; } ((Literal)sobj).setValue(theVal); ((Literal)sobj).setOriginalText("-" + ((Literal)sobj).getOriginalText()); return sobj; } if (sobj instanceof Junction) { // If the junction has two literal values, apply the op to both of them. Junction junc = (Junction) sobj; Object lhs = junc.getLhs(); Object rhs = junc.getRhs(); if (lhs instanceof Literal && rhs instanceof Literal) { lhs = createUnaryBuiltin(sexpr, name, lhs); rhs = createUnaryBuiltin(sexpr, name, rhs); junc.setLhs(SadlModelProcessor.nodeCheck(lhs)); junc.setRhs(SadlModelProcessor.nodeCheck(rhs)); } return junc; } if (BuiltinType.getType(name).equals(BuiltinType.Equal)) { if (sobj instanceof BuiltinElement) { if (isComparisonBuiltin(((BuiltinElement)sobj).getFuncName())) { // this is a "is <comparison>"--translates to <comparsion> (ignore is) return sobj; } } else if (sobj instanceof Literal || sobj instanceof NamedNode) { // an "=" interval value of a value is just the value return sobj; } } BuiltinElement builtin = new BuiltinElement(); builtin.setFuncName(name); if (isModifiedTriple(builtin.getFuncType())) { if (sobj instanceof TripleElement) { ((TripleElement)sobj).setType(getModelProcessor().getTripleModifierType(builtin.getFuncType())); return sobj; } } if (sobj != null) { builtin.addArgument(SadlModelProcessor.nodeCheck(sobj)); } return builtin; } private TripleElement addGraphPatternElementAtEnd(GraphPatternElement head, Node subject, Node predicate, Node object, TripleSourceType sourceType) { TripleElement newTriple = new TripleElement(); newTriple.setSubject(subject); newTriple.setPredicate(predicate); newTriple.setObject(object); newTriple.setSourceType(sourceType); return newTriple; } private GraphPatternElement addGraphPatternElementAtEnd(GraphPatternElement head, GraphPatternElement newTail) { if (head != null) { GraphPatternElement lastElement = getLastGraphPatternElement(head); lastElement.setNext(newTail); } else { head = newTail; } return head; } private GraphPatternElement getLastGraphPatternElement(GraphPatternElement pattern) { while (pattern.getNext() != null) { pattern = pattern.getNext(); } return pattern; } /** * Method to find all of the variables in a graph pattern that might be the implied select variables of a query * @param pattern * @return */ public Set<VariableNode> getSelectVariables(List<GraphPatternElement> patterns) { Set<VariableNode> vars = getUnboundVariables(patterns); // If we don't find an unreferenced variable, see if the pattern defines // a typed b node and get its variable. if (vars.isEmpty()) { for (int i = 0; i < patterns.size(); i++) { GraphPatternElement pattern = patterns.get(i); Set<VariableNode> moreVars = getSelectVariables(pattern); if (moreVars != null && moreVars.size() > 0) { vars.addAll(moreVars); } } } return vars; } public Set<VariableNode> getSelectVariables(GraphPatternElement pattern) { Set<VariableNode> vars = new LinkedHashSet<VariableNode>(); if (pattern instanceof TripleElement) { TripleElement triple = (TripleElement) pattern; if (triple.getSubject() instanceof VariableNode && triple.getPredicate() instanceof RDFTypeNode) { VariableNode var = (VariableNode) triple.getSubject(); vars.add(var); } else if (triple.getSubject() instanceof VariableNode) { vars.add(((VariableNode)triple.getSubject())); } else if (triple.getObject() instanceof VariableNode) { vars.add(((VariableNode)triple.getObject())); } else if (triple.getPredicate() instanceof VariableNode) { vars.add(((VariableNode)triple.getPredicate())); } } else if (pattern instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)pattern).getArguments(); if (args != null) { // right now we have no mechanism to know which variables are unbound so // assume the last one is // TODO Node arg = args.get(args.size() - 1); if (arg instanceof VariableNode) { vars.add((VariableNode) arg); } } } else if (pattern instanceof Junction) { Object lhs = ((Junction)pattern).getLhs(); Object rhs = ((Junction)pattern).getRhs(); if (lhs instanceof GraphPatternElement) { Set<VariableNode> lhsvars = getSelectVariables((GraphPatternElement) lhs); if (lhsvars != null) { vars.addAll(lhsvars); } } if (rhs instanceof GraphPatternElement) { Set<VariableNode> rhsvars = getSelectVariables((GraphPatternElement) rhs); if (rhsvars != null) { vars.addAll(rhsvars); } } } return vars; } private Set<VariableNode> getUnboundVariables(List<GraphPatternElement> patterns) { Set<VariableNode> vars = new LinkedHashSet<VariableNode>(); // We need to find any unreferenced variables in the pattern. for (int i = 0; i < patterns.size(); i++) { GraphPatternElement gpe = patterns.get(i); if (gpe instanceof TripleElement) { // Check the object of each triple to see if it has a variable // node with zero references. TripleElement triple = (TripleElement) gpe; Node subjNode = triple.getSubject(); if (subjNode instanceof VariableNode) { VariableNode var = (VariableNode) subjNode; if (var.getNumReferences() == 0) { vars.add(var); } } else if (subjNode instanceof NamedNode && ((NamedNode)subjNode).getNodeType().equals(NodeType.VariableNode)) { vars.add(new VariableNode(((NamedNode)subjNode).getName())); } Node objNode = triple.getObject(); if (objNode instanceof VariableNode) { VariableNode var = (VariableNode) objNode; if (var.getNumReferences() == 0) { vars.add(var); } } else if (objNode instanceof NamedNode && ((NamedNode)objNode).getNodeType().equals(NodeType.VariableNode)) { vars.add(new VariableNode(((NamedNode)objNode).getName())); } } else if (gpe instanceof BuiltinElement) { // Check the arguments of each builtin to see if it has a // variable node with zero references. BuiltinElement builtin = (BuiltinElement) gpe; for (Node argument : builtin.getArguments()) { if (argument instanceof VariableNode) { VariableNode var = (VariableNode) argument; if (var.getNumReferences() == 0) { vars.add(var); } } } } } return vars; } /** * This method flattens out GraphPatternElement linked lists into a regular List * @param test * @param object */ public void postProcessTest(Test test, TestStatement object) { try { Object lhs = test.getLhs(); if (lhs instanceof List<?> && ((List<?>)lhs).size() > 0) { if (((List<?>)lhs).get(0) instanceof GraphPatternElement) { flattenLinkedList((List<GraphPatternElement>)lhs); } if (lhs instanceof List<?>) { if (((List<?>)lhs).size() == 1) { lhs = ((List<?>)lhs).get(0); test.setLhs(lhs); } else if (((List<?>)lhs).size() == 2 && ((List<?>)lhs).get(1) instanceof BuiltinElement && ((BuiltinElement)((List<?>)lhs).get(1)).isCreatedFromInterval()) { test.setLhs(((List<?>)lhs).get(0)); test.setCompName(((BuiltinElement)((List<?>)lhs).get(1)).getFuncType()); test.setRhs(((BuiltinElement)((List<?>)lhs).get(1)).getArguments().get(1)); } } } else if (lhs instanceof GraphPatternElement && ((GraphPatternElement)lhs).getNext() != null) { boolean done = false; if ((((GraphPatternElement)lhs).getNext() instanceof BuiltinElement)) { // there is a builtin next BuiltinElement be = (BuiltinElement) ((GraphPatternElement)lhs).getNext(); if (isComparisonBuiltin(be.getFuncName())) { ((GraphPatternElement)lhs).setNext(null); if (be.getArguments().size() > 1) { if (be.getArguments().get(0) instanceof VariableNode) { test.setRhs(be.getArguments().get(1)); } else { // this is of the form V is P of S so comparison must be reversed reverseBuiltinComparisonDirection(be); test.setRhs(be.getArguments().get(0)); } } else { addError(new IFTranslationError("A BuiltinElement in a Test is a comparison (" + be.getFuncName() + ") but has less than two arguemnts (" + be.toString() + ")")); } test.setCompName(be.getFuncName()); done = true; } } if (!done) { List<GraphPatternElement> newLhs = new ArrayList<GraphPatternElement>(); newLhs.add((GraphPatternElement) lhs); test.setLhs(flattenLinkedList(newLhs)); } } else if (lhs instanceof BuiltinElement && isModifiedTriple(((BuiltinElement)lhs).getFuncType())) { List<Node> args = ((BuiltinElement)lhs).getArguments(); if (args != null && args.size() == 2) { test.setLhs(args.get(1)); test.setRhs(args.get(0)); test.setCompName(((BuiltinElement)lhs).getFuncName()); } } if (test.getRhs() instanceof ProxyNode) { test.setRhs(((ProxyNode)test.getRhs()).getProxyFor()); } Object rhs = test.getRhs(); if (rhs instanceof List<?> && ((List<?>)rhs).size() > 0) { if (((List<?>)rhs).get(0) instanceof GraphPatternElement) { flattenLinkedList((List<GraphPatternElement>)rhs); } } else if (rhs instanceof GraphPatternElement && ((GraphPatternElement)rhs).getNext() != null) { boolean done = false; if ((((GraphPatternElement)rhs).getNext() instanceof BuiltinElement)) { BuiltinElement be = (BuiltinElement) ((GraphPatternElement)rhs).getNext(); if (isComparisonBuiltin(be.getFuncName())) { ((GraphPatternElement)rhs).setNext(null); test.setLhs(be.getArguments().get(1)); test.setCompName(be.getFuncName()); done = true; } } if (!done) { List<GraphPatternElement> newRhs = new ArrayList<GraphPatternElement>(); newRhs.add((GraphPatternElement) rhs); test.setRhs(flattenLinkedList(newRhs)); } } if (test.getLhs() instanceof ProxyNode) { test.setLhs(((ProxyNode)test.getLhs()).getProxyFor()); } if (test.getCompType() != null && test.getCompType().equals(ComparisonType.Eq) && test.getLhs() != null && test.getRhs() != null && test.getLhs() instanceof NamedNode && test.getRhs() instanceof List<?>) { if (test.getRhsVariables() != null && test.getRhsVariables().size() == 1) { String rhsvar = test.getRhsVariables().get(0).getName(); List<?> rhslist = (List<?>) test.getRhs(); boolean allPass = true; for (int i = 0; i < rhslist.size(); i++) { Object anrhs = rhslist.get(i); if (!(anrhs instanceof TripleElement)) { allPass = false; break; } else { Node subj = ((TripleElement)anrhs).getSubject(); if (!(subj instanceof VariableNode) || !(((VariableNode)subj).getName().equals(rhsvar))) { allPass = false; break; } } } if (allPass) { for (int i = 0; i < rhslist.size(); i++) { TripleElement triple = (TripleElement) rhslist.get(i); triple.setSubject((Node) test.getLhs()); } test.setLhs(test.getRhs()); test.setRhs(null); test.setRhsVariables(null); test.setCompName((String)null); } } } // this is a validity checking section TripleElement singleTriple = null; if (test.getLhs() instanceof TripleElement && test.getRhs() == null && ((TripleElement)test.getLhs()).getNext() == null) { singleTriple = (TripleElement) test.getLhs(); } else if (test.getRhs() instanceof TripleElement && test.getLhs() == null && ((TripleElement)test.getRhs()).getNext() == null) { singleTriple = (TripleElement) test.getRhs(); } if (singleTriple != null) { // a single triple test should not have any variables in it if (singleTriple.getSubject() instanceof VariableNode || singleTriple.getPredicate() instanceof VariableNode || singleTriple.getObject() instanceof VariableNode) { addError(new IFTranslationError("Test is a single triple to be matched; should not contain variables.", object)); } else { try { // modelManager.validateStatement(singleTriple.getSubject(), singleTriple.getPredicate(), singleTriple.getObject()); } catch (Throwable t) { // try to validate but don't do anything on Exception } } } } catch (Exception e) { e.printStackTrace(); } } public static void reverseBuiltinComparisonDirection(BuiltinElement be) { if (be.getFuncType().equals(BuiltinType.LT)) { be.setFuncName(">"); } else if (be.getFuncType().equals(BuiltinType.LTE)) { be.setFuncName(">="); } else if (be.getFuncType().equals(BuiltinType.GT)){ be.setFuncName("<"); } else if (be.getFuncType().equals(BuiltinType.GTE)) { be.setFuncName("<="); } } public static void builtinComparisonComplement(BuiltinElement be) { if (be.getFuncType().equals(BuiltinType.LT)) { be.setFuncName(">="); } else if (be.getFuncType().equals(BuiltinType.LTE)) { be.setFuncName(">"); } else if (be.getFuncType().equals(BuiltinType.GT)){ be.setFuncName("<="); } else if (be.getFuncType().equals(BuiltinType.GTE)) { be.setFuncName("<"); } } public static boolean isComparisonBuiltin(String builtinName) { ComparisonType[] types = ComparisonType.values(); for (ComparisonType type : types) { if (type.matches(builtinName)) { return true; } } return false; } public Rule postProcessRule(Rule rule, EObject object) throws TranslationException { clearCruleVariableTypedOutput(); try { // do this first so that the arguments don't change before these are applied addImpliedAndExpandedProperties(rule); // now do this before any null subjects that are the same variable get replaced with different variables. addMissingCommonVariables(rule); // now add other missing patterns, if needed // addMissingTriplePatterns(rule); } catch (InvalidNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InvalidTypeException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (TranslationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // convert givens linked list to array; expand conjunctions List<GraphPatternElement> givens = flattenRuleJunctions(rule.getGivens()); if (givens != null) { Object results; try { results = expandProxyNodes(givens, false, true); if (results instanceof List<?>) { if (((List<?>)results).size() == 1 && ((List<?>)results).get(0) instanceof Junction) { results = junctionToList((Junction) ((List<?>)results).get(0)); } rule.setGivens((List<GraphPatternElement>) results); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { retiredProxyNodes.clear(); } // convert ifs linked list to array; expand conjunctions List<GraphPatternElement> ifs = flattenRuleJunctions(rule.getIfs()); if (ifs != null) { Object results; try { results = expandProxyNodes(ifs, false, false); if (results instanceof List<?>) { if (((List<?>)results).size() == 1 && ((List<?>)results).get(0) instanceof Junction) { results = junctionToList((Junction) ((List<?>)results).get(0)); } rule.setIfs((List<GraphPatternElement>) results); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // now process conclusions List<GraphPatternElement> thens = flattenRuleJunctions(rule.getThens()); if (thens != null) { Object results; try { results = expandProxyNodes(thens, true, false); if (results instanceof List<?>) { if (((List<?>)results).size() == 1 && ((List<?>)results).get(0) instanceof Junction) { results = junctionToList((Junction) ((List<?>)results).get(0)); } for (int i = 0; i < ((List<?>)results).size(); i++) { GraphPatternElement tgpe = (GraphPatternElement) ((List<?>)results).get(i); results = moveEmbeddedGPEsToIfs(rule, (List<?>) results, tgpe); } rule.setThens((List<GraphPatternElement>) results); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { throw e; } } try { removeDuplicateElements(rule); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return rule; } private void addMissingCommonVariables(Rule rule) throws TranslationException { // Find triples with null subjects List<TripleElement> nullSubjects = null; if (rule.getGivens() != null) { nullSubjects = getNullSubjectTriples(rule.getGivens(), nullSubjects); } if (rule.getIfs() != null) { nullSubjects = getNullSubjectTriples(rule.getIfs(), nullSubjects); } if (rule.getThens() != null) { nullSubjects = getNullSubjectTriples(rule.getThens(), nullSubjects); } if (nullSubjects != null) { Map<NamedNode,List<Resource>> cache = new HashMap<NamedNode, List<Resource>>(); for (int i = 0; i < nullSubjects.size(); i++) { Node prop = nullSubjects.get(i).getPredicate(); if (prop instanceof NamedNode) { Property p = getTheJenaModel().getProperty(((NamedNode)prop).toFullyQualifiedString()); StmtIterator dmnitr = getTheJenaModel().listStatements(p, RDFS.domain, (RDFNode)null); if (dmnitr.hasNext()) { List<Resource> dmnclses = new ArrayList<Resource>(); while (dmnitr.hasNext()) { RDFNode dmn = dmnitr.nextStatement().getObject(); if (dmn.isURIResource()) { dmnclses.add((Resource) dmn); } else if (dmn.canAs(OntClass.class)&& dmn.as(OntClass.class).isUnionClass()) { dmnclses.addAll(getUnionClassMembers(dmn.as(OntClass.class).asUnionClass())); } else { throw new TranslationException("Unhandled case"); } } cache.put((NamedNode)prop, dmnclses); } } } for (int i = 0; i < nullSubjects.size(); i++) { List<Resource> dmns1 = cache.get(nullSubjects.get(i).getPredicate()); for (int j = i +1; j < nullSubjects.size(); j++) { boolean matched = false; List<Resource> dmns2 = cache.get(nullSubjects.get(j).getPredicate()); for (int k = 0; k < dmns2.size(); k++) { Resource dmn2 = dmns2.get(k); if (dmns1.contains(dmn2)) { // there's a match--connect them VariableNode cmnvar = new VariableNode(getNewVar()); nullSubjects.get(i).setSubject(cmnvar); nullSubjects.get(j).setSubject(cmnvar); matched = true; break; } else if (dmn2.canAs(OntClass.class)) { for (int l = 0; l < dmns1.size(); l++) { Resource dmn1 = dmns1.get(l); if (dmn1.canAs(OntClass.class)) { if (SadlUtils.classIsSuperClassOf(dmn1.as(OntClass.class), dmn2.as(OntClass.class))) { VariableNode cmnvar = new VariableNode(getNewVar()); nullSubjects.get(i).setSubject(cmnvar); nullSubjects.get(j).setSubject(cmnvar); matched = true; break; } else if (SadlUtils.classIsSuperClassOf(dmn2.as(OntClass.class), dmn1.as(OntClass.class))) { VariableNode cmnvar = new VariableNode(getNewVar()); nullSubjects.get(i).setSubject(cmnvar); nullSubjects.get(j).setSubject(cmnvar); matched = true; break; } } } } } if (matched) { continue; } } } } } private List<OntClass> getUnionClassMembers(UnionClass unionClass) { List<OntClass> members = new ArrayList<OntClass>(); ExtendedIterator<? extends OntClass> ucitr = unionClass.listOperands(); while (ucitr.hasNext()) { OntClass uccls = ucitr.next(); if (uccls.isURIResource()) { members.add(uccls); } else if (uccls.isUnionClass()) { members.addAll(getUnionClassMembers(uccls.asUnionClass())); } } return members; } private List<TripleElement> getNullSubjectTriples(List<GraphPatternElement> gpes, List<TripleElement> nullSubjects) { for (int i = 0; i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); nullSubjects = getNullSubjectTriples(nullSubjects, gpe); } return nullSubjects; } private List<TripleElement> getNullSubjectTriples(List<TripleElement> nullSubjects, GraphPatternElement gpe) { if (gpe instanceof TripleElement && ((TripleElement)gpe).getSubject() == null) { if (nullSubjects == null) { nullSubjects = new ArrayList<TripleElement>(); } nullSubjects.add((TripleElement) gpe); } else { if (gpe instanceof TripleElement && ((TripleElement)gpe).getSubject() instanceof ProxyNode) { nullSubjects = getNullSubjectTriples(nullSubjects, (GraphPatternElement)((ProxyNode)((TripleElement)gpe).getSubject()).getProxyFor()); } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int i = 0; args != null && i < args.size(); i++) { if (args.get(i) instanceof ProxyNode) { nullSubjects = getNullSubjectTriples(nullSubjects, (GraphPatternElement)((ProxyNode)args.get(i)).getProxyFor()); } } } } return nullSubjects; } private Rule addImpliedAndExpandedProperties(Rule rule) throws InvalidNameException, InvalidTypeException, TranslationException { boolean clearPreviouslyRetired = true; // must clear on first call List<GraphPatternElement> gvns = rule.getGivens(); if (gvns != null) { addImpliedAndExpandedProperties(gvns); clearPreviouslyRetired = false; } List<GraphPatternElement> ifs = rule.getIfs(); if (ifs != null) { addImpliedAndExpandedProperties(ifs); clearPreviouslyRetired = false; } List<GraphPatternElement> thens = rule.getThens(); if (thens != null) { addImpliedAndExpandedProperties(thens); } return rule; } protected void addImpliedAndExpandedProperties(List<GraphPatternElement> fgpes) throws InvalidNameException, InvalidTypeException, TranslationException { // List<GraphPatternElement> fgpes = flattenLinkedList(gpes); for (int i = 0; i < fgpes.size(); i++) { GraphPatternElement gpeback = addImpliedAndExpandedProperties(fgpes.get(i)); fgpes.set(i, gpeback); } } protected GraphPatternElement addImpliedAndExpandedProperties(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { boolean processed = false; if (gpe.getExpandedPropertiesToBeUsed() != null) { gpe = applyExpandedProperties(gpe); processed = true; } if (!processed) { if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int i = 0; args != null && i < args.size(); i++ ) { Node arg = args.get(i); if (arg instanceof ProxyNode) { GraphPatternElement gpeback = addImpliedAndExpandedProperties((GraphPatternElement)((ProxyNode)arg).getProxyFor()); ((ProxyNode)arg).setProxyFor(gpeback); } } } else if (gpe instanceof TripleElement) { Node pred = ((TripleElement)gpe).getPredicate(); if (pred instanceof NamedNode && ((NamedNode)pred).getImpliedPropertyNode() != null) { TripleElement newTriple = new TripleElement(null, ((TripleElement)gpe).getPredicate(), null); newTriple.setPredicate(((NamedNode)pred).getImpliedPropertyNode()); newTriple.setObject(((TripleElement)gpe).getObject()); ((TripleElement)gpe).setObject(SadlModelProcessor.nodeCheck(newTriple)); ((NamedNode)pred).setImpliedPropertyNode(null); } } else if (gpe instanceof Junction) { Object lhs = ((Junction) gpe).getLhs(); if (lhs instanceof ProxyNode) { ((Junction)gpe).setLhs(SadlModelProcessor.nodeCheck(addImpliedAndExpandedProperties(((ProxyNode)lhs).getProxyFor()))); } else { throw new TranslationException("Junction must contain only ProxyNode as left and right."); } Object rhs = ((Junction) gpe).getRhs(); if (rhs instanceof ProxyNode) { ((Junction)gpe).setRhs(SadlModelProcessor.nodeCheck(addImpliedAndExpandedProperties(((ProxyNode)rhs).getProxyFor()))); } else { throw new TranslationException("Junction must contain only ProxyNode as left and right."); } } } return gpe; } //Need to update for implied properties being moved off graph pattern elements? private void applyLeftImpliedProperty(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { NamedNode lip = null; //gpe.getLeftImpliedPropertyUsed(); if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() == null || ((BuiltinElement)gpe).getArguments().size() != 2) { throw new TranslationException("Implied properties can't be applied to a BuiltinElement with other than 2 arguments"); } Node arg0 = ((BuiltinElement)gpe).getArguments().get(0); if (arg0 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg0))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg0); arg0 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple = new TripleElement(arg0, lip, null); arg0 = SadlModelProcessor.nodeCheck(newTriple); ((BuiltinElement)gpe).getArguments().set(0, arg0); for (int i = 0; i < ((BuiltinElement)gpe).getArguments().size(); i++) { Node agi = ((BuiltinElement)gpe).getArguments().get(i); if (agi instanceof ProxyNode && ((ProxyNode)agi).getProxyFor() instanceof BuiltinElement) { addImpliedAndExpandedProperties((BuiltinElement)((ProxyNode)agi).getProxyFor()); } } //((BuiltinElement)gpe).setLeftImpliedPropertyUsed(null); } else if (gpe instanceof TripleElement) { TripleElement newTriple = new TripleElement(((TripleElement)gpe).getSubject(), ((TripleElement)gpe).getPredicate(), null); ((TripleElement)gpe).setSubject(SadlModelProcessor.nodeCheck(newTriple)); ((TripleElement)gpe).setPredicate(lip); //gpe.setRightImpliedPropertyUsed(null); } else { throw new TranslationException("Unexpected GraphPatternElement (" + gpe.getClass().getCanonicalName() + ") encountered applying implied property"); } } //Need to update for implied properties being moved off graph pattern elements? private void applyRightImpliedProperty(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { NamedNode rip = null; //gpe.getRightImpliedPropertyUsed(); if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() == null || ((BuiltinElement)gpe).getArguments().size() != 2) { throw new TranslationException("Implied properties can't be applied to a BuiltinElement with other than 2 arguments"); } Node arg1 = ((BuiltinElement)gpe).getArguments().get(1); if (arg1 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg1))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg1); arg1 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple = new TripleElement(arg1, rip, null); arg1 = SadlModelProcessor.nodeCheck(newTriple); ((BuiltinElement)gpe).getArguments().set(1, arg1); for (int i = 0; i < ((BuiltinElement)gpe).getArguments().size(); i++) { Node agi = ((BuiltinElement)gpe).getArguments().get(i); if (agi instanceof ProxyNode && ((ProxyNode)agi).getProxyFor() instanceof BuiltinElement) { addImpliedAndExpandedProperties((BuiltinElement)((ProxyNode)agi).getProxyFor()); } } //gpe.setRightImpliedPropertyUsed(null); } else if (gpe instanceof TripleElement) { Node objNode = ((TripleElement)gpe).getObject(); TripleElement newTriple = new TripleElement(objNode, rip, null); ((TripleElement)gpe).setObject(SadlModelProcessor.nodeCheck(newTriple)); //gpe.setRightImpliedPropertyUsed(null); } else { throw new TranslationException("Unexpected GraphPatternElement (" + gpe.getClass().getCanonicalName() + ") encountered applying implied property"); } } private GraphPatternElement applyExpandedProperties(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { List<NamedNode> eps = gpe.getExpandedPropertiesToBeUsed(); List<GraphPatternElement> junctionMembers = null; JunctionType jcttype = JunctionType.Conj; if (gpe instanceof BuiltinElement && eps.size() > 1) { if (((BuiltinElement)gpe).getFuncType().equals(BuiltinType.NotEqual)) { if (((BuiltinElement)gpe).getFuncName().equals("assign")) { throw new TranslationException("Can't have disjunction in assignment"); } jcttype = JunctionType.Disj; } junctionMembers = new ArrayList<GraphPatternElement>(); } if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() == null || ((BuiltinElement)gpe).getArguments().size() != 2) { throw new TranslationException("Expanded properties can't be applied to a BuiltinElement with other than 2 arguments"); } int expPropCntr = 0; List<Node> originalArgs = new ArrayList<Node>(); for (NamedNode ep : eps) { BuiltinElement workingGpe = (BuiltinElement) gpe; if (expPropCntr == 0) { for (int i = 0; i < ((BuiltinElement)workingGpe).getArguments().size(); i++) { Node agi = ((BuiltinElement)workingGpe).getArguments().get(i); if (agi instanceof ProxyNode && ((ProxyNode)agi).getProxyFor() instanceof BuiltinElement) { addImpliedAndExpandedProperties((BuiltinElement)((ProxyNode)agi).getProxyFor()); } originalArgs.add(agi); } } else { workingGpe = new BuiltinElement(); workingGpe.setFuncName(((BuiltinElement) gpe).getFuncName()); workingGpe.setFuncType(((BuiltinElement) gpe).getFuncType()); for (int i = 0; i < ((BuiltinElement) gpe).getArguments().size(); i++) { workingGpe.addArgument(originalArgs.get(i)); } } Node arg0 = ((BuiltinElement)workingGpe).getArguments().get(0); if (arg0 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg0))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg0); arg0 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple1 = new TripleElement(arg0, ep, null); arg0 = SadlModelProcessor.nodeCheck(newTriple1); ((BuiltinElement)workingGpe).getArguments().set(0, arg0); Node arg1 = ((BuiltinElement)workingGpe).getArguments().get(1); if (arg1 instanceof NamedNode && getModelProcessor().isProperty(((NamedNode)arg1))) { TripleElement newTriple = singlePropertyToTriple((NamedNode)arg1); arg1 = SadlModelProcessor.nodeCheck(newTriple); } TripleElement newTriple2 = new TripleElement(arg1, ep, null); arg1 = SadlModelProcessor.nodeCheck(newTriple2); ((BuiltinElement)workingGpe).getArguments().set(1, arg1); ((BuiltinElement)workingGpe).setExpandedPropertiesToBeUsed(null); if (junctionMembers != null) { junctionMembers.add(workingGpe); } expPropCntr++; } if (junctionMembers != null) { if (jcttype.equals(JunctionType.Conj)) { gpe = (GraphPatternElement) listToAnd(junctionMembers).get(0); } else { gpe = listToOr(junctionMembers); } } } else if (gpe instanceof TripleElement) { Node objNode = ((TripleElement)gpe).getObject(); if (!(objNode instanceof ConstantNode && ((ConstantNode)objNode).getName().equals(SadlConstants.CONSTANT_NONE))) { int i = 0; } } else { // expanded properties can only apply to equality/inequality and assignment, so no other GraphPatternElement type should be encountered throw new TranslationException("Unexpeced non-BuiltinElement has expanded properties"); } gpe.setExpandedPropertiesToBeUsed(null); return gpe; } private TripleElement singlePropertyToTriple(NamedNode prop) { VariableNode nvar = null; //new VariableNode(getNewVar()); TripleElement newTriple = new TripleElement(nvar, prop, null); return newTriple; } private List<NamedNode> getNamedNodeList(List<NamedNode> found, GraphPatternElement gpe) { if (gpe instanceof TripleElement) { found = addNamedNode(found, ((TripleElement)gpe).getSubject()); found = addNamedNode(found, ((TripleElement)gpe).getObject()); } else if (gpe instanceof BuiltinElement) { if (((BuiltinElement)gpe).getArguments() != null) { for (int i = 0; i < ((BuiltinElement)gpe).getArguments().size(); i++) { found = addNamedNode(found, ((BuiltinElement)gpe).getArguments().get(i)); } } } else if (gpe instanceof Junction) { Object lhs = ((Junction)gpe).getLhs(); if (lhs instanceof Node) { found = addNamedNode(found, (Node) lhs); } Object rhs = ((Junction)gpe).getRhs(); if (rhs instanceof Node) { found = addNamedNode(found, (Node) rhs); } } return found; } private List<NamedNode> addNamedNode(List<NamedNode> found, Node node) { if (node instanceof NamedNode && !(node instanceof VariableNode)) { if (found == null) found = new ArrayList<NamedNode>(); found.add((NamedNode)node); } return found; } private List<GraphPatternElement> decorateCRuleVariables(List<GraphPatternElement> gpes, boolean isRuleThen) { for (int i = 0; i < gpes.size(); i++) { Object premise = gpes.get(i); if (premise instanceof BuiltinElement) { if (((BuiltinElement)premise).getArguments() != null) { for (Node n: ((BuiltinElement)premise).getArguments()) { if (n instanceof VariableNode && ((VariableNode)n).isCRulesVariable() && ((VariableNode)n).getType() != null && !isCruleVariableInTypeOutput((VariableNode) n)) { TripleElement newTypeTriple = new TripleElement(n, new RDFTypeNode(), ((VariableNode)n).getType()); gpes.add(++i, newTypeTriple); addCruleVariableToTypeOutput((VariableNode) n); if (!isRuleThen) { try { i = addNotEqualsBuiltinsForNewCruleVariable(gpes, i, (VariableNode) n); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } else if (premise instanceof TripleElement) { try { TripleElement gpe = (TripleElement) premise; Node subj = gpe.getSubject(); Node obj = gpe.getObject(); if (subj instanceof VariableNode && ((VariableNode)subj).isCRulesVariable() && ((VariableNode)subj).getType() != null && !isCruleVariableInTypeOutput((VariableNode) subj)) { TripleElement newTypeTriple = new TripleElement(subj, new RDFTypeNode(), ((VariableNode)subj).getType()); gpes.add(i++, newTypeTriple); addCruleVariableToTypeOutput((VariableNode) subj); if (!isRuleThen) { i = addNotEqualsBuiltinsForNewCruleVariable(gpes, i, (VariableNode) subj); } } if (obj instanceof VariableNode && ((VariableNode)obj).isCRulesVariable() && ((VariableNode)obj).getType() != null && !isCruleVariableInTypeOutput((VariableNode) obj)) { TripleElement newTypeTriple = new TripleElement(obj, new RDFTypeNode(), ((VariableNode)obj).getType()); gpes.add(++i, newTypeTriple); addCruleVariableToTypeOutput((VariableNode) obj); if (!isRuleThen) { i = addNotEqualsBuiltinsForNewCruleVariable(gpes, i, (VariableNode) obj); } } } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return gpes; } private List<GraphPatternElement> flattenRuleJunctions(List<GraphPatternElement> lst) { if (lst == null) return null; List<GraphPatternElement> results = new ArrayList<GraphPatternElement>(); for (int i = 0; i < lst.size(); i++) { GraphPatternElement gpe = lst.get(i); if (gpe instanceof Junction) { if (((Junction)gpe).getJunctionType().equals(JunctionType.Conj)) { try { results.addAll(flattenRuleJunction((Junction) gpe)); } catch (TranslationException e) { addError(new IFTranslationError(e.getMessage(), e)); } } else { // addError(new IFTranslationError("Disjunction not supported in rules at this time")); // leave this error checking for the final translations step--some rules may support disjunction results.add(gpe); } } // else if (gpe instanceof BuiltinElement && // ((BuiltinElement)gpe).getFuncName() != null && ((BuiltinElement)gpe).getFuncName().equals("and")) { // List<Node> args = ((BuiltinElement)gpe).getArguments(); // for (int j = 0; j <= args.size(); j++) { // Node nj = args.get(j); // } // } else { results.add(gpe); } } return results; } private List<GraphPatternElement> flattenRuleJunction(Junction jct) throws TranslationException { List<GraphPatternElement>results = new ArrayList<GraphPatternElement>(); if (!jct.getJunctionType().equals(JunctionType.Conj)) { // addError(new IFTranslationError("Disjunction not supported in rules at this time")); // this is up to the target translator to decide, not the Intermediate Form Translator results.add(jct); return results; } Object lhs = jct.getLhs(); if (lhs instanceof ProxyNode) { lhs = ((ProxyNode)lhs).getProxyFor(); } if (lhs instanceof Junction) { results.addAll(flattenRuleJunction((Junction)lhs)); } else if (lhs instanceof GraphPatternElement){ results.add((GraphPatternElement) lhs); } else if (lhs instanceof List<?>) { for (int i = 0; i < ((List<?>)lhs).size(); i++) { results.add((GraphPatternElement) ((List<?>)lhs).get(i)); } } else { throw new TranslationException("Encountered non-GraphPatternElement during rule translation"); } Object rhs = jct.getRhs(); if (rhs instanceof ProxyNode) { rhs = ((ProxyNode)rhs).getProxyFor(); } if (rhs instanceof Junction) { results.addAll(flattenRuleJunction((Junction)rhs)); } else if (rhs instanceof GraphPatternElement) { results.add((GraphPatternElement)rhs); } else if (rhs instanceof List<?>) { for (int i = 0; i < ((List<?>)rhs).size(); i++) { results.add((GraphPatternElement) ((List<?>)rhs).get(i)); } } else { throw new TranslationException("Encountered non-GraphPatternElement during rule translation"); } return results; } /** * Method to remove GPE's with isEmbedded true from thens to ifs * * @param rule * @param results * @param tgpe * @return * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ private List<?> moveEmbeddedGPEsToIfs(Rule rule, List<?> results, GraphPatternElement tgpe) throws InvalidNameException, InvalidTypeException, TranslationException { if (tgpe.isEmbedded()) { results.remove(tgpe); rule.getIfs().add(tgpe); } else { if (tgpe instanceof Junction) { int idx = results.indexOf(tgpe); GraphPatternElement newtgpe = moveEmbeddedFromJunction(rule, (Junction)tgpe); if (newtgpe == null) { results.remove(idx); } else if (newtgpe != tgpe) { ((List<GraphPatternElement>)results).set(idx, newtgpe); } } } return results; } /** * Method to move all embedded GPEs in a Junction to the rule ifs and return whatever should be put in * the Junction's place or null if nothing. * * @param rule * @param tgpe * @return * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ private GraphPatternElement moveEmbeddedFromJunction(Rule rule, Junction tgpe) throws InvalidNameException, InvalidTypeException, TranslationException { boolean lhsRemoved = false; boolean rhsRemoved = false; Object lhs = ((Junction)tgpe).getLhs(); Object rhs = ((Junction)tgpe).getRhs(); if (lhs instanceof GraphPatternElement && ((GraphPatternElement)lhs).isEmbedded()) { rule.getIfs().add((GraphPatternElement) lhs); lhsRemoved = true; } else if (lhs instanceof Junction) { lhs = moveEmbeddedFromJunction(rule, (Junction) lhs); } if (rhs instanceof GraphPatternElement && ((GraphPatternElement)rhs).isEmbedded()) { rule.getIfs().add((GraphPatternElement) rhs); rhsRemoved = true; } else if (rhs instanceof Junction) { rhs = moveEmbeddedFromJunction(rule, (Junction) rhs); } if (lhsRemoved && rhsRemoved) { return null; } if (lhsRemoved) { return (GraphPatternElement) rhs; } if (rhsRemoved) { return (GraphPatternElement) lhs; } tgpe.setLhs(SadlModelProcessor.nodeCheck(lhs)); tgpe.setRhs(SadlModelProcessor.nodeCheck(rhs)); return tgpe; } /** * This Map keeps track of the ProxyNodes that have been retired by GraphPatternElements, allowing the retired * ProxyNode and its associated variable to be reused when that GraphPatternElement is revisited in another ProxyNode. */ private Map<GraphPatternElement, ProxyNode> retiredProxyNodes = new HashMap<GraphPatternElement, ProxyNode>(); /** * Top-level method for expanding ProxyNodes * * @param pattern * @param clearPreviousRetired TODO * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ public Object expandProxyNodes(Object pattern, boolean isRuleThen, boolean clearPreviousRetired) throws InvalidNameException, InvalidTypeException, TranslationException { if (clearPreviousRetired) { retiredProxyNodes.clear(); } List<GraphPatternElement> patterns = new ArrayList<GraphPatternElement>(); if (pattern instanceof List<?>) { for (int i = 0; i < ((List<?>)pattern).size(); i++) { expandProxyNodes(patterns, ((List<?>)pattern).get(i), isRuleThen); } } else { Object result = expandProxyNodes(patterns, pattern, isRuleThen); if (patterns.size() == 0) { return result; } } if (patterns.size() > 0) { patterns = decorateCRuleVariables((List<GraphPatternElement>) patterns, isRuleThen); if (!(getTarget() instanceof Test) && patterns.size() > 1) { patterns = listToAnd(patterns); } } return patterns; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#listToAnd(java.util.List) */ @Override public List<GraphPatternElement> listToAnd( List<GraphPatternElement> patterns) throws InvalidNameException, InvalidTypeException, TranslationException { if (patterns == null || patterns.size() == 0) { return null; } if (patterns.size() == 1) { return patterns; } GraphPatternElement lhs = patterns.remove(0); if (lhs instanceof List<?>) { lhs = listToAnd((List<GraphPatternElement>) lhs).get(0); } Junction jand = new Junction(); jand.setJunctionName("and"); jand.setLhs(SadlModelProcessor.nodeCheck(lhs)); if (patterns.size() > 1) { patterns = listToAnd(patterns); } GraphPatternElement rhs = patterns.get(0); if (rhs instanceof List<?>) { rhs = listToAnd((List<GraphPatternElement>) rhs).get(0); } jand.setRhs(SadlModelProcessor.nodeCheck(rhs)); patterns.set(0, jand); return patterns; } private GraphPatternElement listToOr(List<GraphPatternElement> patterns) throws InvalidNameException, InvalidTypeException, TranslationException { if (patterns == null || patterns.size() == 0) { return null; } if (patterns.size() == 1) { return patterns.get(0); } GraphPatternElement lhs = patterns.remove(0); Junction jor = new Junction(); jor.setJunctionName("or"); jor.setLhs(SadlModelProcessor.nodeCheck(lhs)); GraphPatternElement rhs = listToOr(patterns); jor.setRhs(SadlModelProcessor.nodeCheck(rhs)); return jor; } /** * Second-level method for expanding ProxyNodes--this one has a list of the results passed in as an argument * @param patterns * @param pattern * @param isRuleThen * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ protected Object expandProxyNodes(List<GraphPatternElement> patterns, Object pattern, boolean isRuleThen) throws InvalidNameException, InvalidTypeException, TranslationException { if (pattern instanceof ProxyNode) { return expandProxyNodes(patterns, ((ProxyNode)pattern).getProxyFor(), isRuleThen); } if (pattern instanceof TripleElement) { return expandProxyNodes(patterns,(TripleElement)pattern, isRuleThen); } else if (pattern instanceof BuiltinElement) { return expandProxyNodes(patterns, (BuiltinElement)pattern, isRuleThen); } else if (pattern instanceof Literal) { return pattern; } else if (pattern instanceof Junction) { Object retval = null; // remember what we have so far and create a new pattern list for each side of the Junction List<GraphPatternElement> existingPatterns = patterns; List<GraphPatternElement> lhsPatterns = new ArrayList<GraphPatternElement>(); List<GraphPatternElement> rhsPatterns = new ArrayList<GraphPatternElement>(); // get the two sides Object lhs = ((Junction)pattern).getLhs(); Object rhs = ((Junction)pattern).getRhs(); // at least handle the interesting special case where they are literals if (lhs instanceof Literal) { BuiltinElement lhsbe = new BuiltinElement(); lhsbe.setFuncName("=="); lhsbe.setCreatedFromInterval(true); lhsbe.addArgument(SadlModelProcessor.nodeCheck(lhs)); ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(lhsbe)); } else { expandProxyNodes(lhsPatterns, lhs, isRuleThen); if (lhsPatterns.size() == 1) { ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(lhsPatterns.get(0))); } else if (lhsPatterns.size() < 1) { ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(lhs)); } else { ((Junction)pattern).setLhs(SadlModelProcessor.nodeCheck(listToAnd(lhsPatterns).get(0))); // throw new TranslationException("LHS of a Junction should be a single GraphPatternElement: " + jctPatterns.toString()); } } if (rhs instanceof Literal) { BuiltinElement rhsbe = new BuiltinElement(); rhsbe.setFuncName("=="); rhsbe.setCreatedFromInterval(true); rhsbe.addArgument(SadlModelProcessor.nodeCheck(rhs)); retval = SadlModelProcessor.nodeCheck(rhsbe); ((Junction)pattern).setRhs(retval); } else { retval = expandProxyNodes(rhsPatterns, rhs, isRuleThen); if (rhsPatterns.size() == 1) { ((Junction)pattern).setRhs(SadlModelProcessor.nodeCheck(rhsPatterns.get(0))); } else if (rhsPatterns.size() < 1) { ((Junction)pattern).setRhs(SadlModelProcessor.nodeCheck(rhs)); } else { ((Junction)pattern).setRhs(SadlModelProcessor.nodeCheck(listToAnd(rhsPatterns).get(0))); // throw new TranslationException("RHS of a Junction should be a single GraphPatternElement: " + jctPatterns.toString()); } } patterns = existingPatterns; patterns.add((Junction)pattern); return retval; } return patterns; } /** * If a triple has a null, fill it with a variable (search the patterns list first to avoid duplicates), * add the triple to the patterns list, and return the variable. The variable also replaces the proxy node * that contained this triple. * @param patterns * @param te * @param expType * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ protected Object expandProxyNodes(List<GraphPatternElement> patterns, TripleElement te, boolean isRuleThen) throws InvalidNameException, InvalidTypeException, TranslationException { Node returnNode = null; Node retiredNode = findMatchingElementInRetiredProxyNodes(te); if (retiredNode != null && retiredNode instanceof ProxyNode) { retiredNode = ((ProxyNode)retiredNode).getReplacementNode(); } Node subj = te.getSubject(); if (subj instanceof ProxyNode) { if (retiredNode != null) { subj = returnNode = retiredNode; } else if (((ProxyNode)subj).getReplacementNode() != null) { if (!patterns.contains(((ProxyNode)subj).getProxyFor())) { patterns.add((GraphPatternElement) ((ProxyNode)subj).getProxyFor()); retiredProxyNodes.put((GraphPatternElement)((ProxyNode)subj).getProxyFor(), (ProxyNode) subj); } subj = returnNode = ((ProxyNode)subj).getReplacementNode(); } else { Object realSubj = ((ProxyNode)subj).getProxyFor(); Object subjNode = expandProxyNodes(patterns, realSubj, isRuleThen); if (subjNode == null && realSubj instanceof TripleElement) { if (((TripleElement)realSubj).getObject() instanceof VariableNode) { subjNode = ((TripleElement)realSubj).getObject(); } else if (te.getSourceType() != null && te.getSourceType().equals(TripleSourceType.SPV)) { subjNode = ((TripleElement)realSubj).getSubject(); } } ((ProxyNode)subj).setReplacementNode(SadlModelProcessor.nodeCheck(subjNode)); retiredProxyNodes.put((GraphPatternElement) realSubj, (ProxyNode)subj); subj = SadlModelProcessor.nodeCheck(subjNode); if (realSubj instanceof TripleElement && ((TripleElement)realSubj).getSourceType() != null && ((TripleElement)realSubj).getSourceType().equals(TripleSourceType.ITC)) { returnNode = subj; } } te.setSubject(subj); patterns.add(te); } else if (subj == null) { // this is a triple with a need for a variable for subject returnNode = retiredNode != null ? retiredNode : getVariableNode(subj, te.getPredicate(), te.getObject(), true); te.setSubject(returnNode); // TODO when this is nested the triple (te) needs to be inserted before the returnNode is used patterns.add(te); } Node obj = te.getObject(); if (obj instanceof ProxyNode) { int initialPatternLength = patterns == null ? 0 : patterns.size(); if (retiredNode != null) { obj = returnNode = retiredNode; } else if (((ProxyNode)obj).getReplacementNode() != null) { if (!patterns.contains(((ProxyNode)obj).getProxyFor())) { patterns.add((GraphPatternElement) ((ProxyNode)obj).getProxyFor()); retiredProxyNodes.put((GraphPatternElement)((ProxyNode)obj).getProxyFor(), (ProxyNode) obj); } obj = returnNode = ((ProxyNode)obj).getReplacementNode(); } else { Object realObj = ((ProxyNode)obj).getProxyFor(); List<GraphPatternElement> rememberedPatterns = null; if (realObj instanceof BuiltinElement && isRuleThen) { rememberedPatterns = patterns; patterns = new ArrayList<GraphPatternElement>(); } Object objNode = expandProxyNodes(patterns, realObj, isRuleThen); if (objNode == null && ((ProxyNode)obj).getReplacementNode() != null) { // This can happen because the proxy node gets processed but not returned objNode = ((ProxyNode)obj).getReplacementNode(); } if (objNode == null && (realObj instanceof BuiltinElement || (realObj instanceof Junction && ((Junction)realObj).getLhs() instanceof BuiltinElement && ((Junction)realObj).getRhs() instanceof BuiltinElement))) { List<BuiltinElement> builtins = new ArrayList<BuiltinElement>(); Node newNode = null; if (realObj instanceof BuiltinElement) { builtins.add((BuiltinElement)realObj); newNode = getVariableNode((BuiltinElement)realObj); } else { builtins.add((BuiltinElement)((Junction)realObj).getLhs()); newNode = getVariableNode(builtins.get(0)); builtins.add((BuiltinElement)((Junction)realObj).getRhs()); } for (int i = 0; i < builtins.size(); i++) { BuiltinElement bi = builtins.get(i); if (bi.isCreatedFromInterval()) { bi.addArgument(0, newNode); } else { bi.addArgument(newNode); } } objNode = newNode; if (isRuleThen) { addToPremises(patterns); patterns = rememberedPatterns; } } if (objNode == null) { addError(new IFTranslationError("Translation to Intermediate Form failed: " + te.toString())); } ((ProxyNode)obj).setReplacementNode(SadlModelProcessor.nodeCheck(objNode)); // TODO this has a problem, run on TestSadlIde/Sandbox/UnionClassInRule.sadl retiredProxyNodes.put((GraphPatternElement) ((ProxyNode)obj).getProxyFor(), (ProxyNode)obj); obj = SadlModelProcessor.nodeCheck(objNode); } te.setObject(obj); if (!patterns.contains(te)) { if (getTarget() instanceof Rule) { patterns.add(te); } else { patterns.add(Math.max(0, initialPatternLength - 1), te); } } } else if (obj == null) { returnNode = retiredNode != null ? retiredNode : getVariableNode(subj, te.getPredicate(), obj, false); te.setObject(returnNode); if (!patterns.contains(te)) { patterns.add(te); } } if (te.getNext() != null) { GraphPatternElement nextGpe = te.getNext(); te.setNext(null); if (!patterns.contains(te)) { patterns.add(te); } Object nextResult = expandProxyNodes(patterns, nextGpe, isRuleThen); // TODO we don't need to do anything with this, right? } // Special case: a pivot triple ( something type something): return the subject if (te instanceof TripleElement && (((TripleElement)te).getPredicate()) instanceof RDFTypeNode) { // this is an embedded type triple; only the subject can be a subject of the higher-level pattern if (!patterns.contains(te)) { patterns.add(te); } return ((TripleElement)te).getSubject(); } // This is to make sure that complete, self-contained triple elements are still added to the output if (!patterns.contains(te)) { patterns.add(te); } if (retiredNode != null) { return retiredNode; } return returnNode; } /** * This method is currently just a placeholder for finding variables for reuse in built-in patterns. * Currently it just creates a new variable with a new name. * @param bltin * @return */ protected VariableNode getVariableNode(BuiltinElement bltin) { if (getTarget() != null) { } return new VariableNode(getNewVar()); } /** * This method looks in the clauses of a Rule to see if there is already a triple matching the given pattern. If there is * a new variable of the same name is created (to make sure the count is right) and returned. If not a rule or no match * a new variable (new name) is created and returned. * @param subject * @param predicate * @param object * @param varIsSubject * @return */ protected VariableNode getVariableNode(Node subject, Node predicate, Node object, boolean varIsSubject) { VariableNode var = findVariableInTargetForReuse(subject, predicate, object); if (var != null) { // return new VariableNode(var.getName()); return var; } if (predicate != null) { var = new VariableNode(getNewVar()); Property prop = this.getTheJenaModel().getProperty(predicate.toFullyQualifiedString()); try { ConceptName propcn = new ConceptName(predicate.toFullyQualifiedString()); propcn.setType(ConceptType.RDFPROPERTY); // assume the most general if (varIsSubject) { // type is domain TypeCheckInfo dtci = getModelValidator().getTypeInfoFromDomain(propcn, prop, null); if (dtci != null && dtci.getTypeCheckType() != null) { Node tcitype = dtci.getTypeCheckType(); if (tcitype instanceof NamedNode) { NamedNode defn; defn = new NamedNode(((NamedNode)tcitype).toFullyQualifiedString(), ((NamedNode)tcitype).getNodeType()); var.setType(modelProcessor.validateNode(defn)); } else { addError(new IFTranslationError("Domain type did not return a ConceptName.")); } } } else { // type is range TypeCheckInfo dtci; dtci = getModelValidator().getTypeInfoFromRange(propcn, prop, null); if (dtci != null && dtci.getTypeCheckType() != null) { Node tcitype = dtci.getTypeCheckType(); if (tcitype instanceof NamedNode) { NamedNode defn; defn = new NamedNode(((NamedNode)tcitype).toFullyQualifiedString(), ((NamedNode)tcitype).getNodeType()); var.setType(modelProcessor.validateNode(defn)); } else { addError(new IFTranslationError("Range type did not return a ConceptName.")); } } } } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DontTypeCheckException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return var; } protected VariableNode findVariableInTargetForReuse(Node subject, Node predicate, Node object) { // Note: when we find a match we still create a new VariableNode with the same name in order to have the right reference counts for the new VariableNode if (getTarget() instanceof Rule) { VariableNode var = findVariableInTripleForReuse(((Rule)getTarget()).getGivens(), subject, predicate, object); if (var != null) { return var; } var = findVariableInTripleForReuse(((Rule)getTarget()).getIfs(), subject, predicate, object); if (var != null) { return var; } var = findVariableInTripleForReuse(((Rule)getTarget()).getThens(), subject, predicate, object); if (var != null) { return var; } } return null; } private JenaBasedSadlModelValidator getModelValidator() throws TranslationException { if (getModelProcessor() != null) { return getModelProcessor().getModelValidator(); } return null; } /** * Supporting method for the method above (getVariableNode(Node, Node, Node)) * @param gpes * @param subject * @param predicate * @param object * @return */ protected VariableNode findVariableInTripleForReuse(List<GraphPatternElement> gpes, Node subject, Node predicate, Node object) { if (gpes != null) { Iterator<GraphPatternElement> itr = gpes.iterator(); while (itr.hasNext()) { GraphPatternElement gpe = itr.next(); VariableNode var = findVariableInTargetForReuse(gpe, subject, predicate, object); if (var != null) { return var; } } } return null; } private VariableNode findVariableInTargetForReuse(GraphPatternElement gpe, Node subject, Node predicate, Node object) { while (gpe != null) { if (gpe instanceof TripleElement) { VariableNode var = findVariableInTripleForReuse((TripleElement)gpe, subject, predicate, object); if (var != null) { return var; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); if (args != null) { for (Node arg: args) { if (arg instanceof ProxyNode && ((ProxyNode)arg).getProxyFor() instanceof GraphPatternElement) { VariableNode var = findVariableInTargetForReuse((GraphPatternElement)((ProxyNode)arg).getProxyFor(), subject, predicate, object); if (var != null) { return var; } } } } } else if (gpe instanceof Junction) { Object lhs = ((Junction)gpe).getLhs(); if (lhs instanceof GraphPatternElement) { VariableNode var = findVariableInTargetForReuse((GraphPatternElement)lhs, subject, predicate, object); if (var != null) { return var; } } Object rhs = ((Junction)gpe).getRhs(); if (rhs instanceof GraphPatternElement) { VariableNode var = findVariableInTargetForReuse((GraphPatternElement)rhs, subject, predicate, object); if (var != null) { return var; } } } gpe = gpe.getNext(); } return null; } protected VariableNode findVariableInTripleForReuse(TripleElement tr, Node subject, Node predicate, Node object) { Node tsn = tr.getSubject(); Node tpn = tr.getPredicate(); Node ton = tr.getObject(); if (subject == null && tsn instanceof VariableNode) { if (predicate != null && predicate.equals(tpn) && object != null && object.equals(ton)) { return (VariableNode) tsn; } } if (predicate == null && tpn instanceof VariableNode) { if (subject != null && subject.equals(tsn) && object != null && object.equals(ton)) { return (VariableNode) tpn; } } if (object == null && ton instanceof VariableNode) { if (subject != null && subject.equals(tsn) && predicate != null && predicate.equals(tpn)) { return (VariableNode) ton; } } return null; } protected String getNewVar() { String proposedName = "v" + vNum; while (userDefinedVariables.contains(proposedName) // || // !modelManager.getConceptType(proposedName).equals(ConceptType.CONCEPT_NOT_FOUND_IN_MODEL) ) { vNum++; proposedName = "v" + vNum; } vNum++; return proposedName; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#setStartingVariableNumber(int) */ @Override public void setStartingVariableNumber(int vn) { vNum = vn; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#getVariableNumber() */ @Override public int getVariableNumber() { return vNum; } private Node findMatchingElementInRetiredProxyNodes(GraphPatternElement ge) { if (retiredProxyNodes != null) { if (retiredProxyNodes.get(ge) != null) { return retiredProxyNodes.get(ge); } else { if (ge instanceof TripleElement && !(((TripleElement)ge).getPredicate() instanceof RDFTypeNode)) { TripleElement te = (TripleElement) ge; Iterator<GraphPatternElement> itr = retiredProxyNodes.keySet().iterator(); while (itr.hasNext()) { GraphPatternElement gpe = itr.next(); if (gpe instanceof TripleElement && !(((TripleElement)gpe).getPredicate() instanceof RDFTypeNode)) { if ((te.getSubject() == null || te.getSubject().equals(((TripleElement)gpe).getSubject())) && (te.getPredicate() == null || te.getPredicate().equals(((TripleElement)gpe).getPredicate())) && (te.getObject() == null || te.getObject().equals(((TripleElement)gpe).getObject()))) { ProxyNode pn = retiredProxyNodes.get(gpe); return pn.getReplacementNode(); } } } } } } return null; } /** * Method to handle BuiltinElements--if the * @param patterns * @param be * @return * @throws InvalidNameException * @throws InvalidTypeException * @throws TranslationException */ protected Object expandProxyNodes(List<GraphPatternElement> patterns, BuiltinElement be, boolean isRuleThen) throws InvalidNameException, InvalidTypeException, TranslationException { int patternsSize = patterns != null ? patterns.size() : 0; Node returnNode = null; Node retiredNode = findMatchingElementInRetiredProxyNodes(be); boolean isNotOfEqual = false; if (isRuleThen && (be.getFuncType().equals(BuiltinType.Equal) || be.getFuncType().equals(BuiltinType.Assign)) && be.getArguments() != null && be.getArguments().size() == 2 && be.getArguments().get(0) instanceof ProxyNode && be.getArguments().get(1) instanceof ProxyNode) { ProxyNode arg1PN = (ProxyNode) be.getArguments().get(0); ProxyNode arg2PN = (ProxyNode) be.getArguments().get(1); Object realArgForThen = arg1PN.getProxyFor(); Object realArgForIfs = arg2PN.getProxyFor(); int tripleWithObjectNullCount = 0; if (realArgForThen instanceof TripleElement && realArgForIfs instanceof TripleElement) { // // args can be TripleElement only if both are and objects are both null if (((TripleElement)realArgForThen).getObject() == null) { tripleWithObjectNullCount++; } if (((TripleElement)realArgForIfs).getObject() == null) { tripleWithObjectNullCount++; } if (tripleWithObjectNullCount == 1) { addError(new IFTranslationError("Translation to Intermediate Form encountered error (" + be.toString() + "); try separating rule elements with ands.")); } } List<GraphPatternElement> moveToIfts = new ArrayList<GraphPatternElement>(); Object finalIfsVar = expandProxyNodes(moveToIfts, realArgForIfs, false); if (finalIfsVar == null && realArgForIfs instanceof BuiltinElement) { Node newNode = getVariableNode((BuiltinElement)realArgForIfs); ((BuiltinElement)realArgForIfs).addArgument(newNode); finalIfsVar = newNode; ((ProxyNode)arg1PN).setReplacementNode(SadlModelProcessor.nodeCheck(finalIfsVar)); retiredProxyNodes.put((GraphPatternElement) realArgForIfs, arg1PN); } if (realArgForThen instanceof TripleElement && ((TripleElement)realArgForThen).getObject() == null) { Object finalThensVar = expandProxyNodes(patterns, realArgForThen, isRuleThen); ((TripleElement)realArgForThen).setObject(SadlModelProcessor.nodeCheck(finalIfsVar)); if (!patterns.contains((TripleElement)realArgForThen)) { patterns.add((TripleElement)realArgForThen); } if (be.getFuncName().equals("assign")) { ((TripleElement)realArgForThen).setType(TripleModifierType.Assignment); } } else if (realArgForThen instanceof BuiltinElement && ((BuiltinElement)realArgForThen).getArguments() != null) { if (((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1) == null) { ((BuiltinElement)realArgForThen).getArguments().set(((BuiltinElement)realArgForThen).getArguments().size() - 1, SadlModelProcessor.nodeCheck(finalIfsVar)); } else if (((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1) instanceof ProxyNode && ((ProxyNode)((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1)).getProxyFor() instanceof TripleElement && ((TripleElement)((ProxyNode)((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1)).getProxyFor()).getObject() == null) { ((TripleElement)((ProxyNode)((BuiltinElement)realArgForThen).getArguments().get(((BuiltinElement)realArgForThen).getArguments().size() - 1)).getProxyFor()).setObject(SadlModelProcessor.nodeCheck(finalIfsVar)); } else { throw new TranslationException("Unhandled condition, LHS of Equal in Then isn't a BuiltinElement that needs an argument: " + realArgForThen.toString()); } } else if (realArgForThen instanceof Junction) { List<GraphPatternElement> lst = junctionToList((Junction)realArgForThen); GraphPatternElement last = lst.remove(lst.size() - 1); moveToIfts.addAll(lst); patterns.add(last); } else if (realArgForThen instanceof GraphPatternElement){ moveToIfts.add((GraphPatternElement) realArgForThen); } if (!addToPremises(moveToIfts)) { patterns.addAll(patternsSize, moveToIfts); } return null; } else if (getTarget() instanceof Rule && (be.getFuncType().equals(BuiltinType.Equal) || be.getFuncType().equals(BuiltinType.Assign))) { if (be.getArguments().size() == 2) { // this should always be true if (be.getArguments().get(0) instanceof VariableNode && be.getArguments().get(1) instanceof ProxyNode) { Object realArg2 = ((ProxyNode)be.getArguments().get(1)).getProxyFor(); if (realArg2 instanceof BuiltinElement) { ((BuiltinElement)realArg2).addArgument(be.getArguments().get(0)); // the variable goes to return from arg 2 builtin and this builtin goes away return expandProxyNodes(patterns, realArg2, isRuleThen); } else if (realArg2 instanceof TripleElement && ((TripleElement)realArg2).getObject() == null) { ((TripleElement)realArg2).setObject(be.getArguments().get(0)); // the variable goes to the object of the arg 2 triple and this builtin goes away return expandProxyNodes(patterns, realArg2, isRuleThen); } } else if ((be.getArguments().get(1) instanceof Literal || be.getArguments().get(1) instanceof ConstantNode || (be.getArguments().get(1) instanceof NamedNode && ((NamedNode)be.getArguments().get(1)).getNodeType().equals(NodeType.InstanceNode)) || be.getArguments().get(1) instanceof VariableNode) && be.getArguments().get(0) instanceof ProxyNode && ((ProxyNode)be.getArguments().get(0)).getProxyFor() instanceof TripleElement && ((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).getObject() == null) { ((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).setObject(be.getArguments().get(1)); patterns.add(((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor())); if (be.getFuncName().equals("assign")) { ((TripleElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).setType(TripleModifierType.Assignment); } return null; } } } else if (getTarget() instanceof Rule && be.getFuncType().equals(BuiltinType.Not) && be.getArguments().get(0) instanceof ProxyNode && ((ProxyNode)be.getArguments().get(0)).getProxyFor() instanceof BuiltinElement && ((BuiltinElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()).getFuncType().equals(BuiltinType.Equal)) { BuiltinElement eqb = ((BuiltinElement)((ProxyNode)be.getArguments().get(0)).getProxyFor()); Node arg0 = eqb.getArguments().get(0); Node arg1 = eqb.getArguments().get(1); if (arg0 instanceof ProxyNode && ((ProxyNode)arg0).getProxyFor() instanceof TripleElement && ((arg1 instanceof ProxyNode && ((ProxyNode)arg1).getProxyFor() instanceof TripleElement && ((TripleElement)((ProxyNode)arg1).getProxyFor()).getObject() == null)) || arg1 instanceof NamedNode){ // this is of the form: not(is(rdf(s1,p1,v1), rdf(s2,p2,null))) where v1 might also be null // so we want to transform into: rdf(s1,p1,v1), not(rdf(s2,p2,v1)) isNotOfEqual = true; } } if (retiredNode != null && retiredNode instanceof ProxyNode) { retiredNode = ((ProxyNode)retiredNode).getReplacementNode(); } List<Node> args = be.getArguments(); for (int i = 0; args != null && i < args.size(); i++) { Node arg = args.get(i); if (arg == null) { VariableNode var = new VariableNode(getNewVar()); args.set(i, var); returnNode = var; } else if (arg instanceof ProxyNode) { if (retiredNode != null) { args.set(i, retiredNode); } else { Object realArg = ((ProxyNode)arg).getProxyFor(); Object argNode = expandProxyNodes(patterns, realArg, isRuleThen); if (argNode == null) { if (realArg instanceof BuiltinElement) { if (be.getFuncType().equals(BuiltinType.Not)) { if (patterns.get(patterns.size() - 1).equals(realArg)) { // don't put in an intermediate variable for negation of a builtin--if needed the language-specific translator will need to do that // the call above to expandProxyNodes might have put the argNode into the patterns; if so remove it patterns.remove(patterns.size() - 1); if (isNotOfEqual) { TripleElement firstTriple = (TripleElement) patterns.get(patterns.size() - 2); TripleElement secondTriple = (TripleElement) patterns.get(patterns.size() - 1); if (!isRuleThen && !ruleThensContainsTriple(secondTriple)) { if (retiredProxyNodes.containsKey(secondTriple)) { retiredProxyNodes.remove(secondTriple); } secondTriple.setObject(firstTriple.getObject()); secondTriple.setType(TripleModifierType.Not); } else { TripleElement newTriple = new TripleElement(secondTriple.getSubject(), secondTriple.getPredicate(), firstTriple.getObject()); newTriple.setType(TripleModifierType.Not); patterns.add(newTriple); } } } else if (isNotOfEqual && patterns.get(patterns.size() - 1) instanceof TripleElement) { ((TripleElement)patterns.get(patterns.size() - 1)).setType(TripleModifierType.Not); } } else if (((BuiltinElement)realArg).getArguments() != null && getModelProcessor().isBuiltinMissingArgument(((BuiltinElement)realArg).getFuncName(), ((BuiltinElement)realArg).getArguments().size())){ Node newNode = getVariableNode((BuiltinElement)realArg); ((BuiltinElement)realArg).addArgument(newNode); argNode = newNode; ((ProxyNode)arg).setReplacementNode(SadlModelProcessor.nodeCheck(argNode)); retiredProxyNodes.put((GraphPatternElement) realArg, (ProxyNode)arg); args.set(i, SadlModelProcessor.nodeCheck(argNode)); } } else if (realArg instanceof TripleElement) { // don't do anything--keep proxy if triple, negate triple if "not" builtin if (patterns.get(patterns.size() - 1).equals(realArg)) { if (be.getFuncType().equals(BuiltinType.Not)) { ((TripleElement)realArg).setType(TripleModifierType.Not); return realArg; // "not" is a unary operator, so it is safe to assume this is the only argument } else if (be.getFuncName().equals(JenaBasedSadlModelProcessor.THERE_EXISTS) && ((TripleElement)realArg).getSubject() instanceof VariableNode){ be.getArguments().set(0, ((TripleElement)realArg).getSubject()); patterns.add(patterns.size() - 1, be); return null; } } } else if (realArg instanceof Junction) { patterns.remove(patterns.size() - 1); } else { throw new TranslationException("Unexpected real argument"); } } else { ((ProxyNode)arg).setReplacementNode(SadlModelProcessor.nodeCheck(argNode)); if (realArg instanceof GraphPatternElement) { retiredProxyNodes.put((GraphPatternElement) realArg, (ProxyNode)arg); } else { throw new TranslationException("Expected GraphPatternElement in ProxyNode but got " + realArg.getClass().getCanonicalName()); } args.set(i, SadlModelProcessor.nodeCheck(argNode)); } } } } if (be.getFuncName().equals(JenaBasedSadlModelProcessor.THERE_EXISTS)) { if (patterns.size() == 0) { patterns.add(be); } else { // patterns.add(patterns.size() - 1, be); patterns.add(be); } returnNode = be.getArguments() != null ? be.getArguments().get(0) : null; // this can occur during editing } else if (!isNotOfEqual) { removeArgsFromPatterns(patterns, be); patterns.add(be); } return returnNode; } private boolean ruleThensContainsTriple(TripleElement triple) { if (getTarget() instanceof Rule) { List<GraphPatternElement> thens = ((Rule)getTarget()).getThens(); for (GraphPatternElement then : thens) { if (graphPatternsMatch(then, triple)) { return true; } } } return false; } private boolean graphPatternsMatch(GraphPatternElement gp, TripleElement tr) { if (gp instanceof TripleElement) { if (((TripleElement)gp).getSubject().equals(tr.getSubject()) && ((TripleElement)gp).getPredicate().equals(tr.getPredicate())) { return true; } } else if (gp instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gp).getArguments(); for (Node arg : args) { if (arg instanceof ProxyNode) { GraphPatternElement argGp = ((ProxyNode)arg).getProxyFor(); if (graphPatternsMatch(argGp, tr)) { return true; } } } } else if (gp instanceof Junction) { Object lhs = ((Junction)gp).getLhs(); if (lhs instanceof ProxyNode) { if (graphPatternsMatch(((ProxyNode)lhs).getProxyFor(), tr)) { return true; } } Object rhs = ((Junction)gp).getRhs(); if (rhs instanceof ProxyNode) { if (graphPatternsMatch(((ProxyNode)rhs).getProxyFor(), tr)) { return true; } } } return false; } //Removed implied properties from graph pattern element /*private Object applyExpandedAndImpliedProperties(List<GraphPatternElement> patterns, BuiltinElement be, Object realArgForThen, List<GraphPatternElement> moveToIfts, Object finalIfsVar) throws TranslationException, InvalidNameException, InvalidTypeException { if (be.getExpandedPropertiesToBeUsed() != null) { // create a new VariableNode of the same type as finalIfsVar VariableNode thereExistsVar = getVariableNode(be); thereExistsVar.setType(((VariableNode)finalIfsVar).getType()); ((TripleElement)realArgForThen).setObject(thereExistsVar); BuiltinElement thereExistsBe = new BuiltinElement(); thereExistsBe.setFuncName(JenaBasedSadlModelProcessor.THERE_EXISTS); thereExistsBe.addArgument(thereExistsVar); patterns.add(patterns.size() - 1, thereExistsBe); for (NamedNode ep: be.getExpandedPropertiesToBeUsed()) { VariableNode newVar = null; boolean createTriple = false; if (finalIfsVar instanceof Node) { newVar = findVariableInTargetForReuse((Node)finalIfsVar, ep, null); if (newVar == null) { createTriple = true; newVar = getVariableNode(be); } } TripleElement epTriple = new TripleElement(SadlModelProcessor.nodeCheck(thereExistsVar), ep, newVar); patterns.add(epTriple); if (createTriple) { TripleElement epTriple2 = new TripleElement(SadlModelProcessor.nodeCheck(finalIfsVar), ep, newVar); moveToIfts.add(epTriple2); } } } else if (be.getLeftImpliedPropertyUsed() != null) { VariableNode newVar = null; boolean createTriple = false; if (finalIfsVar instanceof Node) { newVar = findVariableInTargetForReuse((Node) finalIfsVar, be.getLeftImpliedPropertyUsed(), null); if (newVar == null) { createTriple = true; newVar = getVariableNode((Node) finalIfsVar, be.getLeftImpliedPropertyUsed(), null, false); } } if (createTriple) { TripleElement epTriple = new TripleElement(SadlModelProcessor.nodeCheck(finalIfsVar), SadlModelProcessor.nodeCheck(be.getLeftImpliedPropertyUsed()), newVar); patterns.add(epTriple); } return newVar; } else if (be.getRightImpliedPropertyUsed() != null) { VariableNode newVar = null; boolean createTriple = false; if (finalIfsVar instanceof Node) { newVar = findVariableInTargetForReuse((Node)finalIfsVar, be.getRightImpliedPropertyUsed(), null); if (newVar == null) { createTriple = true; newVar =getVariableNode((Node) finalIfsVar, be.getRightImpliedPropertyUsed(), null, false); } } if (createTriple) { TripleElement epTriple = new TripleElement(SadlModelProcessor.nodeCheck(finalIfsVar), SadlModelProcessor.nodeCheck(be.getRightImpliedPropertyUsed()), newVar); moveToIfts.add(epTriple); } return newVar; } return null; } */ private void removeArgsFromPatterns(List<GraphPatternElement> patterns, BuiltinElement be) { if (patterns != null && patterns.size() > 0) { List<Node> args = be.getArguments(); if (args != null) { for (Node arg:args) { Object effectiveArg = arg; if (arg instanceof ProxyNode) { effectiveArg = ((ProxyNode)arg).getProxyFor(); } if (effectiveArg instanceof GraphPatternElement) { if (patterns.contains((GraphPatternElement)effectiveArg)) { patterns.remove((GraphPatternElement)effectiveArg); } if (effectiveArg instanceof BuiltinElement) { removeArgsFromPatterns(patterns, (BuiltinElement)effectiveArg); } } } } } } /** * Combine the argument elements with the existing Rule Ifs elements * @param moveToIfts * @throws TranslationException */ protected boolean addToPremises(List<GraphPatternElement> moveToIfts) throws TranslationException { if (getTarget() instanceof Rule) { List<GraphPatternElement> ifts = ((Rule)getTarget()).getIfs(); if (ifts == null) { ((Rule)getTarget()).setIfs(moveToIfts); } else { ifts.addAll(moveToIfts); } return true; } return false; } /** * This method flattens out the GraphPatternElement List so that there are no * next pointers within the list. * * @param list - input GraphPatternElement List that may have chained elements inside it * @return - the transformed list * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ private List<GraphPatternElement> flattenLinkedList(List<GraphPatternElement> list) throws InvalidNameException, InvalidTypeException, TranslationException { // go backwards through list so that the i index will remain valid for (int i = list.size() -1; i >= 0; i--) { GraphPatternElement element = list.get(i); if (element instanceof Junction) { flattenJunction((Junction)element); } GraphPatternElement nextElement = element.getNext(); // an internal chain int j = 0; while (nextElement != null) { element.setNext(null); list.add((1+i+(j++)),nextElement); element = nextElement; nextElement = element.getNext(); } } return list; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#flattenJunction(com.ge.research.sadl.model.gp.Junction) */ @Override public void flattenJunction(Junction element) throws InvalidNameException, InvalidTypeException, TranslationException { Object lhs = element.getLhs(); if (lhs instanceof Junction) { flattenJunction((Junction)lhs); } else if (lhs instanceof GraphPatternElement && ((GraphPatternElement)lhs).getNext() != null) { element.setLhs(SadlModelProcessor.nodeCheck(flattenJunctionSide((GraphPatternElement) lhs))); } Object rhs = element.getRhs(); if (rhs instanceof Junction) { flattenJunction((Junction)rhs); } else if (rhs instanceof GraphPatternElement && ((GraphPatternElement)rhs).getNext() != null) { element.setRhs(SadlModelProcessor.nodeCheck(flattenJunctionSide((GraphPatternElement) rhs))); } } private Object flattenJunctionSide(GraphPatternElement gpe) throws InvalidNameException, InvalidTypeException, TranslationException { if (gpe.getNext() != null) { List<GraphPatternElement> lst = new ArrayList<GraphPatternElement>(); lst.add(gpe); lst = flattenLinkedList(lst); return lst; } return gpe; } private void removeDuplicateElements(Rule rule) throws InvalidNameException, InvalidTypeException, TranslationException { List<GraphPatternElement> givens = rule.getGivens(); List<GraphPatternElement> ifs = rule.getIfs(); List<GraphPatternElement> thens = rule.getThens(); removeDuplicates(thens, thens, true); // remove anything duplicated in thens // removeDuplicates(thens, ifs, false); // remove anything in ifs from thens // removeDuplicates(thens, givens, false); // remove anything in givens from thens removeDuplicates(ifs, ifs, true); // remove anything duplicated in ifs removeDuplicates(ifs, givens, false); // remove anything in givens from ifs removeDuplicates(givens, givens, true); // remove anything duplicated in givens } /** * If an element in list1 is also in list2, remove the element from list1 * * @param list1 * @param list2 * @param bRetainFirst -- true if same lists; if same lists leave first occurance * @throws TranslationException * @throws InvalidTypeException * @throws InvalidNameException */ protected int removeDuplicates(List<GraphPatternElement> list1, List<GraphPatternElement> list2, boolean bRetainFirst) throws InvalidNameException, InvalidTypeException, TranslationException { if (list1 == null || list2 == null || list1.size() < 1 || list2.size() < 1) { return 0; } List<GraphPatternElement> flatList2 = getAllGPEs(list2); int removalCnt = 0; List<Integer> toBeRemoved = null; for (int idx2 = 0; idx2 < flatList2.size(); idx2++) { GraphPatternElement gpeToMatch = flatList2.get(idx2); // this is the element we are considering for duplicate removals boolean foundFirst = false; for (int idx1 = 0; idx1 < list1.size(); idx1++) { GraphPatternElement gpe = list1.get(idx1); if (gpe.equals(gpeToMatch)) { if (!bRetainFirst || foundFirst) { if (toBeRemoved == null) { toBeRemoved = new ArrayList<Integer>(); } if (!toBeRemoved.contains(idx1)) { toBeRemoved.add(idx1); removalCnt++; } } foundFirst = true; } else if (gpe instanceof Junction && ((Junction)gpe).getJunctionType().equals(JunctionType.Conj)) { Object[] results = removeJunctionDuplicates((Junction)gpe, gpeToMatch, bRetainFirst, foundFirst, removalCnt); GraphPatternElement processedGpe = (GraphPatternElement) results[0]; foundFirst = ((Boolean)results[1]).booleanValue(); removalCnt = ((Integer)results[2]).intValue(); if (!processedGpe.equals(gpe)) { list1.set(idx1, processedGpe); } } } } if (toBeRemoved != null) { Collections.sort(toBeRemoved); for (int i = (toBeRemoved.size() - 1); i >= 0; i--) { list1.remove(toBeRemoved.get(i).intValue()); } } return removalCnt; } private Object[] removeJunctionDuplicates(Junction gpe, GraphPatternElement gpeToMatch, boolean bRetainFirst, boolean foundFirst, int removalCnt) throws InvalidNameException, InvalidTypeException, TranslationException { boolean lhsDuplicate = false; boolean rhsDuplicate = false; Object lhs = gpe.getLhs(); if (lhs.equals(gpeToMatch)) { if(!bRetainFirst || foundFirst){ lhsDuplicate = true; } foundFirst = true; } else if (lhs instanceof Junction && ((Junction)lhs).getJunctionType().equals(JunctionType.Conj)) { Object[] lhsResults = removeJunctionDuplicates((Junction)lhs, gpeToMatch, bRetainFirst, foundFirst, removalCnt); GraphPatternElement newLhs = (GraphPatternElement) lhsResults[0]; foundFirst = ((Boolean)lhsResults[1]).booleanValue(); removalCnt = ((Integer)lhsResults[2]).intValue(); if (!newLhs.equals(lhs)) { gpe.setLhs(SadlModelProcessor.nodeCheck(newLhs)); } } Object rhs = gpe.getRhs(); if (rhs != null && rhs.equals(gpeToMatch)) { if (!bRetainFirst || foundFirst) { rhsDuplicate = true; } foundFirst = true; } else if (rhs instanceof Junction && ((Junction)rhs).getJunctionType().equals(JunctionType.Conj)) { Object[] rhsResults = removeJunctionDuplicates((Junction)rhs, gpeToMatch, bRetainFirst, foundFirst, removalCnt); GraphPatternElement newrhs = (GraphPatternElement) rhsResults[0]; foundFirst = ((Boolean)rhsResults[1]).booleanValue(); removalCnt = ((Integer)rhsResults[2]).intValue(); if (!newrhs.equals(rhs)) { gpe.setRhs(SadlModelProcessor.nodeCheck(newrhs)); } } Object[] results = new Object[3]; if (lhsDuplicate) { results[0] = gpe.getRhs(); } else if (rhsDuplicate) { results[0] = gpe.getLhs(); } else { results[0] = gpe; } results[1] = new Boolean(foundFirst); results[2] = new Integer(removalCnt); return results; } private List<GraphPatternElement> getAllGPEs(List<GraphPatternElement> list) throws TranslationException { List<GraphPatternElement> results = null; for (int i = 0; list != null && i < list.size(); i++) { GraphPatternElement gpe = list.get(i); if (gpe instanceof Junction && ((Junction)gpe).getJunctionType().equals(JunctionType.Conj)) { if (results != null) { results.addAll(junctionToList((Junction) gpe)); } else { results = junctionToList((Junction) gpe); } } else { if (results == null) { results = new ArrayList<GraphPatternElement>(); } results.add(gpe); } } if (results != null) { return results; } return list; } /** * Method to convert a Junction to a List<GraphPatternElement>. Note that this method will either handle * conjunction or disjunction at the top level but once the type is set the other type will not be converted * to a list as if both were converted the results would be non-functional. * @param gpe * @return * @throws TranslationException */ public static List<GraphPatternElement> junctionToList(Junction gpe) throws TranslationException { List<GraphPatternElement> lResult = new ArrayList<>(); List<Node> lProxies = junctionToNodeList(gpe); for( Node lProxy : lProxies ) { if( lProxy instanceof ProxyNode ) { lResult.add(((ProxyNode)lProxy).getProxyFor()); } else { throw new TranslationException("junctionToGraphPatternList called on junction which includes a non-GraphPatternElement; this is not supported."); } } return lResult; } /** * Method to convert a Junction to a List<Node>. Note that this method will either handle * conjunction or disjunction at the top level but once the type is set the other type will not be converted * to a list as if both were converted the results would be non-functional. * @param gpe * @return */ public static List<Node> junctionToNodeList(Junction gpe) { List<Node> lResult = new ArrayList<>(1); if ( JunctionType.Conj.equals(gpe.getJunctionType()) ) { lResult = conjunctionToList(gpe); } else if ( JunctionType.Disj.equals(gpe.getJunctionType()) ) { lResult = disjunctionToList(gpe); } else { try { lResult.add(new ProxyNode(gpe)); } catch ( InvalidTypeException e ) {} } return lResult; } public static List<Node> conjunctionToList(Junction gpe) { List<Node> lResult = new ArrayList<>(); Node lhs = (Node)gpe.getLhs(); if (lhs instanceof ProxyNode) { GraphPatternElement lhsProxy = ((ProxyNode)lhs).getProxyFor(); if (lhsProxy instanceof Junction && JunctionType.Conj.equals(((Junction)lhsProxy).getJunctionType())) { lResult.addAll( conjunctionToList((Junction)lhsProxy) ); } else { lResult.add(lhs); } } else { lResult.add(lhs); } Node rhs = (Node)gpe.getRhs(); if (rhs instanceof ProxyNode) { GraphPatternElement rhsProxy = ((ProxyNode)rhs).getProxyFor(); if (rhsProxy instanceof Junction && JunctionType.Conj.equals(((Junction)rhsProxy).getJunctionType())) { lResult.addAll( conjunctionToList((Junction)rhsProxy) ); } else { lResult.add(rhs); } } else { lResult.add(rhs); } return lResult; } public static List<Node> disjunctionToList(Junction gpe) { List<Node> lResult = new ArrayList<>(); Node lhs = (Node)gpe.getLhs(); if (lhs instanceof ProxyNode) { GraphPatternElement lhsProxy = ((ProxyNode)lhs).getProxyFor(); if (lhsProxy instanceof Junction && JunctionType.Disj.equals(((Junction)lhsProxy).getJunctionType())) { lResult.addAll( disjunctionToList((Junction)lhsProxy) ); } else { lResult.add(lhs); } } else { lResult.add(lhs); } Node rhs = (Node)gpe.getRhs(); if (rhs instanceof ProxyNode) { GraphPatternElement rhsProxy = ((ProxyNode)rhs).getProxyFor(); if (rhsProxy instanceof Junction && JunctionType.Disj.equals(((Junction)rhsProxy).getJunctionType())) { lResult.addAll( disjunctionToList((Junction)rhsProxy) ); } else { lResult.add(rhs); } } else { lResult.add(rhs); } return lResult; } /** * This method returns true only if all variables in the element are bound in other rule elements * * @param rule * @param gpe * @return */ private boolean allElementVariablesBound(Rule rule, GraphPatternElement gpe) { if (gpe instanceof TripleElement) { Node subject = ((TripleElement)gpe).getSubject(); if ((subject instanceof VariableNode || subject instanceof NamedNode) && !variableIsBound(rule, gpe, subject)) { return false; } Node object = ((TripleElement)gpe).getObject(); if ((object instanceof VariableNode || object instanceof NamedNode) && !variableIsBound(rule, gpe, object)) { return false; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int i = 0; args != null && i < args.size(); i++) { Node arg = args.get(i); if ((arg instanceof VariableNode || arg instanceof NamedNode) && !variableIsBound(rule, gpe, arg)) { return false; } } } return true; } /** * This method returns true if the argument node is bound in some other element of the rule * * @param rule * @param gpe * @param v * @return */ public static boolean variableIsBound(Rule rule, GraphPatternElement gpe, Node v) { if (v instanceof NamedNode) { if (((NamedNode)v).getNodeType() != null && !(((NamedNode)v).getNodeType().equals(NodeType.VariableNode))) { return true; } } // Variable is bound if it appears in a triple or as the return argument of a built-in List<GraphPatternElement> givens = rule.getGivens(); if (variableIsBoundInOtherElement(givens, 0, gpe, true, false, v)) { return true; } List<GraphPatternElement> ifs = rule.getIfs(); if (variableIsBoundInOtherElement(ifs, 0, gpe, true, false, v)) { return true; } List<GraphPatternElement> thens = rule.getThens(); if (variableIsBoundInOtherElement(thens, 0, gpe, false, true, v)) { return true; } return false; } /** * This method checks the list of GraphPatternElements to see if the specified variable is bound in these elements * * @param gpes - list of GraphPatternElements to check * @param startingIndex - where to start in the list * @param gp - the element in which this variable appears * @param boundIfEqual - use the current element for test? * @param matchMustBeAfter - must the binding be after the current element * @param v - the variable Node being checked * @return - true if the variable is bound else false */ public static boolean variableIsBoundInOtherElement(List<GraphPatternElement> gpes, int startingIndex, GraphPatternElement gp, boolean boundIfEqual, boolean matchMustBeAfter, Node v) { boolean reachedSame = false; for (int i = startingIndex; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); while (gpe != null) { boolean same = gp == null ? false : gp.equals(gpe); if (same) { reachedSame = true; } boolean okToTest = false; if (matchMustBeAfter && reachedSame && !same) { okToTest = true; } if (!matchMustBeAfter && (!same || (same && boundIfEqual))) { okToTest = true; } if (okToTest && variableIsBound(gpe, v)) { return true; } gpe = gpe.getNext(); } } return false; } private static boolean variableIsBound(GraphPatternElement gpe, Node v) { if (gpe instanceof TripleElement) { if ((((TripleElement)gpe).getSubject() != null &&((TripleElement)gpe).getSubject().equals(v)) || (((TripleElement)gpe).getObject() != null && ((TripleElement)gpe).getObject().equals(v))) { return true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); // TODO built-ins can actually have more than the last argument as output, but we can only tell this // if we have special knowledge of the builtin. Current SADL grammar doesn't allow this to occur. if (args != null && args.get(args.size() - 1) != null && args.get(args.size() - 1).equals(v)) { return true; } } else if (gpe instanceof Junction) { Object lhsobj = ((Junction)gpe).getLhs(); if (lhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)lhsobj, v)) { return true; } else if (lhsobj instanceof VariableNode && ((VariableNode)lhsobj).equals(v)) { return true; } Object rhsobj = ((Junction)gpe).getRhs(); if (rhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)rhsobj, v)) { return true; } else if (rhsobj instanceof VariableNode && ((VariableNode)rhsobj).equals(v)) { return true; } } return false; } private boolean doVariableSubstitution(List<GraphPatternElement> gpes, VariableNode v1, VariableNode v2) { boolean retval = false; for (int i = 0; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); if (gpe instanceof TripleElement) { if (((TripleElement)gpe).getSubject().equals(v1)) { ((TripleElement)gpe).setSubject(v2); retval = true; } else if (((TripleElement)gpe).getObject().equals(v1)) { ((TripleElement)gpe).setObject(v2); retval = true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int j = 0; j < args.size(); j++) { if (args.get(j).equals(v1)) { args.set(j, v2); retval = true; } } } else if (gpe instanceof Junction) { logger.error("Not yet handled"); } } return retval; } private boolean doVariableSubstitution(GraphPatternElement gpe, VariableNode v1, VariableNode v2) { boolean retval = false; do { if (gpe instanceof TripleElement) { if (((TripleElement)gpe).getSubject().equals(v1)) { ((TripleElement)gpe).setSubject(v2); retval = true; } else if (((TripleElement)gpe).getObject().equals(v1)) { ((TripleElement)gpe).setObject(v2); retval = true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); for (int j = 0; j < args.size(); j++) { if (args.get(j).equals(v1)) { args.set(j, v2); retval = true; } } } else if (gpe instanceof Junction) { logger.error("Not yet handled"); } gpe = gpe.getNext(); } while (gpe != null); return retval; } private void setFirstOfPhrase(GraphPatternElement firstOfPhrase) { this.firstOfPhrase = firstOfPhrase; } protected GraphPatternElement getFirstOfPhrase() { return firstOfPhrase; } /* (non-Javadoc) * @see com.ge.research.sadl.jena.I_IntermediateFormTranslator#setEncapsulatingTarget(java.lang.Object) */ @Override public void setEncapsulatingTarget(Object _encapsulatingTarget) { encapsulatingTarget = _encapsulatingTarget; } public boolean isCollectNamedNodes() { return collectNamedNodes; } public void setCollectNamedNodes(boolean collectNamedNodes) { this.collectNamedNodes = collectNamedNodes; } /** * This method can be called only once for a given set of translations; calling it clears the list of ConceptNames * @return */ public List<ConceptName> getNamedNodes() { if (namedNodes != null) { List<ConceptName> x = new ArrayList<ConceptName>(namedNodes); namedNodes.clear(); return x; } return null; } private void setNamedNodes(List<ConceptName> namedNodes) { this.namedNodes = namedNodes; } private boolean isCruleVariableInTypeOutput(VariableNode cruleVariable) { if (cruleVariablesTypeOutput == null) return false; return cruleVariablesTypeOutput.contains(cruleVariable); } private void addCruleVariableToTypeOutput(VariableNode cruleVariable) { if (cruleVariablesTypeOutput == null) { cruleVariablesTypeOutput = new ArrayList<VariableNode>(); } cruleVariablesTypeOutput.add(cruleVariable); } private void clearCruleVariableTypedOutput() { if (cruleVariablesTypeOutput != null) { cruleVariablesTypeOutput.clear(); } } private int addNotEqualsBuiltinsForNewCruleVariable(List<GraphPatternElement> gpes, int currentIdx, VariableNode node) throws TranslationException { if (cruleVariablesTypeOutput == null) { throw new TranslationException("This should never happen! Please report."); } int crvSize = cruleVariablesTypeOutput.size(); if (!cruleVariablesTypeOutput.get(crvSize - 1).equals(node)) { throw new TranslationException("This method should always be called immediately after creating a Crules variable."); } if (crvSize == 1) { return currentIdx; } for (int i = crvSize - 2; i >= 0; i--) { VariableNode otherVar = cruleVariablesTypeOutput.get(i); if (otherVar.getType().equals(node.getType())) { if (!notEqualAlreadyPresent(gpes, otherVar, node)) { BuiltinElement newBi = new BuiltinElement(); newBi.setFuncName("!="); newBi.setFuncType(BuiltinType.NotEqual); newBi.addArgument(otherVar); newBi.addArgument(node); gpes.add(++currentIdx, newBi); } } } return currentIdx; } private boolean notEqualAlreadyPresent(List<GraphPatternElement> gpes, VariableNode var1, VariableNode var2) { for (int i = 0; i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); if (gpe instanceof BuiltinElement && ((BuiltinElement)gpe).getFuncType().equals(BuiltinType.NotEqual)) { List<Node> args = ((BuiltinElement)gpe).getArguments(); int found = 0; for (int j =0; args != null && j < args.size(); j++) { if (args.get(j).equals(var1)) { found++; } if (args.get(j).equals(var2)) { found++; } } if (found == 2) { return true; } } } return false; } @Override public JenaBasedSadlModelProcessor getModelProcessor() { return modelProcessor; } private void setModelProcessor(JenaBasedSadlModelProcessor modelProcessor) { this.modelProcessor = modelProcessor; } @Override public Object cook(Object obj) throws TranslationException, InvalidNameException, InvalidTypeException { if (obj instanceof Rule) { return cook((Rule)obj); } resetIFTranslator(); setStartingVariableNumber(getVariableNumber() + getModelProcessor().getVariableNumber()); return expandProxyNodes(obj, false, true); } @Override public Object cook(Object obj, boolean treatAsConclusion) throws TranslationException, InvalidNameException, InvalidTypeException { if (obj instanceof Rule) { return cook((Rule)obj); } resetIFTranslator(); setStartingVariableNumber(getVariableNumber() + getModelProcessor().getVariableNumber()); return expandProxyNodes(obj, treatAsConclusion, true); } public Rule cook(Rule rule) { try { rule = addImpliedAndExpandedProperties(rule); // rule = addMissingTriplePatterns(rule); } catch (Exception e) { addError(new IFTranslationError("Translation to Intermediate Form encountered error (" + e.toString() + ")while 'cooking' IntermediateForm.")); e.printStackTrace(); } return rule; } protected OntModel getTheJenaModel() { return theJenaModel; } protected void setTheJenaModel(OntModel theJenaModel) { this.theJenaModel = theJenaModel; } @Override public boolean graphPatternElementMustBeInConclusions(GraphPatternElement gpe) { if (gpe instanceof BuiltinElement && ((BuiltinElement)gpe).getFuncName().equals("assign")) { return true; } return false; } /** * Method to return the type of element returned by a list element extraction built-in * @param bi * @return */ public NamedNode listElementIdentifierListType(BuiltinElement bi) { if (bi.getFuncName().equals("lastElement") || bi.getFuncName().equals("firstElement") || bi.getFuncName().equals("elementBefore") || bi.getFuncName().equals("elementAfter") || bi.getFuncName().equals("elementInList") || bi.getFuncName().equals("sublist")) { Node listArg = bi.getArguments().get(0); if (listArg instanceof NamedNode) { return (NamedNode) listArg; } else if (listArg instanceof ProxyNode) { Object pf = ((ProxyNode)listArg).getProxyFor(); if (pf instanceof TripleElement) { Node pred = ((TripleElement) pf).getPredicate(); if (pred instanceof NamedNode) { Property p = theJenaModel.getProperty(((NamedNode)pred).toFullyQualifiedString()); try { ConceptName pcn = getModelProcessor().namedNodeToConceptName((NamedNode)pred); TypeCheckInfo tci = getModelValidator().getTypeInfoFromRange(pcn, p, null); Node lsttype = tci.getTypeCheckType(); if (lsttype instanceof NamedNode) { return (NamedNode) lsttype; } } catch (DontTypeCheckException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } return null; } return null; } @Override public void reset() { // nothing needed in this class } }
looking at fixing test failure in "is not" constructs
sadl3/com.ge.research.sadl.parent/com.ge.research.sadl.jena/src/com/ge/research/sadl/jena/IntermediateFormTranslator.java
looking at fixing test failure in "is not" constructs
<ide><path>adl3/com.ge.research.sadl.parent/com.ge.research.sadl.jena/src/com/ge/research/sadl/jena/IntermediateFormTranslator.java <ide> } <ide> } <ide> } <del> else if (obj == null) { <add> else if (obj == null && returnNode == null) { <add> // if the subject was null, so returnNode is not null, don't create a variable for object and return that as <add> // it will mess up what's up the stack <ide> returnNode = retiredNode != null ? retiredNode : getVariableNode(subj, te.getPredicate(), obj, false); <ide> te.setObject(returnNode); <ide> if (!patterns.contains(te)) {
Java
lgpl-2.1
73fcf6c13230a10194542b7866b6ab4a5b58ea6f
0
quarnster/silence
/* BassTest.java - An example player for the Bass device * Copyright (C) 2000 Fredrik Ehnbom * * 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import silence.*; import silence.devices.*; import silence.devices.bass.*; import java.awt.*; import java.awt.event.*; /** * An example player for the Bass device * @author Fredrik Ehnbom * @version $Id: BassTest.java,v 1.2 2000/06/11 20:44:40 quarn Exp $ */ public class BassTest extends Frame { static { // load the library for bass System.loadLibrary("bassglue"); } /** * The AudioDevice to use for playing the AudioFormat */ private AudioDevice audioDevice = new BassDevice() { // This is how you redefine the sync method. public void sync(int eff) { System.out.println("Bass wants to sync... (effect num: " + eff + ")"); } }; private Scrollbar vol = new Scrollbar(Scrollbar.HORIZONTAL, 128, 4, 0, 100); private String file = null; /** * Creates a new Silence player. * @param file The file to play */ public BassTest(String file) { super("BASS test: " + file); this.file = file; setLayout(new BorderLayout()); vol.addAdjustmentListener(volListener); add("North", vol); try { audioDevice.init(true); } catch (AudioException me) { me.printStackTrace(); audioDevice.close(); System.exit(1); } Button b = new Button("Play"); b.addActionListener(listener); add("West", b); b = new Button("Stop"); b.addActionListener(listener); add("East", b); b = new Button("Pause"); b.addActionListener(listener); add("South", b); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { audioDevice.stop(); audioDevice.close(); dispose(); System.exit(0); } }); setSize(320, 240); show(); } AdjustmentListener volListener = new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { audioDevice.setVolume(vol.getValue()); } }; ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String event = ((Button) e.getSource()).getLabel(); if (event.equals("Play")) { try { audioDevice.play(file, false); audioDevice.setVolume(vol.getValue()); } catch (AudioException ae) { ae.printStackTrace(); } } else if (event.equals("Stop")) { audioDevice.stop(); } else if (event.equals("Pause")) { try { audioDevice.pause(); } catch (AudioException fe) { fe.printStackTrace(); } } } }; public static void main(String args[]) { if (args.length != 1) { System.out.println("Usage: java BassTest <song>"); } else { new BassTest(args[0]); } } } /* * ChangeLog: * $Log: BassTest.java,v $ * Revision 1.2 2000/06/11 20:44:40 quarn * fixed main which started the FmodTest... * * Revision 1.1 2000/06/10 18:04:39 quarn * A test for Bass * */
tests/BassTest.java
/* BassTest.java - An example player for the Bass device * Copyright (C) 2000 Fredrik Ehnbom * * 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import silence.*; import silence.devices.*; import silence.devices.bass.*; import java.awt.*; import java.awt.event.*; /** * An example player for the Bass device * @author Fredrik Ehnbom * @version $Id: BassTest.java,v 1.1 2000/06/10 18:04:39 quarn Exp $ */ public class BassTest extends Frame { static { // load the library for bass System.loadLibrary("bassglue"); } /** * The AudioDevice to use for playing the AudioFormat */ private AudioDevice audioDevice = new BassDevice() { // This is how you redefine the sync method. public void sync(int eff) { System.out.println("Bass wants to sync... (effect num: " + eff + ")"); } }; private Scrollbar vol = new Scrollbar(Scrollbar.HORIZONTAL, 128, 4, 0, 100); private String file = null; /** * Creates a new Silence player. * @param file The file to play */ public BassTest(String file) { super("BASS test: " + file); this.file = file; setLayout(new BorderLayout()); vol.addAdjustmentListener(volListener); add("North", vol); try { audioDevice.init(true); } catch (AudioException me) { me.printStackTrace(); audioDevice.close(); System.exit(1); } Button b = new Button("Play"); b.addActionListener(listener); add("West", b); b = new Button("Stop"); b.addActionListener(listener); add("East", b); b = new Button("Pause"); b.addActionListener(listener); add("South", b); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { audioDevice.stop(); audioDevice.close(); dispose(); System.exit(0); } }); setSize(320, 240); show(); } AdjustmentListener volListener = new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { audioDevice.setVolume(vol.getValue()); } }; ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String event = ((Button) e.getSource()).getLabel(); if (event.equals("Play")) { try { audioDevice.play(file, false); audioDevice.setVolume(vol.getValue()); } catch (AudioException ae) { ae.printStackTrace(); } } else if (event.equals("Stop")) { audioDevice.stop(); } else if (event.equals("Pause")) { try { audioDevice.pause(); } catch (AudioException fe) { fe.printStackTrace(); } } } }; public static void main(String args[]) { if (args.length != 1) { System.out.println("Usage: java BassTest <song>"); } else { new FmodTest(args[0]); } } } /* * ChangeLog: * $Log: BassTest.java,v $ * Revision 1.1 2000/06/10 18:04:39 quarn * A test for Bass * */
fixed main which started the FmodTest...
tests/BassTest.java
fixed main which started the FmodTest...
<ide><path>ests/BassTest.java <ide> /** <ide> * An example player for the Bass device <ide> * @author Fredrik Ehnbom <del> * @version $Id: BassTest.java,v 1.1 2000/06/10 18:04:39 quarn Exp $ <add> * @version $Id: BassTest.java,v 1.2 2000/06/11 20:44:40 quarn Exp $ <ide> */ <ide> public class BassTest extends Frame { <ide> <ide> if (args.length != 1) { <ide> System.out.println("Usage: java BassTest <song>"); <ide> } else { <del> new FmodTest(args[0]); <add> new BassTest(args[0]); <ide> } <ide> } <ide> } <ide> /* <ide> * ChangeLog: <ide> * $Log: BassTest.java,v $ <add> * Revision 1.2 2000/06/11 20:44:40 quarn <add> * fixed main which started the FmodTest... <add> * <ide> * Revision 1.1 2000/06/10 18:04:39 quarn <ide> * A test for Bass <ide> *
JavaScript
mit
6802851fea70c499ee3504bbd0b66771d0682969
0
telyn/ebnf-lint
var util = require('util'); var SanityChecker = function(ast) { var areSequencesEqual = function(a, b) { a.list.reduce(function(equal, item, index) { return areProductionsEqual(item, b.list[index]); }); } //TODO placeholder (requires both sets of options to be in same order.) var areChoicesEqual = function(a, b) { a.options.reduce(function(equal, item, index) { return areProductionsEqual(item, b.options[index]); }); } var areProductionsEqual = function(a, b) { console.error("\t"+a.type + " == "+b.type+"?"); if(a.type != b.type) { return false; } switch(a.type) { case "terminal": case "special": return a.value == b.value; case "identifier": return a.name == b.name; case "exception": return areProductionsEqual(a.from, b.from) && areProductionsEqual(a.exception, b.exception); case "optional": case "many": case "group": return areProductionsEqual(a.value, b.value); case "choice": return areChoicesEqual(a,b); case "sequence": return areSequencesEqual(a,b); default: throw new Error("Unexpected type "+a.type); } } var traverseAllNodes = function(root, callback) { //root can be anything from the AST, but NOT an array callback(root); var traverse = function(node) { return traverseAllNodes(node,callback); }; switch(root.type) { case "terminal": break; case "identifier": break; case "special": break; case "optional": case "many": case "group": traverse(root.value); break; case "repetition": throw new Error("Repetition isn't finished yet."); case "exception": traverse(root.from); traverse(root.exception); break; case "choice": root.options.forEach(traverse); break; case "sequence": root.list.forEach(traverse); break; case "rule": traverse(root.production); break; case "grammar": root.rules.forEach(traverse); break; default: throw new Error("Unexpected type "+root.type); } } var findDuplicateProductions = function(rule) { } var findDuplicateIdentifiers = function() { var dupes = []; ast.forEach(function(a, aindex) { ast.forEach(function(b, bindex) { if (aindex < bindex && a.identifier.name == b.identifier.name) { b.original = a; dupes.push(b); } }); }); return dupes.map(function(dupe) { return makeProblem("duplicate rule identifier", {duplicate: dupe, original: dupe.original}); }); } var findUnusedAndUndeclaredIdentifiers = function() { var used = []; var declared = []; traverseAllNodes(ast, function(node) { if(node.type == "rule") { declared.push(node); } else if(node.type == "identifier") { used.push(node); } }); var undeclared = used.filter(function(usedid) { return !declared.some(function(declaredrule) { return usedid.name == declaredrule.identifier.name; }); }); var unused = declared.filter(function(declaredrule) { return !used.some(function(usedid) { return usedid.name == declaredrule.identifier.name; }); }); var problems = undeclared.map(function(id) { return makeProblem("undeclared identifier", {identifier:id}); }); problems = problems.concat(unused.map(function(rule) { return makeProblem("unused identifier", {rule: rule}); })); return problems; } var findEquivalentRules = function() { var equivalentRuleSets = []; var worthComparingTo = ast; while(worthComparingTo.length > 0) { var a = worthComparingTo.shift(); var setindex = -1; var stillWorthComparingTo = []; while(worthComparingTo.length > 0) { var b = worthComparingTo.shift(); console.log(a.identifier.name + " == " + b.identifier.name + "?"); if(areProductionsEqual(a.production, b.production)) { if(setindex == -1) { setindex = equivalentRuleSets.length; equivalentRuleSets[setindex] = [a]; } equivalentRuleSets[setindex].push(b); } else { stillWorthComparingTo.push(b); } } worthComparingTo = stillWorthComparingTo; } return equivalentRuleSets.map(function(ruleset) { return makeProblem('equivalent rules', { rules: ruleset }); }); } var makeProblem = function(type, extra) { var getLine = function(obj) { return obj.line; }; var getColumn = function(obj) { return obj.column; }; var getRuleIdentifier = function(rule) { return rule.identifier; }; var makeRuleReference = function(rule) { return util.format("%s (%d:%d)", rule.identifier.name, rule.line, rule.column); }; var assembleProblemObject = function(type, level, line, column, message, extra) { var problem = { type: type, level: level, line: line, column: column, rawmessage: message, data: extra }; return problem; } var problem = {}; switch(type) { case 'equivalent rules': var original = extra.rules.shift(); var message = util.format("%d equivalents of this rule were found: %s.", error.rules.length, extra.rules.map(makeRuleReference).join(', ')); problem = assembleProblemObject(type, "warning", original.line, original.column, message, extra); break; case 'undeclared identifier': var message = util.format("Identifier '%s' is not defined.", extra.identifier.name); problem = assembleProblemObject(type, "error", extra.identifier.line, extra.identifier.column, message, extra); break; case 'unused identifier': var message = util.format("Rule '%s' is never used.", extra.rule.identifier.name); problem = assembleProblemObject(type, "warning", extra.rule.line, extra.rule.column, message, extra); break; case 'duplicate rule identifier': var message = util.format("A rule with the name '%s' is already defined on line %d.", extra.duplicate.identifier.name, extra.original.identifier.line); problem = assembleProblemObject(type, "error", extra.duplicate.line, extra.duplicate.column, message, extra); break; default: throw new Error("Unknown error type '"+error.type+"'"); } problem.message = util.format("%d:%d: %s: %s", problem.line, problem.column, problem.level, problem.rawmessage); return problem; } var sortProblems = function(problems) { var compareLevels = function(a, b) { switch(a) { case "error": switch(b) { case "error": return 0; case "warning": return 1; } case "warning": switch(b) { case "error": return -1; case "warning": return 0; } } } var compareProblems = function(a, b) { if(a.line == b.line) { if(a.column == b.column) { return compareLevels(a.level, b.level); } return a.column - b.column; } return a.line - b.line; } return problems.sort(compareProblems); } this.check = function() { var problems = []; problems = problems.concat(findEquivalentRules()); problems = problems.concat(findUnusedAndUndeclaredIdentifiers()); return sortProblems(problems); } }; module.exports = SanityChecker;
lib/sanitychecker.js
var util = require('util'); var SanityChecker = function(ast) { var areSequencesEqual = function(a, b) { a.list.reduce(function(equal, item, index) { return areProductionsEqual(item, b.list[index]); }); } //TODO placeholder (requires both sets of options to be in same order.) var areChoicesEqual = function(a, b) { a.options.reduce(function(equal, item, index) { return areProductionsEqual(item, b.options[index]); }); } var areProductionsEqual = function(a, b) { console.error("\t"+a.type + " == "+b.type+"?"); if(a.type != b.type) { return false; } switch(a.type) { case "terminal": case "special": return a.value == b.value; case "identifier": return a.name == b.name; case "exception": return areProductionsEqual(a.from, b.from) && areProductionsEqual(a.exception, b.exception); case "optional": case "many": case "group": return areProductionsEqual(a.value, b.value); case "choice": return areChoicesEqual(a,b); case "sequence": return areSequencesEqual(a,b); default: throw new Error("Unexpected type "+a.type); } } var traverseAllNodes = function(root, callback) { //root can be anything from the AST, but NOT an array callback(root); var traverse = function(node) { return traverseAllNodes(node,callback); }; switch(root.type) { case "terminal": break; case "identifier": break; case "special": break; case "optional": case "many": case "group": traverse(root.value); break; case "repetition": throw new Error("Repetition isn't finished yet."); case "exception": traverse(root.from); traverse(root.exception); case "choice": root.options.forEach(traverse); break; case "sequence": root.list.forEach(traverse); break; case "rule": traverse(root.production); break; case "grammar": root.rules.forEach(traverse); break; default: throw new Error("Unexpected type "+root.type); } } var findDuplicateProductions = function(rule) { } var findDuplicateIdentifiers = function() { var dupes = []; ast.forEach(function(a, aindex) { ast.forEach(function(b, bindex) { if (aindex < bindex && a.identifier.name == b.identifier.name) { b.original = a; dupes.push(b); } }); }); return dupes.map(function(dupe) { return makeProblem("duplicate rule identifier", {duplicate: dupe, original: dupe.original}); }); } var findUnusedAndUndeclaredIdentifiers = function() { var used = []; var declared = []; traverseAllNodes(ast, function(node) { if(node.type == "rule") { declared.push(node); } else if(node.type == "identifier") { used.push(node); } }); var undeclared = used.filter(function(usedid) { return !declared.some(function(declaredrule) { return usedid.name == declaredrule.identifier.name; }); }); var unused = declared.filter(function(declaredrule) { return !used.some(function(usedid) { return usedid.name == declaredrule.identifier.name; }); }); var problems = undeclared.map(function(id) { return makeProblem("undeclared identifier", {identifier:id}); }); problems = problems.concat(unused.map(function(rule) { return makeProblem("unused identifier", {rule: rule}); })); return problems; } var findEquivalentRules = function() { var equivalentRuleSets = []; var worthComparingTo = ast; while(worthComparingTo.length > 0) { var a = worthComparingTo.shift(); var setindex = -1; var stillWorthComparingTo = []; while(worthComparingTo.length > 0) { var b = worthComparingTo.shift(); console.log(a.identifier.name + " == " + b.identifier.name + "?"); if(areProductionsEqual(a.production, b.production)) { if(setindex == -1) { setindex = equivalentRuleSets.length; equivalentRuleSets[setindex] = [a]; } equivalentRuleSets[setindex].push(b); } else { stillWorthComparingTo.push(b); } } worthComparingTo = stillWorthComparingTo; } return equivalentRuleSets.map(function(ruleset) { return makeProblem('equivalent rules', { rules: ruleset }); }); } var makeProblem = function(type, extra) { var getLine = function(obj) { return obj.line; }; var getColumn = function(obj) { return obj.column; }; var getRuleIdentifier = function(rule) { return rule.identifier; }; var makeRuleReference = function(rule) { return util.format("%s (%d:%d)", rule.identifier.name, rule.line, rule.column); }; var assembleProblemObject = function(type, level, line, column, message, extra) { var problem = { type: type, level: level, line: line, column: column, rawmessage: message, data: extra }; return problem; } var problem = {}; switch(type) { case 'equivalent rules': var original = extra.rules.shift(); var message = util.format("%d equivalents of this rule were found: %s.", error.rules.length, extra.rules.map(makeRuleReference).join(', ')); problem = assembleProblemObject(type, "warning", original.line, original.column, message, extra); break; case 'undeclared identifier': var message = util.format("Identifier '%s' is not defined.", extra.identifier.name); problem = assembleProblemObject(type, "error", extra.identifier.line, extra.identifier.column, message, extra); break; case 'unused identifier': var message = util.format("Rule '%s' is never used.", extra.rule.identifier.name); problem = assembleProblemObject(type, "warning", extra.rule.line, extra.rule.column, message, extra); break; case 'duplicate rule identifier': var message = util.format("A rule with the name '%s' is already defined on line %d.", extra.duplicate.identifier.name, extra.original.identifier.line); problem = assembleProblemObject(type, "error", extra.duplicate.line, extra.duplicate.column, message, extra); break; default: throw new Error("Unknown error type '"+error.type+"'"); } problem.message = util.format("%d:%d: %s: %s", problem.line, problem.column, problem.level, problem.rawmessage); return problem; } var sortProblems = function(problems) { var compareLevels = function(a, b) { switch(a) { case "error": switch(b) { case "error": return 0; case "warning": return 1; } case "warning": switch(b) { case "error": return -1; case "warning": return 0; } } } var compareProblems = function(a, b) { if(a.line == b.line) { if(a.column == b.column) { return compareLevels(a.level, b.level); } return a.column - b.column; } return a.line - b.line; } return problems.sort(compareProblems); } this.check = function() { var problems = []; problems = problems.concat(findEquivalentRules()); problems = problems.concat(findUnusedAndUndeclaredIdentifiers()); return sortProblems(problems); } }; module.exports = SanityChecker;
Fixed sanitychecker. Was missing a break in a switch.
lib/sanitychecker.js
Fixed sanitychecker.
<ide><path>ib/sanitychecker.js <ide> case "exception": <ide> traverse(root.from); <ide> traverse(root.exception); <add> break; <ide> case "choice": <ide> root.options.forEach(traverse); <ide> break;
Java
apache-2.0
a27ffd2caac9d870fe249797cc07878f65832277
0
albertotn/VividSwingAnimations
package de.anormalmedia.vividswinganimations.panels; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import javax.swing.JPanel; public class SlidePanel extends JPanel { public enum DIRECTION { fromLeft, fromRight, fromBottom, fromTop; } private float slideValue = 0f; private DIRECTION direction = DIRECTION.fromLeft; public SlidePanel( DIRECTION direction ) { super(); setOpaque( false ); this.direction = direction; } public void setDirection( DIRECTION direction ) { this.direction = direction; } public void setSlideValue( float slideValue ) { this.slideValue = slideValue; this.repaint(); } public float getSlideValue() { return slideValue; } @Override public void setBounds( int x, int y, int width, int height ) { synchronized( getTreeLock() ) { super.setBounds( x, y, width, height ); } invalidate(); validateTree(); } @Override public void paint( Graphics g ) { Graphics2D g2d = (Graphics2D)g.create(); g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR ); g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY ); g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); int w = getWidth(); int h = getHeight(); int delta = 0; Rectangle clip = g2d.getClipBounds(); int transX = 0; int transY = 0; switch( direction ) { case fromLeft: delta = (int)Math.floor( w * slideValue ); clip = new Rectangle( 0, 0, delta, h ); transX = -(w - delta); break; case fromRight: delta = (int)Math.floor( w * slideValue ); clip = new Rectangle( w - delta, 0, delta, h ); transX = (w - delta); break; case fromTop: delta = (int)Math.floor( h * slideValue ); clip = new Rectangle( 0, 0, w, delta ); transY = -(h - delta); break; case fromBottom: delta = (int)Math.floor( h * slideValue ); clip = new Rectangle( 0, h - delta, w, delta ); transY = (h - delta); break; } g2d.setClip( clip.intersection( g2d.getClipBounds() ) ); g2d.translate( transX, transY ); super.paint( g2d ); g2d.dispose(); } }
src/de/anormalmedia/vividswinganimations/panels/SlidePanel.java
package de.anormalmedia.vividswinganimations.panels; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import javax.swing.JPanel; public class SlidePanel extends JPanel { public enum DIRECTION { fromLeft, fromRight, fromBottom, fromTop; } private float slideValue = 0f; private DIRECTION direction = DIRECTION.fromLeft; public SlidePanel( DIRECTION direction ) { super(); setOpaque( false ); this.direction = direction; } public void setDirection( DIRECTION direction ) { this.direction = direction; } public void setSlideValue( float slideValue ) { this.slideValue = slideValue; this.repaint(); } public float getSlideValue() { return slideValue; } @Override public void setBounds( int x, int y, int width, int height ) { synchronized( getTreeLock() ) { super.setBounds( x, y, width, height ); } invalidate(); validateTree(); } @Override public void paint( Graphics g ) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR ); g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY ); g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); int w = getWidth(); int h = getHeight(); int delta = 0; Shape oldClip = g2d.getClip(); switch( direction ) { case fromLeft: delta = (int)Math.floor( w * slideValue ); g2d.setClip( 0, 0, delta, h ); g2d.translate( -(w - delta), 0 ); break; case fromRight: delta = (int)Math.floor( w * slideValue ); g2d.setClip( w - delta, 0, delta, h ); g2d.translate( (w - delta), 0 ); break; case fromTop: delta = (int)Math.floor( h * slideValue ); g2d.setClip( 0, 0, w, delta ); g2d.translate( 0, -(h - delta) ); break; case fromBottom: delta = (int)Math.floor( h * slideValue ); g2d.setClip( 0, h - delta, w, delta ); g2d.translate( 0, (h - delta) ); break; } super.paint( g2d ); switch( direction ) { case fromLeft: g2d.translate( (w - delta), 0 ); break; case fromRight: g2d.translate( -(w - delta), 0 ); break; case fromTop: g2d.translate( 0, (h - delta) ); break; case fromBottom: g2d.translate( 0, -(h - delta) ); break; } g2d.setClip( oldClip ); g2d.dispose(); } }
Tweaked SlidePanel: No need to restore clip and translation. Intersect with existing clips.
src/de/anormalmedia/vividswinganimations/panels/SlidePanel.java
Tweaked SlidePanel: No need to restore clip and translation. Intersect with existing clips.
<ide><path>rc/de/anormalmedia/vividswinganimations/panels/SlidePanel.java <ide> <ide> import java.awt.Graphics; <ide> import java.awt.Graphics2D; <add>import java.awt.Rectangle; <ide> import java.awt.RenderingHints; <del>import java.awt.Shape; <ide> <ide> import javax.swing.JPanel; <ide> <ide> <ide> @Override <ide> public void paint( Graphics g ) { <del> Graphics2D g2d = (Graphics2D)g; <add> Graphics2D g2d = (Graphics2D)g.create(); <ide> g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR ); <ide> g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY ); <ide> g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); <ide> int h = getHeight(); <ide> int delta = 0; <ide> <del> Shape oldClip = g2d.getClip(); <add> Rectangle clip = g2d.getClipBounds(); <add> int transX = 0; <add> int transY = 0; <ide> switch( direction ) { <ide> case fromLeft: <ide> delta = (int)Math.floor( w * slideValue ); <del> g2d.setClip( 0, 0, delta, h ); <del> g2d.translate( -(w - delta), 0 ); <add> clip = new Rectangle( 0, 0, delta, h ); <add> transX = -(w - delta); <ide> break; <ide> case fromRight: <ide> delta = (int)Math.floor( w * slideValue ); <del> g2d.setClip( w - delta, 0, delta, h ); <del> g2d.translate( (w - delta), 0 ); <add> clip = new Rectangle( w - delta, 0, delta, h ); <add> transX = (w - delta); <ide> break; <ide> case fromTop: <ide> delta = (int)Math.floor( h * slideValue ); <del> g2d.setClip( 0, 0, w, delta ); <del> g2d.translate( 0, -(h - delta) ); <add> clip = new Rectangle( 0, 0, w, delta ); <add> transY = -(h - delta); <ide> break; <ide> case fromBottom: <ide> delta = (int)Math.floor( h * slideValue ); <del> g2d.setClip( 0, h - delta, w, delta ); <del> g2d.translate( 0, (h - delta) ); <add> clip = new Rectangle( 0, h - delta, w, delta ); <add> transY = (h - delta); <ide> break; <ide> } <add> g2d.setClip( clip.intersection( g2d.getClipBounds() ) ); <add> g2d.translate( transX, transY ); <ide> super.paint( g2d ); <del> switch( direction ) { <del> case fromLeft: <del> g2d.translate( (w - delta), 0 ); <del> break; <del> case fromRight: <del> g2d.translate( -(w - delta), 0 ); <del> break; <del> case fromTop: <del> g2d.translate( 0, (h - delta) ); <del> break; <del> case fromBottom: <del> g2d.translate( 0, -(h - delta) ); <del> break; <del> } <del> g2d.setClip( oldClip ); <ide> g2d.dispose(); <ide> } <ide> }
Java
mit
96597d04b4b374cff5ef0b602196d65dfb325449
0
tupilabs/tap4j,tupilabs/tap4j
/* * The MIT License * * Copyright (c) 2010 tap4j team (see AUTHORS) * * 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.tap4j.parser; import org.tap4j.model.BailOut; import org.tap4j.model.Comment; import org.tap4j.model.Footer; import org.tap4j.model.Header; import org.tap4j.model.Plan; import org.tap4j.model.TapElement; import org.tap4j.model.TapElementFactory; import org.tap4j.model.TestResult; import org.tap4j.model.TestSet; import org.tap4j.model.Text; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.UnsupportedCharsetException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; /** * TAP 13 parser. * * @since 1.0 */ public class Tap13Parser implements Parser { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Tap13Parser.class .getCanonicalName()); /** * UTF-8 encoding constant. */ private static final String UTF8_ENCODING = "UTF-8"; /** * Stack of stream status information bags. Every bag stores state of the parser * related to certain indentation level. This is to support subtest feature. */ private final Stack<StreamStatus> states = new Stack<>(); /** * The current state. */ private StreamStatus state = null; private int baseIndentation; /** * Decoder used. This is only used when trying to parse something that is * encoded (like a raw file or byte stream) and the encoding isn't otherwise * known. */ private CharsetDecoder decoder; /** * Require a TAP plan. */ private final boolean planRequired; /** * Enable subtests. */ private final boolean enableSubtests; /** * A stack that holds subtests for which we don't know exact parent yet. */ private final Stack<StreamStatus> subStack = new Stack<>(); /** * Remove corrupted YAML. YAML parser error should not cause TAP parser error. * The content that failed to be parsed as YAML will be just removed from the TAP diagnostic data. * Switched off by default. */ private final boolean removeYamlIfCorrupted; /** * Parser Constructor. * * A parser constructed this way will enforce that any input should include * a plan. * * @param encoding Encoding. This will not matter when parsing sources that * are already decoded (e.g. {@link String} or {@link Readable}), but it * will be used in the {@link #parseFile} method (whether or not it is the * right encoding for the File being parsed). * @param enableSubtests Whether subtests are enabled or not */ public Tap13Parser(String encoding, boolean enableSubtests) { this(encoding, enableSubtests, true); } /** * Parser Constructor. * * @param encoding Encoding. This will not matter when parsing sources that * are already decoded (e.g. {@link String} or {@link Readable}), but it * will be used in the {@link #parseFile} method (whether or not it is the * right encoding for the File being parsed). * @param enableSubtests Whether subtests are enabled or not * @param planRequired flag that defines whether a plan is required or not */ public Tap13Parser(String encoding, boolean enableSubtests, boolean planRequired) { this(encoding, enableSubtests, planRequired, false); } /** * Parser Constructor. * * @param encoding Encoding. This will not matter when parsing sources that * are already decoded (e.g. {@link String} or {@link Readable}), but it * will be used in the {@link #parseFile} method (whether or not it is the * right encoding for the File being parsed). * @param enableSubtests Whether subtests are enabled or not * @param planRequired flag that defines whether a plan is required or not * @param removeYamlIfCorrupted flag that defines whether a corrupted YAML content will be removed without causing whole TAP processing failure */ public Tap13Parser(String encoding, boolean enableSubtests, boolean planRequired, boolean removeYamlIfCorrupted) { super(); /* * Resolving the encoding name to a CharsetDecoder here has two * benefits. First, if it isn't known or supported, the caller finds out * as early as possible. Second, a decoder obtained this way will check * the validity of its input and throw exceptions if it doesn't match * the encoding. All the other ways to specify an encoding result in a * default behavior to silently drop or change data ... not great in a * testing tool. */ try { if (null != encoding) { this.decoder = Charset.forName(encoding).newDecoder(); } } catch (UnsupportedCharsetException uce) { throw new ParserException(String.format("Invalid encoding: %s", encoding), uce); } this.enableSubtests = enableSubtests; this.planRequired = planRequired; this.removeYamlIfCorrupted = removeYamlIfCorrupted; } /** * Parser Constructor. * * A parser created with this constructor will assume that any input to the * {@link #parseFile} method is encoded in {@code UTF-8}. * * @param enableSubtests Whether subtests are enabled or not */ public Tap13Parser(boolean enableSubtests) { this(UTF8_ENCODING, enableSubtests); } /** * Parser Constructor. * * A parser created with this constructor will assume that any input to the * {@link #parseFile} method is encoded in {@code UTF-8}, and will not * recognize subtests. */ public Tap13Parser() { this(UTF8_ENCODING, false); } /** * Saves the current state in the stack. * @param indentation state indentation */ private void pushState(int indentation) { states.push(state); state = new StreamStatus(); state.setIndentationLevel(indentation); } /** * {@inheritDoc} */ @Override public TestSet parseTapStream(String tapStream) { return parseTapStream(CharBuffer.wrap(tapStream)); } /** * {@inheritDoc} */ @Override public TestSet parseFile(File tapFile) { if (null == decoder) { throw new ParserException( "Must have encoding specified if using parseFile"); } try ( FileInputStream fis = new FileInputStream(tapFile); InputStreamReader isr = new InputStreamReader(fis, decoder) ) { return parseTapStream(isr); } catch (FileNotFoundException e) { throw new ParserException("TAP file not found: " + tapFile, e); } catch (IOException e) { LOGGER.log(Level.SEVERE, String.format("Failed to close file stream: %s", e.getMessage()), e); throw new ParserException(String.format("Failed to close file stream for file %s: %s: ", tapFile, e.getMessage()), e); } } /** * {@inheritDoc} */ @Override public TestSet parseTapStream(Readable tapStream) { state = new StreamStatus(); baseIndentation = Integer.MAX_VALUE; try (Scanner scanner = new Scanner(tapStream)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line != null && line.length() > 0) { parseLine(line); } } onFinish(); } catch (Exception e) { throw new ParserException(String.format("Error parsing TAP Stream: %s", e.getMessage()), e); } return state.getTestSet(); } /** * Parse a TAP line. * * @param tapLineOrig TAP line */ public void parseLine(String tapLineOrig) { // filter out cursor related control sequences ESC[25?l and ESC[25?h String tapLine = tapLineOrig.replaceAll("\u001B\\[\\?25[lh]", ""); final TapElement tapElement = TapElementFactory.createTapElement(tapLine); final boolean invalidTapElement = tapElement == null; final Text text = TapElementFactory.createTextElement(tapLine); if (text != null && (invalidTapElement || state.isInYaml())) { String trimmedLine = tapLine.trim(); if (state.isInYaml()) { boolean yamlEndMarkReached = trimmedLine.equals("...") && ( tapLine.equals(state.getYamlIndentation() + "...") || text.getIndentation() < state.getYamlIndentation().length()); if (yamlEndMarkReached) { state.setInYaml(false); parseDiagnostics(); } else { state.getDiagnosticBuffer().append(tapLine); state.getDiagnosticBuffer().append('\n'); } } else { if (trimmedLine.equals("---") && state.getTestSet().getTestResults().size() > 0) { if (text.getIndentation() < baseIndentation) { throw new ParserException(String.format("Invalid indentation. Check your TAP Stream. Line: %s", tapLine)); } state.setInYaml(true); state.setYamlIndentation(text.getIndentationString()); } else { state.getTestSet().getTapLines().add(text); state.setLastParsedElement(text); } } return; } if (invalidTapElement) { return; } int indentation = tapElement.getIndentation(); if (indentation < baseIndentation) { baseIndentation = indentation; } StreamStatus prevState = null; if (indentation != state.getIndentationLevel() && enableSubtests) { // indentation changed if (indentation > state.getIndentationLevel()) { int prevIndent = state.getIndentationLevel(); pushState(indentation); // make room for children if (indentation - prevIndent > 4) subStack.push(state); } else { // going down if (states.peek().getIndentationLevel() == indentation) { prevState = state; state = states.pop(); } else { state = new StreamStatus(); state.setIndentationLevel(indentation); subStack.push(state); } } } if (tapElement instanceof Header) { if (state.getTestSet().getHeader() != null) { throw new ParserException("Duplicated TAP Header found."); } if (!state.isFirstLine()) { throw new ParserException( "Invalid position of TAP Header. It must be the first " + "element (apart of Comments) in the TAP Stream."); } state.getTestSet().setHeader((Header) tapElement); } else if (tapElement instanceof Plan) { Plan currentPlan = (Plan) tapElement; if (state.getTestSet().getPlan() != null) { if (currentPlan.getInitialTestNumber() != 1 || currentPlan.getLastTestNumber() != 0) { throw new ParserException("Duplicated TAP Plan found."); } } else { state.getTestSet().setPlan(currentPlan); } if (state.getTestSet().getTestResults().size() <= 0 && state.getTestSet().getBailOuts().size() <= 0) { state.setPlanBeforeTestResult(true); } } else if (tapElement instanceof TestResult) { parseDiagnostics(); final TestResult testResult = (TestResult) tapElement; if (testResult.getTestNumber() == 0) { if (state.getTestSet().getPlan() != null && !state.isPlanBeforeTestResult()) { return; // done testing mark } if (state.getTestSet().getPlan() != null && state.getTestSet().getPlan().getLastTestNumber() == state.getTestSet().getTestResults().size()) { return; // done testing mark but plan before test result } testResult.setTestNumber(state.getTestSet().getNextTestNumber()); } state.getTestSet().addTestResult(testResult); if (prevState != null && enableSubtests) { state.getTestSet().getTestResults().get( state.getTestSet().getNumberOfTestResults() - 1) .setSubtest(prevState.getTestSet()); } if (indentation == 0 && enableSubtests) { TestResult currLast = state.getTestSet().getTestResults().get( state.getTestSet().getNumberOfTestResults() - 1); while (!subStack.empty()) { StreamStatus nextLevel = subStack.pop(); currLast.setSubtest(nextLevel.getTestSet()); currLast = nextLevel.getTestSet().getTestResults().get(0); } } } else if (tapElement instanceof Footer) { state.getTestSet().setFooter((Footer) tapElement); } else if (tapElement instanceof BailOut) { state.getTestSet().addBailOut((BailOut) tapElement); } else if (tapElement instanceof Comment) { final Comment comment = (Comment) tapElement; state.getTestSet().addComment(comment); if (state.getLastParsedElement() instanceof TestResult) { ((TestResult) state.getLastParsedElement()).addComment(comment); } } state.setFirstLine(false); if (!(tapElement instanceof Comment)) { state.setLastParsedElement(tapElement); } } /** * Called after the rest of the stream has been processed. */ private void onFinish() { if (planRequired && state.getTestSet().getPlan() == null) { throw new ParserException("Missing TAP Plan."); } parseDiagnostics(); while (!states.isEmpty() && state.getIndentationLevel() > baseIndentation) { state = states.pop(); } } /* -- Utility methods --*/ /** * <p> * Checks if there is any diagnostic information on the diagnostic buffer. * </p> * <p> * If so, tries to parse it using snakeyaml. * </p> */ private void parseDiagnostics() { // If we found any meta, then process it with SnakeYAML if (state.getDiagnosticBuffer().length() > 0) { if (state.getLastParsedElement() == null) { throw new ParserException("Found diagnostic information without a previous TAP element."); } try { @SuppressWarnings("unchecked") Map<String, Object> metaIterable = (Map<String, Object>) new Yaml() .load(state.getDiagnosticBuffer().toString()); state.getLastParsedElement().setDiagnostic(metaIterable); } catch (Exception ex) { if (this.removeYamlIfCorrupted) { Map<String, Object> metaInfo = new HashMap<>(); metaInfo.put("TAP processing error", "could not parse original diagnostic YAML data"); state.getLastParsedElement().setDiagnostic(metaInfo); } else { throw new ParserException("Error parsing YAML [" + state.getDiagnosticBuffer().toString() + "]: " + ex.getMessage(), ex); } } this.state.getDiagnosticBuffer().setLength(0); } } }
src/main/java/org/tap4j/parser/Tap13Parser.java
/* * The MIT License * * Copyright (c) 2010 tap4j team (see AUTHORS) * * 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.tap4j.parser; import org.tap4j.model.BailOut; import org.tap4j.model.Comment; import org.tap4j.model.Footer; import org.tap4j.model.Header; import org.tap4j.model.Plan; import org.tap4j.model.TapElement; import org.tap4j.model.TapElementFactory; import org.tap4j.model.TestResult; import org.tap4j.model.TestSet; import org.tap4j.model.Text; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.UnsupportedCharsetException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; /** * TAP 13 parser. * * @since 1.0 */ public class Tap13Parser implements Parser { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Tap13Parser.class .getCanonicalName()); /** * UTF-8 encoding constant. */ private static final String UTF8_ENCODING = "UTF-8"; /** * Stack of stream status information bags. Every bag stores state of the parser * related to certain indentation level. This is to support subtest feature. */ private final Stack<StreamStatus> states = new Stack<>(); /** * The current state. */ private StreamStatus state = null; private int baseIndentation; /** * Decoder used. This is only used when trying to parse something that is * encoded (like a raw file or byte stream) and the encoding isn't otherwise * known. */ private CharsetDecoder decoder; /** * Require a TAP plan. */ private final boolean planRequired; /** * Enable subtests. */ private final boolean enableSubtests; /** * A stack that holds subtests for which we don't know exact parent yet. */ private final Stack<StreamStatus> subStack = new Stack<>(); /** * Remove corrupted YAML. YAML parser error should not cause TAP parser error. * The content that failed to be parsed as YAML will be just removed from the TAP diagnostic data. * Switched off by default. */ private final boolean removeYamlIfCorrupted; /** * Parser Constructor. * * A parser constructed this way will enforce that any input should include * a plan. * * @param encoding Encoding. This will not matter when parsing sources that * are already decoded (e.g. {@link String} or {@link Readable}), but it * will be used in the {@link #parseFile} method (whether or not it is the * right encoding for the File being parsed). * @param enableSubtests Whether subtests are enabled or not */ public Tap13Parser(String encoding, boolean enableSubtests) { this(encoding, enableSubtests, true); } /** * Parser Constructor. * * @param encoding Encoding. This will not matter when parsing sources that * are already decoded (e.g. {@link String} or {@link Readable}), but it * will be used in the {@link #parseFile} method (whether or not it is the * right encoding for the File being parsed). * @param enableSubtests Whether subtests are enabled or not * @param planRequired flag that defines whether a plan is required or not */ public Tap13Parser(String encoding, boolean enableSubtests, boolean planRequired) { this(encoding, enableSubtests, planRequired, false); } /** * Parser Constructor. * * @param encoding Encoding. This will not matter when parsing sources that * are already decoded (e.g. {@link String} or {@link Readable}), but it * will be used in the {@link #parseFile} method (whether or not it is the * right encoding for the File being parsed). * @param enableSubtests Whether subtests are enabled or not * @param planRequired flag that defines whether a plan is required or not * @param removeYamlIfCorrupted flag that defines whether a corrupted YAML content will be removed without causing whole TAP processing failure */ public Tap13Parser(String encoding, boolean enableSubtests, boolean planRequired, boolean removeYamlIfCorrupted) { super(); /* * Resolving the encoding name to a CharsetDecoder here has two * benefits. First, if it isn't known or supported, the caller finds out * as early as possible. Second, a decoder obtained this way will check * the validity of its input and throw exceptions if it doesn't match * the encoding. All the other ways to specify an encoding result in a * default behavior to silently drop or change data ... not great in a * testing tool. */ try { if (null != encoding) { this.decoder = Charset.forName(encoding).newDecoder(); } } catch (UnsupportedCharsetException uce) { throw new ParserException(String.format("Invalid encoding: %s", encoding), uce); } this.enableSubtests = enableSubtests; this.planRequired = planRequired; this.removeYamlIfCorrupted = removeYamlIfCorrupted; } /** * Parser Constructor. * * A parser created with this constructor will assume that any input to the * {@link #parseFile} method is encoded in {@code UTF-8}. * * @param enableSubtests Whether subtests are enabled or not */ public Tap13Parser(boolean enableSubtests) { this(UTF8_ENCODING, enableSubtests); } /** * Parser Constructor. * * A parser created with this constructor will assume that any input to the * {@link #parseFile} method is encoded in {@code UTF-8}, and will not * recognize subtests. */ public Tap13Parser() { this(UTF8_ENCODING, false); } /** * Saves the current state in the stack. * @param indentation state indentation */ private void pushState(int indentation) { states.push(state); state = new StreamStatus(); state.setIndentationLevel(indentation); } /** * {@inheritDoc} */ @Override public TestSet parseTapStream(String tapStream) { return parseTapStream(CharBuffer.wrap(tapStream)); } /** * {@inheritDoc} */ @Override public TestSet parseFile(File tapFile) { if (null == decoder) { throw new ParserException( "Must have encoding specified if using parseFile"); } try ( FileInputStream fis = new FileInputStream(tapFile); InputStreamReader isr = new InputStreamReader(fis, decoder) ) { return parseTapStream(isr); } catch (FileNotFoundException e) { throw new ParserException("TAP file not found: " + tapFile, e); } catch (IOException e) { LOGGER.log(Level.SEVERE, String.format("Failed to close file stream: %s", e.getMessage()), e); throw new ParserException(String.format("Failed to close file stream for file %s: %s: ", tapFile, e.getMessage()), e); } } /** * {@inheritDoc} */ @Override public TestSet parseTapStream(Readable tapStream) { state = new StreamStatus(); baseIndentation = Integer.MAX_VALUE; try (Scanner scanner = new Scanner(tapStream)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line != null && line.length() > 0) { parseLine(line); } } onFinish(); } catch (Exception e) { throw new ParserException(String.format("Error parsing TAP Stream: %s", e.getMessage()), e); } return state.getTestSet(); } /** * Parse a TAP line. * * @param tapLineOrig TAP line */ public void parseLine(String tapLineOrig) { // filter out cursor related control sequences ESC[25?l and ESC[25?h String tapLine = tapLineOrig.replaceAll("\u001B\\[\\?25[lh]", ""); TapElement tapElement = TapElementFactory.createTapElement(tapLine); if (tapElement == null) { return; } final Text text = TapElementFactory.createTextElement(tapLine); if (text != null && state.isInYaml()) { String trimmedLine = tapLine.trim(); if (state.isInYaml()) { boolean yamlEndMarkReached = trimmedLine.equals("...") && ( tapLine.equals(state.getYamlIndentation() + "...") || text.getIndentation() < state.getYamlIndentation().length()); if (yamlEndMarkReached) { state.setInYaml(false); parseDiagnostics(); } else { state.getDiagnosticBuffer().append(tapLine); state.getDiagnosticBuffer().append('\n'); } } else { if (trimmedLine.equals("---") && state.getTestSet().getTestResults().size() > 0) { if (text.getIndentation() < baseIndentation) { throw new ParserException(String.format("Invalid indentation. Check your TAP Stream. Line: %s", tapLine)); } state.setInYaml(true); state.setYamlIndentation(text.getIndentationString()); } else { state.getTestSet().getTapLines().add(text); state.setLastParsedElement(text); } } return; } int indentation = tapElement.getIndentation(); if (indentation < baseIndentation) { baseIndentation = indentation; } StreamStatus prevState = null; if (indentation != state.getIndentationLevel() && enableSubtests) { // indentation changed if (indentation > state.getIndentationLevel()) { int prevIndent = state.getIndentationLevel(); pushState(indentation); // make room for children if (indentation - prevIndent > 4) subStack.push(state); } else { // going down if (states.peek().getIndentationLevel() == indentation) { prevState = state; state = states.pop(); } else { state = new StreamStatus(); state.setIndentationLevel(indentation); subStack.push(state); } } } if (tapElement instanceof Header) { if (state.getTestSet().getHeader() != null) { throw new ParserException("Duplicated TAP Header found."); } if (!state.isFirstLine()) { throw new ParserException( "Invalid position of TAP Header. It must be the first " + "element (apart of Comments) in the TAP Stream."); } state.getTestSet().setHeader((Header) tapElement); } else if (tapElement instanceof Plan) { Plan currentPlan = (Plan) tapElement; if (state.getTestSet().getPlan() != null) { if (currentPlan.getInitialTestNumber() != 1 || currentPlan.getLastTestNumber() != 0) { throw new ParserException("Duplicated TAP Plan found."); } } else { state.getTestSet().setPlan(currentPlan); } if (state.getTestSet().getTestResults().size() <= 0 && state.getTestSet().getBailOuts().size() <= 0) { state.setPlanBeforeTestResult(true); } } else if (tapElement instanceof TestResult) { parseDiagnostics(); final TestResult testResult = (TestResult) tapElement; if (testResult.getTestNumber() == 0) { if (state.getTestSet().getPlan() != null && !state.isPlanBeforeTestResult()) { return; // done testing mark } if (state.getTestSet().getPlan() != null && state.getTestSet().getPlan().getLastTestNumber() == state.getTestSet().getTestResults().size()) { return; // done testing mark but plan before test result } testResult.setTestNumber(state.getTestSet().getNextTestNumber()); } state.getTestSet().addTestResult(testResult); if (prevState != null && enableSubtests) { state.getTestSet().getTestResults().get( state.getTestSet().getNumberOfTestResults() - 1) .setSubtest(prevState.getTestSet()); } if (indentation == 0 && enableSubtests) { TestResult currLast = state.getTestSet().getTestResults().get( state.getTestSet().getNumberOfTestResults() - 1); while (!subStack.empty()) { StreamStatus nextLevel = subStack.pop(); currLast.setSubtest(nextLevel.getTestSet()); currLast = nextLevel.getTestSet().getTestResults().get(0); } } } else if (tapElement instanceof Footer) { state.getTestSet().setFooter((Footer) tapElement); } else if (tapElement instanceof BailOut) { state.getTestSet().addBailOut((BailOut) tapElement); } else if (tapElement instanceof Comment) { final Comment comment = (Comment) tapElement; state.getTestSet().addComment(comment); if (state.getLastParsedElement() instanceof TestResult) { ((TestResult) state.getLastParsedElement()).addComment(comment); } } state.setFirstLine(false); if (!(tapElement instanceof Comment)) { state.setLastParsedElement(tapElement); } } /** * Called after the rest of the stream has been processed. */ private void onFinish() { if (planRequired && state.getTestSet().getPlan() == null) { throw new ParserException("Missing TAP Plan."); } parseDiagnostics(); while (!states.isEmpty() && state.getIndentationLevel() > baseIndentation) { state = states.pop(); } } /* -- Utility methods --*/ /** * <p> * Checks if there is any diagnostic information on the diagnostic buffer. * </p> * <p> * If so, tries to parse it using snakeyaml. * </p> */ private void parseDiagnostics() { // If we found any meta, then process it with SnakeYAML if (state.getDiagnosticBuffer().length() > 0) { if (state.getLastParsedElement() == null) { throw new ParserException("Found diagnostic information without a previous TAP element."); } try { @SuppressWarnings("unchecked") Map<String, Object> metaIterable = (Map<String, Object>) new Yaml() .load(state.getDiagnosticBuffer().toString()); state.getLastParsedElement().setDiagnostic(metaIterable); } catch (Exception ex) { if (this.removeYamlIfCorrupted) { Map<String, Object> metaInfo = new HashMap<>(); metaInfo.put("TAP processing error", "could not parse original diagnostic YAML data"); state.getLastParsedElement().setDiagnostic(metaInfo); } else { throw new ParserException("Error parsing YAML [" + state.getDiagnosticBuffer().toString() + "]: " + ex.getMessage(), ex); } } this.state.getDiagnosticBuffer().setLength(0); } } }
Fix unit tests and spotbugs
src/main/java/org/tap4j/parser/Tap13Parser.java
Fix unit tests and spotbugs
<ide><path>rc/main/java/org/tap4j/parser/Tap13Parser.java <ide> // filter out cursor related control sequences ESC[25?l and ESC[25?h <ide> String tapLine = tapLineOrig.replaceAll("\u001B\\[\\?25[lh]", ""); <ide> <del> TapElement tapElement = TapElementFactory.createTapElement(tapLine); <del> if (tapElement == null) { <del> return; <del> } <add> final TapElement tapElement = TapElementFactory.createTapElement(tapLine); <add> final boolean invalidTapElement = tapElement == null; <ide> <ide> final Text text = TapElementFactory.createTextElement(tapLine); <ide> <del> if (text != null && state.isInYaml()) { <add> if (text != null && (invalidTapElement || state.isInYaml())) { <ide> <ide> String trimmedLine = tapLine.trim(); <ide> <ide> return; <ide> } <ide> <add> if (invalidTapElement) { <add> return; <add> } <ide> int indentation = tapElement.getIndentation(); <ide> <ide> if (indentation < baseIndentation) {
Java
apache-2.0
92cfc4c1b0565cbb309c53806ed649009237008d
0
rasika90/carbon-uuf,sajithar/carbon-uuf,Shan1024/carbon-uuf,sajithar/carbon-uuf,manuranga/carbon-uuf,wso2/carbon-uuf,manuranga/carbon-uuf,wso2/carbon-uuf,rasika90/carbon-uuf,wso2/carbon-uuf,Shan1024/carbon-uuf,rasika90/carbon-uuf,manuranga/carbon-uuf,manuranga/carbon-uuf,Shan1024/carbon-uuf,wso2/carbon-uuf,this/carbon-uuf,this/carbon-uuf,this/carbon-uuf,this/carbon-uuf,Shan1024/carbon-uuf
package org.wso2.carbon.uuf.core; import org.wso2.carbon.uuf.model.Model; import java.util.Optional; public class Page implements Comparable<Page> { private final UriPatten uriPatten; private final Renderable renderer; private final Optional<Layout> layout; public Page(UriPatten uriPatten, Renderable renderer) { this(uriPatten, renderer, null); } public Page(UriPatten uriPatten, Renderable renderer, Layout layout) { this.uriPatten = uriPatten; this.renderer = renderer; this.layout = Optional.ofNullable(layout); } public UriPatten getUriPatten() { return uriPatten; } public String render(Model model, ComponentLookup componentLookup, RequestLookup requestLookup, API api) { requestLookup.pushToPublicUriStack(requestLookup.getAppContext() + componentLookup.getPublicUriInfix(this)); String output = renderer.render(model, componentLookup, requestLookup, api); requestLookup.popPublicUriStack(); if (layout.isPresent()) { output = layout.get().render(componentLookup, requestLookup); } return output; } @Override public String toString() { return "{\"uriPattern\": " + uriPatten + ", \"renderer\": " + renderer + "}"; } @Override public int compareTo(Page otherPage) { return this.getUriPatten().compareTo(otherPage.getUriPatten()); } }
uuf-core/src/main/java/org/wso2/carbon/uuf/core/Page.java
package org.wso2.carbon.uuf.core; import org.wso2.carbon.uuf.model.Model; import java.util.Optional; public class Page implements Comparable<Page> { private final UriPatten uriPatten; private final Renderable renderer; private final Optional<Layout> layout; public Page(UriPatten uriPatten, Renderable renderer) { this(uriPatten, renderer, null); } public Page(UriPatten uriPatten, Renderable renderer, Layout layout) { this.uriPatten = uriPatten; this.renderer = renderer; this.layout = Optional.ofNullable(layout); } public UriPatten getUriPatten() { return uriPatten; } public String render(Model model, ComponentLookup componentLookup, RequestLookup requestLookup, API api) { requestLookup.pushToPublicUriStack(requestLookup.getAppContext() + componentLookup.getPublicUriInfix(this)); String output = renderer.render(model, componentLookup, requestLookup, api); requestLookup.popPublicUriStack(); if (layout.isPresent()) { output = layout.get().render(componentLookup, requestLookup); } return output; } @Override public String toString() { return "{\"uriPattern\": \"" + uriPatten.toString() + "\", \"renderer\": \"" + renderer + "\"}"; } @Override public int compareTo(Page otherPage) { return this.getUriPatten().compareTo(otherPage.getUriPatten()); } }
corrected 'toString' method of Page class
uuf-core/src/main/java/org/wso2/carbon/uuf/core/Page.java
corrected 'toString' method of Page class
<ide><path>uf-core/src/main/java/org/wso2/carbon/uuf/core/Page.java <ide> <ide> @Override <ide> public String toString() { <del> return "{\"uriPattern\": \"" + uriPatten.toString() + "\", \"renderer\": \"" + renderer + "\"}"; <add> return "{\"uriPattern\": " + uriPatten + ", \"renderer\": " + renderer + "}"; <ide> } <ide> <ide> @Override
Java
epl-1.0
error: pathspec 'src/de/finetech/utils/InfosystemcallResult.java' did not match any file(s) known to git
f08f05896075f6f6d424b2b7e2f24e4289400c25
1
mrothenbuecher/GroovyFO,mkuerbis/GroovyFO
package de.finetech.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.TreeMap; import java.util.Vector; import de.abas.eks.jfop.remote.FO; /** * stellt das ergebnis eines Infosystem aufrufs dar. * * @author MKürbis * */ public class InfosystemcallResult { private TreeMap<String, String> head; private Vector<TreeMap<String, String>> table; private Infosystemcall call; private Vector<String[]> lines; private Vector<String[]> getLinesOfFile(String file) throws IOException { Vector<String[]> lines = new Vector<String[]>(); if (file != null) { BufferedReader br = new BufferedReader(new FileReader(file)); for (String line; (line = br.readLine()) != null;) { lines.add(line.split(";")); } br.close(); } return lines; } protected InfosystemcallResult(Infosystemcall call) throws IOException { this.call = call; this.head = new TreeMap<String, String>(); this.table = new Vector<TreeMap<String, String>>(); this.lines = this.getLinesOfFile(call.outputFile); boolean headFields = call.showAllHeadFields || call.headOutputFields.size() > 0; if (headFields) { for (int i = 0; i < lines.get(0).length; i++) { String key = lines.get(0)[i]; head.put(key, lines.get(1)[i]); } } if (call.showAllTableFields || call.tableOutputFields.size() > 0) { // index der Variablennamen zeile in der Outputdatei festlegen int row = (headFields) ? 2 : 0; // zeile mit den Variablennamen speichern String[] keys = lines.get(row); // für jede Datenzeile for (int j = row + 1; j < lines.size(); j++) { TreeMap<String, String> foo = new TreeMap<String, String>(); for (int i = 0; i < keys.length; i++) { foo.put(keys[i], lines.get(j)[i]); } table.add(foo); } } } public TreeMap<String, String> getHead() { return this.head; } public Vector<TreeMap<String, String>> getTable() { return this.table; } public String getOutputFile() { return call.outputFile; } public String getInfosystem() { return call.infosystem; } public String getCommando(){ return call.getCommand(); } public void printFile() { for (String[] line : lines) { for (String column : line) { FO.println("-lfsuppress " + column + ";"); } FO.println(""); } } }
src/de/finetech/utils/InfosystemcallResult.java
Create InfosystemcallResult.java
src/de/finetech/utils/InfosystemcallResult.java
Create InfosystemcallResult.java
<ide><path>rc/de/finetech/utils/InfosystemcallResult.java <add>package de.finetech.utils; <add> <add>import java.io.BufferedReader; <add>import java.io.FileReader; <add>import java.io.IOException; <add>import java.util.TreeMap; <add>import java.util.Vector; <add> <add>import de.abas.eks.jfop.remote.FO; <add> <add>/** <add> * stellt das ergebnis eines Infosystem aufrufs dar. <add> * <add> * @author MKürbis <add> * <add> */ <add>public class InfosystemcallResult { <add> <add> private TreeMap<String, String> head; <add> private Vector<TreeMap<String, String>> table; <add> <add> private Infosystemcall call; <add> <add> private Vector<String[]> lines; <add> <add> private Vector<String[]> getLinesOfFile(String file) throws IOException { <add> Vector<String[]> lines = new Vector<String[]>(); <add> if (file != null) { <add> BufferedReader br = new BufferedReader(new FileReader(file)); <add> for (String line; (line = br.readLine()) != null;) { <add> lines.add(line.split(";")); <add> } <add> br.close(); <add> } <add> return lines; <add> } <add> <add> protected InfosystemcallResult(Infosystemcall call) throws IOException { <add> this.call = call; <add> this.head = new TreeMap<String, String>(); <add> this.table = new Vector<TreeMap<String, String>>(); <add> this.lines = this.getLinesOfFile(call.outputFile); <add> boolean headFields = call.showAllHeadFields <add> || call.headOutputFields.size() > 0; <add> if (headFields) { <add> for (int i = 0; i < lines.get(0).length; i++) { <add> String key = lines.get(0)[i]; <add> head.put(key, lines.get(1)[i]); <add> } <add> } <add> if (call.showAllTableFields || call.tableOutputFields.size() > 0) { <add> // index der Variablennamen zeile in der Outputdatei festlegen <add> int row = (headFields) ? 2 : 0; <add> // zeile mit den Variablennamen speichern <add> String[] keys = lines.get(row); <add> // für jede Datenzeile <add> for (int j = row + 1; j < lines.size(); j++) { <add> TreeMap<String, String> foo = new TreeMap<String, String>(); <add> for (int i = 0; i < keys.length; i++) { <add> foo.put(keys[i], lines.get(j)[i]); <add> } <add> table.add(foo); <add> } <add> } <add> } <add> <add> public TreeMap<String, String> getHead() { <add> return this.head; <add> } <add> <add> public Vector<TreeMap<String, String>> getTable() { <add> return this.table; <add> } <add> <add> public String getOutputFile() { <add> return call.outputFile; <add> } <add> <add> public String getInfosystem() { <add> return call.infosystem; <add> } <add> <add> public String getCommando(){ <add> return call.getCommand(); <add> } <add> <add> public void printFile() { <add> for (String[] line : lines) { <add> for (String column : line) { <add> FO.println("-lfsuppress " + column + ";"); <add> } <add> FO.println(""); <add> } <add> } <add> <add>}