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
epl-1.0
a05ea241a2d6e67e583bbf0be9132d5f5fe257d3
0
opendaylight/yangtools,opendaylight/yangtools
/* * Copyright (c) 2014, 2015 Cisco Systems, Inc. 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.io.ByteStreams; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.commons.lang.SerializationUtils; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec; import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaContext; public class NormalizedNodeStreamReaderWriterTest { @Test public void testNormalizedNodeStreaming() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter( ByteStreams.newDataOutput(byteArrayOutputStream)); NormalizedNode<?, ?> testContainer = createTestContainer(); writer.writeNormalizedNode(testContainer); QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster"); QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor"); QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description"); ContainerNode toasterNode = Builders.containerBuilder(). withNodeIdentifier(new NodeIdentifier(toaster)). withChild(ImmutableNodes.leafNode(darknessFactor, "1000")). withChild(ImmutableNodes.leafNode(description, largeString(20))) .build(); ContainerNode toasterContainer = Builders.containerBuilder(). withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)). withChild(toasterNode).build(); writer.writeNormalizedNode(toasterContainer); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(byteArrayOutputStream.toByteArray())); NormalizedNode<?,?> node = reader.readNormalizedNode(); Assert.assertEquals(testContainer, node); node = reader.readNormalizedNode(); Assert.assertEquals(toasterContainer, node); writer.close(); } private static NormalizedNode<?, ?> createTestContainer() { byte[] bytes1 = {1,2,3}; LeafSetEntryNode<Object> entry1 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeWithValue(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)). withValue(bytes1).build(); byte[] bytes2 = {}; LeafSetEntryNode<Object> entry2 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeWithValue(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)). withValue(bytes2).build(); LeafSetEntryNode<Object> entry3 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeWithValue(TestModel.BINARY_LEAF_LIST_QNAME, null)). withValue(null).build(); return TestModel.createBaseTestContainerBuilder(). withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME)). withChild(entry1).withChild(entry2).withChild(entry3).build()). withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1,2,3,4})). withChild(Builders.orderedMapBuilder(). withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.ORDERED_LIST_QNAME)). withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME, TestModel.ID_QNAME, 11)).build()). build(); } @Test public void testYangInstanceIdentifierStreaming() throws IOException { YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH). node(TestModel.OUTER_LIST_QNAME).nodeWithKey( TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter(ByteStreams.newDataOutput(byteArrayOutputStream)); writer.writeYangInstanceIdentifier(path); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(byteArrayOutputStream.toByteArray())); YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier(); Assert.assertEquals(path, newPath); writer.close(); } @Test public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter( ByteStreams.newDataOutput(byteArrayOutputStream)); NormalizedNode<?, ?> testContainer = TestModel.createBaseTestContainerBuilder().build(); writer.writeNormalizedNode(testContainer); YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH). node(TestModel.OUTER_LIST_QNAME).nodeWithKey( TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build(); writer.writeYangInstanceIdentifier(path); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(byteArrayOutputStream.toByteArray())); NormalizedNode<?,?> node = reader.readNormalizedNode(); Assert.assertEquals(testContainer, node); YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier(); Assert.assertEquals(path, newPath); writer.close(); } @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) public void testInvalidNormalizedNodeStream() throws IOException { byte[] protobufBytes = new NormalizedNodeToNodeCodec(null).encode( TestModel.createBaseTestContainerBuilder().build()).getNormalizedNode().toByteArray(); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(protobufBytes)); reader.readNormalizedNode(); } @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) public void testInvalidYangInstanceIdentifierStream() throws IOException { byte[] protobufBytes = {1,2,3}; NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(protobufBytes)); reader.readYangInstanceIdentifier(); } @Test public void testWithSerializable() { NormalizedNode<?, ?> input = TestModel.createTestContainer(); SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(input ); SampleNormalizedNodeSerializable clone = (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable); Assert.assertEquals(input, clone.getInput()); } private static String largeString(final int pow){ String s = "X"; for(int i=0;i<pow;i++){ StringBuilder b = new StringBuilder(); b.append(s).append(s); s = b.toString(); } return s; } }
node/utils/stream/NormalizedNodeStreamReaderWriterTest.java
/* * Copyright (c) 2014, 2015 Cisco Systems, Inc. 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.io.ByteStreams; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.commons.lang.SerializationUtils; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec; import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils; import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.Builders; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaContext; public class NormalizedNodeStreamReaderWriterTest { @Test public void testNormalizedNodeStreaming() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter( ByteStreams.newDataOutput(byteArrayOutputStream)); NormalizedNode<?, ?> testContainer = createTestContainer(); writer.writeNormalizedNode(testContainer); QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster"); QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor"); QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description"); ContainerNode toasterNode = Builders.containerBuilder(). withNodeIdentifier(new NodeIdentifier(toaster)). withChild(ImmutableNodes.leafNode(darknessFactor, "1000")). withChild(ImmutableNodes.leafNode(description, largeString(20))) .build(); ContainerNode toasterContainer = Builders.containerBuilder(). withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)). withChild(toasterNode).build(); writer.writeNormalizedNode(toasterContainer); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(byteArrayOutputStream.toByteArray())); NormalizedNode<?,?> node = reader.readNormalizedNode(); Assert.assertEquals(testContainer, node); node = reader.readNormalizedNode(); Assert.assertEquals(toasterContainer, node); writer.close(); } private static NormalizedNode<?, ?> createTestContainer() { byte[] bytes1 = {1,2,3}; LeafSetEntryNode<Object> entry1 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeWithValue(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)). withValue(bytes1).build(); byte[] bytes2 = {}; LeafSetEntryNode<Object> entry2 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeWithValue(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)). withValue(bytes2).build(); LeafSetEntryNode<Object> entry3 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeWithValue(TestModel.BINARY_LEAF_LIST_QNAME, null)). withValue(null).build(); return TestModel.createBaseTestContainerBuilder(). withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME)). withChild(entry1).withChild(entry2).withChild(entry3).build()). withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1,2,3,4})). withChild(Builders.orderedMapBuilder(). withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.ORDERED_LIST_QNAME)). withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME, TestModel.ID_QNAME, 11)).build()). build(); } @Test public void testYangInstanceIdentifierStreaming() throws IOException { YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH). node(TestModel.OUTER_LIST_QNAME).nodeWithKey( TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter(ByteStreams.newDataOutput(byteArrayOutputStream)); writer.writeYangInstanceIdentifier(path); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(byteArrayOutputStream.toByteArray())); YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier(); Assert.assertEquals(path, newPath); writer.close(); } @Test public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter( ByteStreams.newDataOutput(byteArrayOutputStream)); NormalizedNode<?, ?> testContainer = TestModel.createBaseTestContainerBuilder().build(); writer.writeNormalizedNode(testContainer); YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH). node(TestModel.OUTER_LIST_QNAME).nodeWithKey( TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build(); writer.writeYangInstanceIdentifier(path); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(byteArrayOutputStream.toByteArray())); NormalizedNode<?,?> node = reader.readNormalizedNode(); Assert.assertEquals(testContainer, node); YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier(); Assert.assertEquals(path, newPath); writer.close(); } @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) public void testInvalidNormalizedNodeStream() throws IOException { byte[] protobufBytes = new NormalizedNodeToNodeCodec(null).encode( TestModel.createBaseTestContainerBuilder().build()).getNormalizedNode().toByteArray(); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(protobufBytes)); reader.readNormalizedNode(); } @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) public void testInvalidYangInstanceIdentifierStream() throws IOException { YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH).build(); byte[] protobufBytes = ShardTransactionMessages.DeleteData.newBuilder().setInstanceIdentifierPathArguments( InstanceIdentifierUtils.toSerializable(path)).build().toByteArray(); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( ByteStreams.newDataInput(protobufBytes)); reader.readYangInstanceIdentifier(); } @Test public void testWithSerializable() { NormalizedNode<?, ?> input = TestModel.createTestContainer(); SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(input ); SampleNormalizedNodeSerializable clone = (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable); Assert.assertEquals(input, clone.getInput()); } private static String largeString(final int pow){ String s = "X"; for(int i=0;i<pow;i++){ StringBuilder b = new StringBuilder(); b.append(s).append(s); s = b.toString(); } return s; } }
Remove Helium Tx modify operation messages Removed the following deprecated Helium Tx messages and related code: DeleteData[Reply] MergeData[Reply] WriteData[Reply] ReadyTransaction Also removed the associated protobuf message classes. Change-Id: I6f5db0096a60b50e51bf94b12f38941a4be9ca20 Signed-off-by: Tom Pantelis <[email protected]>
node/utils/stream/NormalizedNodeStreamReaderWriterTest.java
Remove Helium Tx modify operation messages
<ide><path>ode/utils/stream/NormalizedNodeStreamReaderWriterTest.java <ide> import org.junit.Assert; <ide> import org.junit.Test; <ide> import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec; <del>import org.opendaylight.controller.cluster.datastore.util.InstanceIdentifierUtils; <ide> import org.opendaylight.controller.cluster.datastore.util.TestModel; <del>import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages; <ide> import org.opendaylight.yangtools.yang.common.QName; <ide> import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; <ide> import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; <ide> <ide> @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) <ide> public void testInvalidYangInstanceIdentifierStream() throws IOException { <del> YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH).build(); <del> <del> byte[] protobufBytes = ShardTransactionMessages.DeleteData.newBuilder().setInstanceIdentifierPathArguments( <del> InstanceIdentifierUtils.toSerializable(path)).build().toByteArray(); <del> <add> byte[] protobufBytes = {1,2,3}; <ide> NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( <ide> ByteStreams.newDataInput(protobufBytes)); <ide>
Java
mpl-2.0
ac09efa49359207dbd046f68d611a62203db4664
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: TestParameters.java,v $ * * $Revision: 1.5 $ * * last change: $Author: pjunck $ $Date: 2004-11-02 11:42:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package lib; import java.util.Hashtable; import util.PropertyName; //import com.sun.star.lang.XMultiServiceFactory; /** * TestParameters describes a parameters (in a form of pairs: name, value) to * be passed to tests and which may affect the test behaviour. That can be, * for example, standard paths, connection strings, etc. The TestParameters * also provides XMultiServiceFactory for the test (tests). */ public class TestParameters extends Hashtable { /** * The ConnectionString for Office Connection<br> * default is 'socket,host=localhost,port=8100' */ public String ConnectionString="socket,host=localhost,port=8100"; /** * The AppProvider contains the Application Provider<br> * to control the ServiceFactory. */ public Object AppProvider=null; /** * The Process contains the Process handler<br> * to control the Application. */ public Object ProcessHandler=null; /** * The AppExecutionCmd contains the full qualified<br> * command to an Application to be started. */ public String AppExecutionCommand=""; /** * Shoert wait time for the Office: default is 500 milliseconds */ public int ShortWait = 500; /** * The OfficeProvider contains the full qualified * class that provides a connection to StarOffice<br> * default is helper.OfficeProvider */ public String OfficeProvider = "helper.OfficeProvider"; /** * The Testbase to be executed by the runner<br> * default is 'java_fat' */ public String TestBase="java_fat"; /** * The ServiceFactory to create instances */ public Object ServiceFactory; /** * The Path to the component description */ public String DescriptionPath; /** * The Path to the test documents that are loaded during the test <br> * default will be the tmp dir */ public String TestDocumentPath=System.getProperty("java.io.tmpdir"); /** * 'true' is a log should be written, 'false' elsewhere <br> * these will be provided by the testcases<br> * default is true */ public boolean LoggingIsActive=true; /** * 'true' is a debug information should be written, 'false' elsewhere * these will be provided by the framework.<br> * Debug information will always be written on standard out.<br> * default is true */ public boolean DebugIsActive=false; /* * This parameter contains the testjob to be executed<br> * by the framework */ public Object TestJob; /* * This parameter contains the class used<br> * for Logging */ public String LogWriter="stats.SimpleLogWriter"; /* * This parameter contains the class used<br> * for Logging */ public String OutProducer="stats.SimpleOutProducer"; /* * This parameter contains the timeout used<br> * by the watcher */ public Integer TimeOut = new Integer(30000); /** * Wraper around "get()" with some debug output * @param key A key of this table. * @return The value of this key. * @see java.util.Hashtable */ public Object get(Object key) { Object val = super.get(key); if (val == null && DebugIsActive) { System.out.print("Have been asked for key \""+key.toString()); System.out.println("\" which is not part of params."); } return val; } /** * Special get method for boolean values: for convenience. * Will return 'false' if the value is not of "Boolean" type. * @param key A key of this table. * @return The value of this key, castet to a boolean type. */ public boolean getBool(Object key) { Object val = super.get(key); if (val != null) { if (val instanceof String) { String sVal = (String)val; if (sVal.equalsIgnoreCase("true") || sVal.equalsIgnoreCase("yes")) { return true; } else if (sVal.equalsIgnoreCase("false") || sVal.equalsIgnoreCase("no")) { return false; } } if (val instanceof Boolean) return ((Boolean)val).booleanValue(); } return false; } /** * Special get method for integer values: for convenience. * Will return 0 if the value cannot be interpreted as Integer. * @param key A key of this table. * @return The value of this key, castet to an int type. */ public int getInt(Object key) { Object val = super.get(key); if ( val != null ) { if (val instanceof Integer) { return ((Integer)val).intValue(); } else { try { if ( val instanceof String ) { Integer nr = new Integer((String)val); if (nr.intValue() > 0) return nr.intValue(); } } catch ( java.lang.NumberFormatException nfe) {} } } return 0; } /** * Wraper around "put()" * @param key A key of this table. * @param val The value of the key. * @return The value of this key. * @see java.util.Hashtable */ public Object put(Object key, Object val) { return super.put(key,val); } /** * Constructor, defaults for Parameters are set. */ public TestParameters() { //fill the propertyset put(PropertyName.CONNECTION_STRING,ConnectionString); put(PropertyName.TEST_BASE,TestBase); put(PropertyName.TEST_DOCUMENT_PATH,TestDocumentPath); put(PropertyName.LOGGING_IS_ACTIVE,Boolean.valueOf(LoggingIsActive)); put(PropertyName.DEBUG_IS_ACTIVE,Boolean.valueOf(DebugIsActive)); put(PropertyName.OUT_PRODUCER,OutProducer); put(PropertyName.SHORT_WAIT,new Integer(ShortWait)); put(PropertyName.OFFICE_PROVIDER,OfficeProvider); put(PropertyName.LOG_WRITER,LogWriter); put(PropertyName.APP_EXECUTION_COMMAND,AppExecutionCommand); put(PropertyName.TIME_OUT,TimeOut); // get the operating system put(PropertyName.OPERATING_SYSTEM, getSOCompatibleOSName()); //For compatibility Reasons put("CNCSTR",ConnectionString); put("DOCPTH",TestDocumentPath); System.setProperty("DOCPTH",TestDocumentPath); } /** * @return a XMultiServiceFactory to be used by a test (tests). */ public Object getMSF() { Object ret = null; ret = get("ServiceFactory"); return ret; } /** * Convert the system dependent operating system name to a name according * to OOo rules. * @return A valid OS name, or "" if the name is not known. */ String getSOCompatibleOSName() { String osname = System.getProperty ("os.name").toLowerCase (); String osarch = System.getProperty ("os.arch"); String operatingSystem = ""; if (osname.indexOf ("windows")>-1) { operatingSystem = PropertyName.WNTMSCI; } else if (osname.indexOf ("linux")>-1) { operatingSystem = PropertyName.UNXLNGI; } else if (osname.indexOf ("sunos")>-1) { if (osarch.equals ("x86")) { operatingSystem = PropertyName.UNXSOLI; } else { operatingSystem = PropertyName.UNXSOLS; } } return operatingSystem; } }// finish class TestParamenters
qadevOOo/runner/lib/TestParameters.java
/************************************************************************* * * $RCSfile: TestParameters.java,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2003-11-18 16:16:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package lib; import java.util.Hashtable; //import com.sun.star.lang.XMultiServiceFactory; /** * TestParameters describes a parameters (in a form of pairs: name, value) to * be passed to tests and which may affect the test behaviour. That can be, * for example, standard paths, connection strings, etc. The TestParameters * also provides XMultiServiceFactory for the test (tests). */ public class TestParameters extends Hashtable { /** * The ConnectionString for Office Connection<br> * default is 'socket,host=localhost,port=8100' */ public String ConnectionString="socket,host=localhost,port=8100"; /** * The AppProvider contains the Application Provider<br> * to control the ServiceFactory. */ public Object AppProvider=null; /** * The Process contains the Process handler<br> * to control the Application. */ public Object ProcessHandler=null; /** * The AppExecutionCmd contains the full qualified<br> * command to an Application to be started. */ public String AppExecutionCommand=""; /** * The OfficeProvider contains the full qualified * class that provides a connection to StarOffice<br> * default is helper.OfficeProvider */ public String OfficeProvider = "helper.OfficeProvider"; /** * The Testbase to be executed by the runner<br> * default is 'java_fat' */ public String TestBase="java_fat"; /** * The ServiceFactory to create instances */ public Object ServiceFactory; /** * The Path to the component description */ public String DescriptionPath; /** * The Path to the test documents that are loaded during the test <br> * default will be the tmp dir */ public String TestDocumentPath=System.getProperty("java.io.tmpdir"); /** * 'true' is a log should be written, 'false' elsewhere <br> * these will be provided by the testcases<br> * default is true */ public boolean LoggingIsActive=true; /** * 'true' is a debug information should be written, 'false' elsewhere * these will be provided by the framework.<br> * Debug information will always be written on standard out.<br> * default is true */ public boolean DebugIsActive=false; /* * This parameter contains the testjob to be executed<br> * by the framework */ public Object TestJob; /* * This parameter contains the class used<br> * for Logging */ public String LogWriter="stats.SimpleLogWriter"; /* * This parameter contains the class used<br> * for Logging */ public String OutProducer="stats.SimpleOutProducer"; /* * This parameter contains the timeout used<br> * by the watcher */ public Integer TimeOut = new Integer(30000); /** * Wraper around "get()" with some debug output * @param key A key of this table. * @return The value of this key. * @see java.util.Hashtable */ public Object get(Object key) { Object val = super.get(key); if (val == null && DebugIsActive) { System.out.print("Have been asked for key \""+key.toString()); System.out.println("\" which is not part of params."); } return val; } /** * Special get method for boolean values: for convenience. * Will return 'false' if the value is not of "Boolean" type. * @param key A key of this table. * @return The value of this key, castet to a boolean type. */ public boolean getBool(Object key) { Object val = super.get(key); if (val != null) { if (val instanceof String) { String sVal = (String)val; if (sVal.equalsIgnoreCase("true") || sVal.equalsIgnoreCase("yes")) { return true; } else if (sVal.equalsIgnoreCase("false") || sVal.equalsIgnoreCase("no")) { return false; } } if (val instanceof Boolean) return ((Boolean)val).booleanValue(); } return false; } /** * Special get method for integer values: for convenience. * Will return 0 if the value cannot be interpreted as Integer. * @param key A key of this table. * @return The value of this key, castet to an int type. */ public int getInt(Object key) { Object val = super.get(key); if ( val != null ) { if (val instanceof Integer) { return ((Integer)val).intValue(); } else { try { if ( val instanceof String ) { Integer nr = new Integer((String)val); if (nr.intValue() > 0) return nr.intValue(); } } catch ( java.lang.NumberFormatException nfe) {} } } return 0; } /** * Wraper around "put()" * @param key A key of this table. * @param val The value of the key. * @return The value of this key. * @see java.util.Hashtable */ public Object put(Object key, Object val) { return super.put(key,val); } /** * Constructor, defaults for Parameters are set. */ public TestParameters() { //fill the propertyset put("ConnectionString",ConnectionString); put("TestBase",TestBase); put("TestDocumentPath",TestDocumentPath); put("LoggingIsActive",Boolean.valueOf(LoggingIsActive)); put("DebugIsActive",Boolean.valueOf(DebugIsActive)); put("OutProducer",OutProducer); put("OfficeProvider",OfficeProvider); put("LogWriter",LogWriter); put("AppExecutionCommand",AppExecutionCommand); put("TimeOut",TimeOut); //For compatibility Reasons put("CNCSTR",ConnectionString); put("DOCPTH",TestDocumentPath); System.setProperty("DOCPTH",TestDocumentPath); } /** * @return a XMultiServiceFactory to be used by a test (tests). */ public Object getMSF() { Object ret = null; ret = get("ServiceFactory"); return ret; } }// finish class TestParamenters
INTEGRATION: CWS qadev19 (1.4.78); FILE MERGED 2004/09/17 12:00:28 sg 1.4.78.2: #i32878#CHG: fixed bugs 2004/08/27 15:17:07 sg 1.4.78.1: #i32942#CHG: initialize 'OperatingSystem' variable.
qadevOOo/runner/lib/TestParameters.java
INTEGRATION: CWS qadev19 (1.4.78); FILE MERGED 2004/09/17 12:00:28 sg 1.4.78.2: #i32878#CHG: fixed bugs 2004/08/27 15:17:07 sg 1.4.78.1: #i32942#CHG: initialize 'OperatingSystem' variable.
<ide><path>adevOOo/runner/lib/TestParameters.java <ide> * <ide> * $RCSfile: TestParameters.java,v $ <ide> * <del> * $Revision: 1.4 $ <del> * <del> * last change: $Author: kz $ $Date: 2003-11-18 16:16:03 $ <add> * $Revision: 1.5 $ <add> * <add> * last change: $Author: pjunck $ $Date: 2004-11-02 11:42:52 $ <ide> * <ide> * The Contents of this file are made available subject to the terms of <ide> * either of the following licenses <ide> package lib; <ide> <ide> import java.util.Hashtable; <add>import util.PropertyName; <add> <ide> //import com.sun.star.lang.XMultiServiceFactory; <ide> <ide> /** <ide> */ <ide> <ide> public String AppExecutionCommand=""; <add> <add> /** <add> * Shoert wait time for the Office: default is 500 milliseconds <add> */ <add> public int ShortWait = 500; <ide> <ide> <ide> /** <ide> /** <ide> * Constructor, defaults for Parameters are set. <ide> */ <del> <ide> public TestParameters() { <ide> //fill the propertyset <del> put("ConnectionString",ConnectionString); <del> put("TestBase",TestBase); <del> put("TestDocumentPath",TestDocumentPath); <del> put("LoggingIsActive",Boolean.valueOf(LoggingIsActive)); <del> put("DebugIsActive",Boolean.valueOf(DebugIsActive)); <del> put("OutProducer",OutProducer); <del> put("OfficeProvider",OfficeProvider); <del> put("LogWriter",LogWriter); <del> put("AppExecutionCommand",AppExecutionCommand); <del> put("TimeOut",TimeOut); <add> put(PropertyName.CONNECTION_STRING,ConnectionString); <add> put(PropertyName.TEST_BASE,TestBase); <add> put(PropertyName.TEST_DOCUMENT_PATH,TestDocumentPath); <add> put(PropertyName.LOGGING_IS_ACTIVE,Boolean.valueOf(LoggingIsActive)); <add> put(PropertyName.DEBUG_IS_ACTIVE,Boolean.valueOf(DebugIsActive)); <add> put(PropertyName.OUT_PRODUCER,OutProducer); <add> put(PropertyName.SHORT_WAIT,new Integer(ShortWait)); <add> put(PropertyName.OFFICE_PROVIDER,OfficeProvider); <add> put(PropertyName.LOG_WRITER,LogWriter); <add> put(PropertyName.APP_EXECUTION_COMMAND,AppExecutionCommand); <add> put(PropertyName.TIME_OUT,TimeOut); <add> <add> // get the operating system <add> put(PropertyName.OPERATING_SYSTEM, getSOCompatibleOSName()); <ide> <ide> //For compatibility Reasons <ide> put("CNCSTR",ConnectionString); <ide> return ret; <ide> } <ide> <add> /** <add> * Convert the system dependent operating system name to a name according <add> * to OOo rules. <add> * @return A valid OS name, or "" if the name is not known. <add> */ <add> String getSOCompatibleOSName() { <add> String osname = System.getProperty ("os.name").toLowerCase (); <add> String osarch = System.getProperty ("os.arch"); <add> String operatingSystem = ""; <add> if (osname.indexOf ("windows")>-1) { <add> operatingSystem = PropertyName.WNTMSCI; <add> } else if (osname.indexOf ("linux")>-1) { <add> operatingSystem = PropertyName.UNXLNGI; <add> } else if (osname.indexOf ("sunos")>-1) { <add> if (osarch.equals ("x86")) { <add> operatingSystem = PropertyName.UNXSOLI; <add> } else { <add> operatingSystem = PropertyName.UNXSOLS; <add> } <add> } <add> return operatingSystem; <add> } <add> <ide> }// finish class TestParamenters
Java
apache-2.0
2ff6b1adbc09450f5681135f27fcc34e1ce9d4c9
0
GFriedrich/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,lqbweb/logging-log4j2,apache/logging-log4j2,lburgazzoli/apache-logging-log4j2,lburgazzoli/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,GFriedrich/logging-log4j2,lburgazzoli/logging-log4j2,lburgazzoli/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,xnslong/logging-log4j2,lqbweb/logging-log4j2,xnslong/logging-log4j2,xnslong/logging-log4j2
/* * 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.logging.log4j.core.layout; import java.nio.charset.Charset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.DefaultConfiguration; import org.apache.logging.log4j.core.config.Node; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; import org.apache.logging.log4j.core.pattern.PatternFormatter; import org.apache.logging.log4j.core.pattern.PatternParser; import org.apache.logging.log4j.core.pattern.RegexReplacement; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; /** * A flexible layout configurable with pattern string. * <p> * The goal of this class is to {@link org.apache.logging.log4j.core.Layout#toByteArray format} a {@link LogEvent} and * return the results. The format of the result depends on the <em>conversion pattern</em>. * </p> * <p> * The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern * is composed of literal text and format control expressions called <em>conversion specifiers</em>. * </p> * <p> * See the Log4j Manual for details on the supported pattern converters. * </p> */ @Plugin(name = "PatternLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true) public final class PatternLayout extends AbstractStringLayout { /** * Default pattern string for log output. Currently set to the string <b>"%m%n"</b> which just prints the * application supplied message. */ public static final String DEFAULT_CONVERSION_PATTERN = "%m%n"; /** * A conversion pattern equivalent to the TTCCCLayout. Current value is <b>%r [%t] %p %c %x - %m%n</b>. */ public static final String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n"; /** * A simple pattern. Current value is <b>%d [%t] %p %c - %m%n</b>. */ public static final String SIMPLE_CONVERSION_PATTERN = "%d [%t] %p %c - %m%n"; /** Key to identify pattern converters. */ public static final String KEY = "Converter"; private static final long serialVersionUID = 1L; private static final ThreadLocal<TextEncoderHelper> textEncoderHelper = new ThreadLocal<>(); /** * Conversion pattern. */ private final String conversionPattern; private final PatternSelector patternSelector; private final Serializer eventSerializer; /** * Constructs a EnhancedPatternLayout using the supplied conversion pattern. * * @param config The Configuration. * @param replace The regular expression to match. * @param eventPattern conversion pattern. * @param patternSelector The PatternSelector. * @param charset The character set. * @param alwaysWriteExceptions Whether or not exceptions should always be handled in this pattern (if {@code true}, * exceptions will be written even if the pattern does not specify so). * @param noConsoleNoAnsi * If {@code "true"} (default) and {@link System#console()} is null, do not output ANSI escape codes * @param headerPattern header conversion pattern. * @param footerPattern footer conversion pattern. */ private PatternLayout(final Configuration config, final RegexReplacement replace, final String eventPattern, final PatternSelector patternSelector, final Charset charset, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi, final String headerPattern, final String footerPattern) { super(config, charset, createSerializer(config, replace, headerPattern, null, patternSelector, alwaysWriteExceptions, noConsoleNoAnsi), createSerializer(config, replace, footerPattern, null, patternSelector, alwaysWriteExceptions, noConsoleNoAnsi)); this.conversionPattern = eventPattern; this.patternSelector = patternSelector; this.eventSerializer = createSerializer(config, replace, eventPattern, DEFAULT_CONVERSION_PATTERN, patternSelector, alwaysWriteExceptions, noConsoleNoAnsi); } public static Serializer createSerializer(final Configuration configuration, final RegexReplacement replace, final String pattern, final String defaultPattern, final PatternSelector patternSelector, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi) { if (Strings.isEmpty(pattern) && Strings.isEmpty(defaultPattern)) { return null; } if (patternSelector == null) { try { final PatternParser parser = createPatternParser(configuration); final List<PatternFormatter> list = parser.parse(pattern == null ? defaultPattern : pattern, alwaysWriteExceptions, noConsoleNoAnsi); final PatternFormatter[] formatters = list.toArray(new PatternFormatter[0]); return new PatternSerializer(formatters, replace); } catch (final RuntimeException ex) { throw new IllegalArgumentException("Cannot parse pattern '" + pattern + "'", ex); } } return new PatternSelectorSerializer(patternSelector, replace); } /** * Gets the conversion pattern. * * @return the conversion pattern. */ public String getConversionPattern() { return conversionPattern; } /** * Gets this PatternLayout's content format. Specified by: * <ul> * <li>Key: "structured" Value: "false"</li> * <li>Key: "formatType" Value: "conversion" (format uses the keywords supported by OptionConverter)</li> * <li>Key: "format" Value: provided "conversionPattern" param</li> * </ul> * * @return Map of content format keys supporting PatternLayout */ @Override public Map<String, String> getContentFormat() { final Map<String, String> result = new HashMap<>(); result.put("structured", "false"); result.put("formatType", "conversion"); result.put("format", conversionPattern); return result; } /** * Formats a logging event to a writer. * * @param event logging event to be formatted. * @return The event formatted as a String. */ @Override public String toSerializable(final LogEvent event) { return eventSerializer.toSerializable(event); } @Override public void encode(final LogEvent event, final ByteBufferDestination destination) { if (!Constants.ENABLE_THREADLOCALS || !(eventSerializer instanceof Serializer2)) { super.encode(event, destination); return; } final StringBuilder text = toText((Serializer2) eventSerializer, event, getStringBuilder()); final TextEncoderHelper helper = getCachedTextEncoderHelper(); helper.encodeText(text, destination); } /** * Creates a text representation of the specified log event * and writes it into the specified StringBuilder. * <p> * Implementations are free to return a new StringBuilder if they can * detect in advance that the specified StringBuilder is too small. */ private StringBuilder toText(final Serializer2 serializer, final LogEvent event, final StringBuilder destination) { return serializer.toSerializable(event, destination); } private TextEncoderHelper getCachedTextEncoderHelper() { TextEncoderHelper result = textEncoderHelper.get(); if (result == null) { result = new TextEncoderHelper(getCharset()); textEncoderHelper.set(result); } return result; } /** * Creates a PatternParser. * @param config The Configuration. * @return The PatternParser. */ public static PatternParser createPatternParser(final Configuration config) { if (config == null) { return new PatternParser(config, KEY, LogEventPatternConverter.class); } PatternParser parser = config.getComponent(KEY); if (parser == null) { parser = new PatternParser(config, KEY, LogEventPatternConverter.class); config.addComponent(KEY, parser); parser = config.getComponent(KEY); } return parser; } @Override public String toString() { return patternSelector == null ? conversionPattern : patternSelector.toString(); } /** * Creates a pattern layout. * * @param pattern * The pattern. If not specified, defaults to DEFAULT_CONVERSION_PATTERN. * @param patternSelector * Allows different patterns to be used based on some selection criteria. * @param config * The Configuration. Some Converters require access to the Interpolator. * @param replace * A Regex replacement String. * @param charset * The character set. The platform default is used if not specified. * @param alwaysWriteExceptions * If {@code "true"} (default) exceptions are always written even if the pattern contains no exception tokens. * @param noConsoleNoAnsi * If {@code "true"} (default is false) and {@link System#console()} is null, do not output ANSI escape codes * @param headerPattern * The footer to place at the top of the document, once. * @param footerPattern * The footer to place at the bottom of the document, once. * @return The PatternLayout. */ @PluginFactory public static PatternLayout createLayout( @PluginAttribute(value = "pattern", defaultString = DEFAULT_CONVERSION_PATTERN) final String pattern, @PluginElement("PatternSelector") final PatternSelector patternSelector, @PluginConfiguration final Configuration config, @PluginElement("Replace") final RegexReplacement replace, // LOG4J2-783 use platform default by default, so do not specify defaultString for charset @PluginAttribute(value = "charset") final Charset charset, @PluginAttribute(value = "alwaysWriteExceptions", defaultBoolean = true) final boolean alwaysWriteExceptions, @PluginAttribute(value = "noConsoleNoAnsi", defaultBoolean = false) final boolean noConsoleNoAnsi, @PluginAttribute("header") final String headerPattern, @PluginAttribute("footer") final String footerPattern) { return newBuilder() .withPattern(pattern) .withPatternSelector(patternSelector) .withConfiguration(config) .withRegexReplacement(replace) .withCharset(charset) .withAlwaysWriteExceptions(alwaysWriteExceptions) .withNoConsoleNoAnsi(noConsoleNoAnsi) .withHeader(headerPattern) .withFooter(footerPattern) .build(); } private static class PatternSerializer implements Serializer, Serializer2 { private final PatternFormatter[] formatters; private final RegexReplacement replace; private PatternSerializer(final PatternFormatter[] formatters, final RegexReplacement replace) { super(); this.formatters = formatters; this.replace = replace; } @Override public String toSerializable(final LogEvent event) { final StringBuilder buf = getStringBuilder(); return toSerializable(event, buf).toString(); } @Override public StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) { final int len = formatters.length; for (int i = 0; i < len; i++) { formatters[i].format(event, buffer); } if (replace != null) { // creates temporary objects String str = buffer.toString(); str = replace.format(str); buffer.setLength(0); buffer.append(str); } return buffer; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); builder.append("[formatters="); builder.append(Arrays.toString(formatters)); builder.append(", replace="); builder.append(replace); builder.append("]"); return builder.toString(); } } private static class PatternSelectorSerializer implements Serializer, Serializer2 { private final PatternSelector patternSelector; private final RegexReplacement replace; private PatternSelectorSerializer(final PatternSelector patternSelector, final RegexReplacement replace) { super(); this.patternSelector = patternSelector; this.replace = replace; } @Override public String toSerializable(final LogEvent event) { final StringBuilder buf = getStringBuilder(); return toSerializable(event, buf).toString(); } @Override public StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) { final PatternFormatter[] formatters = patternSelector.getFormatters(event); final int len = formatters.length; for (int i = 0; i < len; i++) { formatters[i].format(event, buffer); } if (replace != null) { // creates temporary objects String str = buffer.toString(); str = replace.format(str); buffer.setLength(0); buffer.append(str); } return buffer; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); builder.append("[patternSelector="); builder.append(patternSelector); builder.append(", replace="); builder.append(replace); builder.append("]"); return builder.toString(); } } /** * Creates a PatternLayout using the default options. These options include using UTF-8, the default conversion * pattern, exceptions being written, and with ANSI escape codes. * * @return the PatternLayout. * @see #DEFAULT_CONVERSION_PATTERN Default conversion pattern */ public static PatternLayout createDefaultLayout() { return newBuilder().build(); } /** * Creates a PatternLayout using the default options and the given configuration. These options include using UTF-8, * the default conversion pattern, exceptions being written, and with ANSI escape codes. * * @param configuration The Configuration. * * @return the PatternLayout. * @see #DEFAULT_CONVERSION_PATTERN Default conversion pattern */ public static PatternLayout createDefaultLayout(final Configuration configuration) { return newBuilder().withConfiguration(configuration).build(); } /** * Creates a builder for a custom PatternLayout. * * @return a PatternLayout builder. */ @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } /** * Custom PatternLayout builder. Use the {@link PatternLayout#newBuilder() builder factory method} to create this. */ public static class Builder implements org.apache.logging.log4j.core.util.Builder<PatternLayout> { @PluginBuilderAttribute private String pattern = PatternLayout.DEFAULT_CONVERSION_PATTERN; @PluginElement("PatternSelector") private PatternSelector patternSelector = null; @PluginConfiguration private Configuration configuration = null; @PluginElement("Replace") private RegexReplacement regexReplacement = null; // LOG4J2-783 use platform default by default @PluginBuilderAttribute private Charset charset = Charset.defaultCharset(); @PluginBuilderAttribute private boolean alwaysWriteExceptions = true; @PluginBuilderAttribute private boolean noConsoleNoAnsi = false; @PluginBuilderAttribute private String header = null; @PluginBuilderAttribute private String footer = null; private Builder() { } // TODO: move javadocs from PluginFactory to here public Builder withPattern(final String pattern) { this.pattern = pattern; return this; } public Builder withPatternSelector(final PatternSelector patternSelector) { this.patternSelector = patternSelector; return this; } public Builder withConfiguration(final Configuration configuration) { this.configuration = configuration; return this; } public Builder withRegexReplacement(final RegexReplacement regexReplacement) { this.regexReplacement = regexReplacement; return this; } public Builder withCharset(final Charset charset) { // LOG4J2-783 if null, use platform default by default if (charset != null) { this.charset = charset; } return this; } public Builder withAlwaysWriteExceptions(final boolean alwaysWriteExceptions) { this.alwaysWriteExceptions = alwaysWriteExceptions; return this; } public Builder withNoConsoleNoAnsi(final boolean noConsoleNoAnsi) { this.noConsoleNoAnsi = noConsoleNoAnsi; return this; } public Builder withHeader(final String header) { this.header = header; return this; } public Builder withFooter(final String footer) { this.footer = footer; return this; } @Override public PatternLayout build() { // fall back to DefaultConfiguration if (configuration == null) { configuration = new DefaultConfiguration(); } return new PatternLayout(configuration, regexReplacement, pattern, patternSelector, charset, alwaysWriteExceptions, noConsoleNoAnsi, header, footer); } } }
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/PatternLayout.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.logging.log4j.core.layout; import java.nio.charset.Charset; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.DefaultConfiguration; import org.apache.logging.log4j.core.config.Node; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; import org.apache.logging.log4j.core.pattern.PatternFormatter; import org.apache.logging.log4j.core.pattern.PatternParser; import org.apache.logging.log4j.core.pattern.RegexReplacement; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; /** * A flexible layout configurable with pattern string. * <p> * The goal of this class is to {@link org.apache.logging.log4j.core.Layout#toByteArray format} a {@link LogEvent} and * return the results. The format of the result depends on the <em>conversion pattern</em>. * </p> * <p> * The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern * is composed of literal text and format control expressions called <em>conversion specifiers</em>. * </p> * <p> * See the Log4j Manual for details on the supported pattern converters. * </p> */ @Plugin(name = "PatternLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true) public final class PatternLayout extends AbstractStringLayout { /** * Default pattern string for log output. Currently set to the string <b>"%m%n"</b> which just prints the * application supplied message. */ public static final String DEFAULT_CONVERSION_PATTERN = "%m%n"; /** * A conversion pattern equivalent to the TTCCCLayout. Current value is <b>%r [%t] %p %c %x - %m%n</b>. */ public static final String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n"; /** * A simple pattern. Current value is <b>%d [%t] %p %c - %m%n</b>. */ public static final String SIMPLE_CONVERSION_PATTERN = "%d [%t] %p %c - %m%n"; /** Key to identify pattern converters. */ public static final String KEY = "Converter"; private static final long serialVersionUID = 1L; private static final ThreadLocal<TextEncoderHelper> textEncoderHelper = new ThreadLocal<>(); /** * Conversion pattern. */ private final String conversionPattern; private final PatternSelector patternSelector; private final Serializer eventSerializer; /** * Constructs a EnhancedPatternLayout using the supplied conversion pattern. * * @param config The Configuration. * @param replace The regular expression to match. * @param eventPattern conversion pattern. * @param patternSelector The PatternSelector. * @param charset The character set. * @param alwaysWriteExceptions Whether or not exceptions should always be handled in this pattern (if {@code true}, * exceptions will be written even if the pattern does not specify so). * @param noConsoleNoAnsi * If {@code "true"} (default) and {@link System#console()} is null, do not output ANSI escape codes * @param headerPattern header conversion pattern. * @param footerPattern footer conversion pattern. */ private PatternLayout(final Configuration config, final RegexReplacement replace, final String eventPattern, final PatternSelector patternSelector, final Charset charset, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi, final String headerPattern, final String footerPattern) { super(config, charset, createSerializer(config, replace, headerPattern, null, patternSelector, alwaysWriteExceptions, noConsoleNoAnsi), createSerializer(config, replace, footerPattern, null, patternSelector, alwaysWriteExceptions, noConsoleNoAnsi)); this.conversionPattern = eventPattern; this.patternSelector = patternSelector; this.eventSerializer = createSerializer(config, replace, eventPattern, DEFAULT_CONVERSION_PATTERN, patternSelector, alwaysWriteExceptions, noConsoleNoAnsi); } public static Serializer createSerializer(final Configuration configuration, final RegexReplacement replace, final String pattern, final String defaultPattern, final PatternSelector patternSelector, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi) { if (Strings.isEmpty(pattern) && Strings.isEmpty(defaultPattern)) { return null; } if (patternSelector == null) { try { final PatternParser parser = createPatternParser(configuration); final List<PatternFormatter> list = parser.parse(pattern == null ? defaultPattern : pattern, alwaysWriteExceptions, noConsoleNoAnsi); final PatternFormatter[] formatters = list.toArray(new PatternFormatter[0]); return new PatternSerializer(formatters, replace); } catch (final RuntimeException ex) { throw new IllegalArgumentException("Cannot parse pattern '" + pattern + "'", ex); } } return new PatternSelectorSerializer(patternSelector, replace); } /** * Gets the conversion pattern. * * @return the conversion pattern. */ public String getConversionPattern() { return conversionPattern; } /** * Gets this PatternLayout's content format. Specified by: * <ul> * <li>Key: "structured" Value: "false"</li> * <li>Key: "formatType" Value: "conversion" (format uses the keywords supported by OptionConverter)</li> * <li>Key: "format" Value: provided "conversionPattern" param</li> * </ul> * * @return Map of content format keys supporting PatternLayout */ @Override public Map<String, String> getContentFormat() { final Map<String, String> result = new HashMap<>(); result.put("structured", "false"); result.put("formatType", "conversion"); result.put("format", conversionPattern); return result; } /** * Formats a logging event to a writer. * * @param event logging event to be formatted. * @return The event formatted as a String. */ @Override public String toSerializable(final LogEvent event) { return eventSerializer.toSerializable(event); } @Override public void encode(final LogEvent event, final ByteBufferDestination destination) { if (!Constants.ENABLE_OBJECT_POOLING || !(eventSerializer instanceof Serializer2)) { super.encode(event, destination); return; } final StringBuilder text = toText((Serializer2) eventSerializer, event, getStringBuilder()); final TextEncoderHelper helper = getCachedTextEncoderHelper(); helper.encodeText(text, destination); } /** * Creates a text representation of the specified log event * and writes it into the specified StringBuilder. * <p> * Implementations are free to return a new StringBuilder if they can * detect in advance that the specified StringBuilder is too small. */ private StringBuilder toText(final Serializer2 serializer, final LogEvent event, final StringBuilder destination) { return serializer.toSerializable(event, destination); } private TextEncoderHelper getCachedTextEncoderHelper() { TextEncoderHelper result = textEncoderHelper.get(); if (result == null) { result = new TextEncoderHelper(getCharset()); textEncoderHelper.set(result); } return result; } /** * Creates a PatternParser. * @param config The Configuration. * @return The PatternParser. */ public static PatternParser createPatternParser(final Configuration config) { if (config == null) { return new PatternParser(config, KEY, LogEventPatternConverter.class); } PatternParser parser = config.getComponent(KEY); if (parser == null) { parser = new PatternParser(config, KEY, LogEventPatternConverter.class); config.addComponent(KEY, parser); parser = config.getComponent(KEY); } return parser; } @Override public String toString() { return patternSelector == null ? conversionPattern : patternSelector.toString(); } /** * Creates a pattern layout. * * @param pattern * The pattern. If not specified, defaults to DEFAULT_CONVERSION_PATTERN. * @param patternSelector * Allows different patterns to be used based on some selection criteria. * @param config * The Configuration. Some Converters require access to the Interpolator. * @param replace * A Regex replacement String. * @param charset * The character set. The platform default is used if not specified. * @param alwaysWriteExceptions * If {@code "true"} (default) exceptions are always written even if the pattern contains no exception tokens. * @param noConsoleNoAnsi * If {@code "true"} (default is false) and {@link System#console()} is null, do not output ANSI escape codes * @param headerPattern * The footer to place at the top of the document, once. * @param footerPattern * The footer to place at the bottom of the document, once. * @return The PatternLayout. */ @PluginFactory public static PatternLayout createLayout( @PluginAttribute(value = "pattern", defaultString = DEFAULT_CONVERSION_PATTERN) final String pattern, @PluginElement("PatternSelector") final PatternSelector patternSelector, @PluginConfiguration final Configuration config, @PluginElement("Replace") final RegexReplacement replace, // LOG4J2-783 use platform default by default, so do not specify defaultString for charset @PluginAttribute(value = "charset") final Charset charset, @PluginAttribute(value = "alwaysWriteExceptions", defaultBoolean = true) final boolean alwaysWriteExceptions, @PluginAttribute(value = "noConsoleNoAnsi", defaultBoolean = false) final boolean noConsoleNoAnsi, @PluginAttribute("header") final String headerPattern, @PluginAttribute("footer") final String footerPattern) { return newBuilder() .withPattern(pattern) .withPatternSelector(patternSelector) .withConfiguration(config) .withRegexReplacement(replace) .withCharset(charset) .withAlwaysWriteExceptions(alwaysWriteExceptions) .withNoConsoleNoAnsi(noConsoleNoAnsi) .withHeader(headerPattern) .withFooter(footerPattern) .build(); } private static class PatternSerializer implements Serializer, Serializer2 { private final PatternFormatter[] formatters; private final RegexReplacement replace; private PatternSerializer(final PatternFormatter[] formatters, final RegexReplacement replace) { super(); this.formatters = formatters; this.replace = replace; } @Override public String toSerializable(final LogEvent event) { final StringBuilder buf = getStringBuilder(); return toSerializable(event, buf).toString(); } @Override public StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) { final int len = formatters.length; for (int i = 0; i < len; i++) { formatters[i].format(event, buffer); } if (replace != null) { // creates temporary objects String str = buffer.toString(); str = replace.format(str); buffer.setLength(0); buffer.append(str); } return buffer; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); builder.append("[formatters="); builder.append(Arrays.toString(formatters)); builder.append(", replace="); builder.append(replace); builder.append("]"); return builder.toString(); } } private static class PatternSelectorSerializer implements Serializer, Serializer2 { private final PatternSelector patternSelector; private final RegexReplacement replace; private PatternSelectorSerializer(final PatternSelector patternSelector, final RegexReplacement replace) { super(); this.patternSelector = patternSelector; this.replace = replace; } @Override public String toSerializable(final LogEvent event) { final StringBuilder buf = getStringBuilder(); return toSerializable(event, buf).toString(); } @Override public StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) { final PatternFormatter[] formatters = patternSelector.getFormatters(event); final int len = formatters.length; for (int i = 0; i < len; i++) { formatters[i].format(event, buffer); } if (replace != null) { // creates temporary objects String str = buffer.toString(); str = replace.format(str); buffer.setLength(0); buffer.append(str); } return buffer; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()); builder.append("[patternSelector="); builder.append(patternSelector); builder.append(", replace="); builder.append(replace); builder.append("]"); return builder.toString(); } } /** * Creates a PatternLayout using the default options. These options include using UTF-8, the default conversion * pattern, exceptions being written, and with ANSI escape codes. * * @return the PatternLayout. * @see #DEFAULT_CONVERSION_PATTERN Default conversion pattern */ public static PatternLayout createDefaultLayout() { return newBuilder().build(); } /** * Creates a PatternLayout using the default options and the given configuration. These options include using UTF-8, * the default conversion pattern, exceptions being written, and with ANSI escape codes. * * @param configuration The Configuration. * * @return the PatternLayout. * @see #DEFAULT_CONVERSION_PATTERN Default conversion pattern */ public static PatternLayout createDefaultLayout(final Configuration configuration) { return newBuilder().withConfiguration(configuration).build(); } /** * Creates a builder for a custom PatternLayout. * * @return a PatternLayout builder. */ @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } /** * Custom PatternLayout builder. Use the {@link PatternLayout#newBuilder() builder factory method} to create this. */ public static class Builder implements org.apache.logging.log4j.core.util.Builder<PatternLayout> { @PluginBuilderAttribute private String pattern = PatternLayout.DEFAULT_CONVERSION_PATTERN; @PluginElement("PatternSelector") private PatternSelector patternSelector = null; @PluginConfiguration private Configuration configuration = null; @PluginElement("Replace") private RegexReplacement regexReplacement = null; // LOG4J2-783 use platform default by default @PluginBuilderAttribute private Charset charset = Charset.defaultCharset(); @PluginBuilderAttribute private boolean alwaysWriteExceptions = true; @PluginBuilderAttribute private boolean noConsoleNoAnsi = false; @PluginBuilderAttribute private String header = null; @PluginBuilderAttribute private String footer = null; private Builder() { } // TODO: move javadocs from PluginFactory to here public Builder withPattern(final String pattern) { this.pattern = pattern; return this; } public Builder withPatternSelector(final PatternSelector patternSelector) { this.patternSelector = patternSelector; return this; } public Builder withConfiguration(final Configuration configuration) { this.configuration = configuration; return this; } public Builder withRegexReplacement(final RegexReplacement regexReplacement) { this.regexReplacement = regexReplacement; return this; } public Builder withCharset(final Charset charset) { // LOG4J2-783 if null, use platform default by default if (charset != null) { this.charset = charset; } return this; } public Builder withAlwaysWriteExceptions(final boolean alwaysWriteExceptions) { this.alwaysWriteExceptions = alwaysWriteExceptions; return this; } public Builder withNoConsoleNoAnsi(final boolean noConsoleNoAnsi) { this.noConsoleNoAnsi = noConsoleNoAnsi; return this; } public Builder withHeader(final String header) { this.header = header; return this; } public Builder withFooter(final String footer) { this.footer = footer; return this; } @Override public PatternLayout build() { // fall back to DefaultConfiguration if (configuration == null) { configuration = new DefaultConfiguration(); } return new PatternLayout(configuration, regexReplacement, pattern, patternSelector, charset, alwaysWriteExceptions, noConsoleNoAnsi, header, footer); } } }
LOG4J2-1291 Fix renamed constant.
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/PatternLayout.java
LOG4J2-1291 Fix renamed constant.
<ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/layout/PatternLayout.java <ide> <ide> @Override <ide> public void encode(final LogEvent event, final ByteBufferDestination destination) { <del> if (!Constants.ENABLE_OBJECT_POOLING || !(eventSerializer instanceof Serializer2)) { <add> if (!Constants.ENABLE_THREADLOCALS || !(eventSerializer instanceof Serializer2)) { <ide> super.encode(event, destination); <ide> return; <ide> }
Java
apache-2.0
5fb0ef2f76b5c0c2a5ded31c6770b84ff916ae00
0
hgani/androlib,hgani/androlib,hgani/androlib
package com.gani.lib.http; import com.gani.lib.logging.GLog; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class GImmutableParams implements Serializable { // NOTE: Value should only be either String or String[] private Map<String, Object> paramMap; protected GImmutableParams() { this(new HashMap<String, Object>()); } protected GImmutableParams(Map<String, Object> initialData) { this.paramMap = new HashMap<>(); paramMap.putAll(initialData); } protected Map<String, Object> getMap() { return paramMap; } protected GParams toMutable() { return new GParams.Default(paramMap); } public String asQueryString() { StringBuilder buffer = new StringBuilder(); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { if (entry.getValue() == null) { GLog.e(UrlUtils.class, "Null param value for key " + entry.getKey()); } else { if (entry.getValue() instanceof String) { buffer.append("&").append(entry.getKey()).append("=").append(UrlUtils.encodeUrl((String) entry.getValue())); } else { // // Note that when the array is empty, this is skipped entirely or else it will pass an array with blank string to the server // for (String value : (String[]) entry.getValue()) { // buffer.append("&").append(entry.getKey()).append("=").append(encodeUrl(value)); // } String[] values = (String[]) entry.getValue(); if (values.length > 0) { for (String value : values) { buffer.append("&").append(entry.getKey()).append("=").append(UrlUtils.encodeUrl(value)); } } else { // This solves 2 issues: // - Allow server implementation to be more predictable as the param key (e.g. params[handshake][key]) always exists. // - Even more important is that if this is the only param key (e.g. params[handshake][key]), not passing this will make the whole param (params[handshake]) to be missing. // // The only drawback is that in Rails, this will be received as `[""]` (an array with one empty string), but this can be consistently solved as it also applies to web form. buffer.append("&").append(entry.getKey()).append("="); } } } } return (buffer.length() == 0)? "" : buffer.substring(1); } @Override public String toString() { return asQueryString(); } // // public static GImmutableParams fromUri(Uri uri) { // GParams params = GParams.create(); // for (String key : uri.getQueryParameterNames()) { // String value = uri.getQueryParameter(key); // params.put(key, value); // } // return params.toImmutable(); // } }
ganilib/src/main/java/com/gani/lib/http/GImmutableParams.java
package com.gani.lib.http; import com.gani.lib.logging.GLog; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class GImmutableParams implements Serializable { // NOTE: Value should only be either String or String[] private Map<String, Object> paramMap; protected GImmutableParams() { this(new HashMap<String, Object>()); } protected GImmutableParams(Map<String, Object> initialData) { this.paramMap = new HashMap<>(); paramMap.putAll(initialData); } protected GParams toMutable() { return new GParams.Default(paramMap); } public String asQueryString() { StringBuilder buffer = new StringBuilder(); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { if (entry.getValue() == null) { GLog.e(UrlUtils.class, "Null param value for key " + entry.getKey()); } else { if (entry.getValue() instanceof String) { buffer.append("&").append(entry.getKey()).append("=").append(UrlUtils.encodeUrl((String) entry.getValue())); } else { // // Note that when the array is empty, this is skipped entirely or else it will pass an array with blank string to the server // for (String value : (String[]) entry.getValue()) { // buffer.append("&").append(entry.getKey()).append("=").append(encodeUrl(value)); // } String[] values = (String[]) entry.getValue(); if (values.length > 0) { for (String value : values) { buffer.append("&").append(entry.getKey()).append("=").append(UrlUtils.encodeUrl(value)); } } else { // This solves 2 issues: // - Allow server implementation to be more predictable as the param key (e.g. params[handshake][key]) always exists. // - Even more important is that if this is the only param key (e.g. params[handshake][key]), not passing this will make the whole param (params[handshake]) to be missing. // // The only drawback is that in Rails, this will be received as `[""]` (an array with one empty string), but this can be consistently solved as it also applies to web form. buffer.append("&").append(entry.getKey()).append("="); } } } } return (buffer.length() == 0)? "" : buffer.substring(1); } @Override public String toString() { return asQueryString(); } // // public static GImmutableParams fromUri(Uri uri) { // GParams params = GParams.create(); // for (String key : uri.getQueryParameterNames()) { // String value = uri.getQueryParameter(key); // params.put(key, value); // } // return params.toImmutable(); // } }
expose params map
ganilib/src/main/java/com/gani/lib/http/GImmutableParams.java
expose params map
<ide><path>anilib/src/main/java/com/gani/lib/http/GImmutableParams.java <ide> protected GImmutableParams(Map<String, Object> initialData) { <ide> this.paramMap = new HashMap<>(); <ide> paramMap.putAll(initialData); <add> } <add> <add> protected Map<String, Object> getMap() { <add> return paramMap; <ide> } <ide> <ide> protected GParams toMutable() {
Java
apache-2.0
62d0cf24e8a33565799bc6994f534945e0b9c275
0
kotucz/ld28,kotucz/ld28
package com.badlogic.gradletest; import com.badlogic.gdx.*; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g3d.*; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HelloApp extends ApplicationAdapter { public static final int RADIUS = 8; public static final int TYPE_BASIC = 0; public static final int TYPE_P = 1; public static final float P_SIZE = 0.5f; private SpriteBatch batch; private Texture img; private OrthographicCamera camera; private Rectangle bucket; private Sound dropSound; private Music rainMusic; private Model model; private ModelInstance instance; private ModelBatch modelBatch; private PerspectiveCamera cam; private Environment environment; private CameraInputController camController; private List<Thing> things = new ArrayList<Thing>(); private Model sphereModel; private ModelInstance sphereInstance; private long frame; private Material thingMaterial; private Texture imgfg; private ShapeRenderer shapeRenderer; private Model projectileModel; float flash = 0; private Vector3 swipe; private HelloApp.Thing firstParticle; @Override public void create() { batch = new SpriteBatch(); modelBatch = new ModelBatch(); shapeRenderer = new ShapeRenderer(); img = new Texture("background.png"); imgfg = new Texture("foreground.png"); // try { // new FreeTypeFontGenerator(Gdx.files.internal("test.fnt")); // } catch(Exception e) { // e.printStackTrace(); // } // Bullet.init(); camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 480); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // cam.position.set(10f, 10f, 10f); cam.position.set(0f, 0f, 15f); cam.lookAt(0, 0, 0); cam.near = 0.1f; cam.far = 300f; cam.update(); bucket = new Rectangle(); bucket.x = 800 / 2 - 64 / 2; bucket.y = 20; bucket.width = 64; bucket.height = 64; // Thing e1 = new Thing(); // things.add(e1); // e1.quat.set(new Vector3(1, 0, 0), 1); // e1.quatv.set(new Vector3(1, 1, 1), 1f); // Thing e = new Thing(); // e.quatv.set(new Vector3(0, 0, 5), 1); // things.add(e); // Thing e3 = new Thing(); // e3.quatv.set(new Vector3(1, 0.1f, 0), 1); // things.add(e3); // Thing e4 = new Thing(); // e4.setDirection(new Vector3(0, 0, 1)); // Vector3 direction = new Vector3(0, 0, 1); // e4.getDirection(direction); // things.add(e4); // load the drop sound effect and the rain background "music" dropSound = Gdx.audio.newSound(Gdx.files.internal("clap.wav")); rainMusic = Gdx.audio.newMusic(Gdx.files.internal("noise.wav")); // can be mp3 environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); ModelBuilder modelBuilder = new ModelBuilder(); thingMaterial = new Material(ColorAttribute.createDiffuse(Color.GREEN)); model = modelBuilder.createBox(1f, 1f, 1f, thingMaterial, VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); instance = new ModelInstance(model); sphereModel = modelBuilder.createSphere(3f, 3f, 3f, 20, 20, // new Material(ColorAttribute.createDiffuse(Color.ORANGE)), new Material(ColorAttribute.createDiffuse(1, 1, 0, 0.5f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); sphereInstance = new ModelInstance(sphereModel); projectileModel = modelBuilder.createSphere(P_SIZE, P_SIZE, P_SIZE, 5, 5, new Material(ColorAttribute.createDiffuse(Color.RED)), // new Material(ColorAttribute.createDiffuse(1, 1, 0, 0.1f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); // start the playback of the background music immediately rainMusic.setLooping(true); rainMusic.play(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer( camController, new InputAdapter() { @Override public boolean keyDown(int keycode) { // dropSound.play(); return super.keyDown(keycode); } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { swipe = new Vector3(screenX, screenY, 0); Vector3 pos1 = new Vector3(0, 0, 1); pos1.prj(cam.view.cpy().inv()); // pos1.prj(cam.view); firstParticle = shootP(pos1, new Vector3()); return super.touchDown(screenX, screenY, pointer, button); } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { swipe.sub(screenX, screenY, 0); swipe.x *= -1; swipe.prj(cam.view.cpy().inv()); // cam.unproject(swipe); swipe.nor(); // shootP(getRandomVector(), getRandomVector()); firstParticle.setDirection(swipe); // float pan = (2f * screenX / Gdx.graphics.getWidth()) - 1; // Gdx.app.log("touch ", "pan " + pan); // dropSound.play((float) screenY / Gdx.graphics.getHeight(), 1, pan); playHitSound(firstParticle.pos, cam); // shootP(new Vector3(0, 0, 1), swipe); return super.touchUp(screenX, screenY, pointer, button); } })); for (int i = 0; i < 10; i++) { Thing t = new Thing(TYPE_BASIC); // t.setDirection(randomize(new Vector3())); randomize(t.pos, 1f); t.adjustToSphere(); things.add(t); } } private Vector3 getRandomVector() { return getRandomVector(1f); } private Vector3 getRandomVector(float m) { return randomize(new Vector3(), m); } @Override public void render() { frame++; // frame = 1; camController.update(); camera.update(); Gdx.gl.glEnable(GL10.GL_BLEND); Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); Gdx.gl.glClearColor(0.5f * flash, 0.7f + 0.5f * flash, 0.6f + 0.5f * flash, 0.0f); // Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT // | GL10.GL_ALPHA_BITS ); if (Gdx.input.isTouched()) { Vector3 touchPos = new Vector3(); touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); camera.unproject(touchPos); bucket.x = touchPos.x - 64 / 2; } if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) bucket.x -= 200 * Gdx.graphics.getDeltaTime(); if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) bucket.x += 200 * Gdx.graphics.getDeltaTime(); if (bucket.x < 0) bucket.x = 0; if (bucket.x > 800 - 64) bucket.x = 800 - 64; drawBackground(); batch.setProjectionMatrix(camera.combined); // batch.begin(); // batch.draw(img, bucket.x, bucket.y); // batch.end(); updateThings(); checkCollicions1(); checkCollisionsP(); // modelBatch.begin(cam); // instance.transform.idt(); // modelBatch.render(instance, environment); // // instance.transform.setToTranslation(1, 0, 0); // modelBatch.render(instance, environment); // // instance.transform.setToTranslation(0, 0, 1); // modelBatch.render(instance, environment); // // instance.transform.setToTranslation(2, 0, 0); // modelBatch.render(instance, environment); // // modelBatch.end(); // instance.materials. drawThings(); drawCore(); drawForeground(); drawShapes(); drawFlashes(flash); flash *= 0.95f; } private void updateThings() { for (Iterator<Thing> iterator = things.iterator(); iterator.hasNext(); ) { Thing thing = iterator.next(); if (thing.dead) { iterator.remove(); } else { thing.update(); } } } private void checkCollicions1() { for (int i = 0; i < things.size(); i++) { Thing thing1 = things.get(i); for (int j = i + 1; j < things.size(); j++) { Thing thing2 = things.get(j); // collision(thing1, thing2); } } } private void checkCollisionsP() { final List<Thing> snapshot = new ArrayList<Thing>(things); for (Thing thingp : snapshot) { if (thingp.type == TYPE_P) { for (Thing thingt : snapshot) { if (thingt.type == TYPE_BASIC) { collisionP(thingp, thingt); } } } } } private void drawThings() { modelBatch.begin(cam); for (Thing thing : things) { // if (frame % 60 == 0) { // thing.modelInstance.materials.get(0).set(ColorAttribute.createDiffuse(new Color(MathUtils.random(), MathUtils.random(), MathUtils.random(), MathUtils.random()))); // } thing.getTransform(thing.modelInstance.transform); modelBatch.render(thing.modelInstance, environment); } modelBatch.end(); } private void drawCore() { // if (frame % 2 == 1) { Gdx.gl.glEnable(GL10.GL_BLEND); modelBatch.begin(cam); sphereInstance.transform.setToScaling(2, 2, 2); modelBatch.render(sphereInstance, environment); modelBatch.end(); Gdx.gl.glDisable(GL10.GL_BLEND); } } private void drawBackground() { batch.begin(); // batch.draw(img, 0, 0); batch.draw(img, 0, 0, 800, 480); batch.end(); } private void drawForeground() { batch.setProjectionMatrix(camera.combined); batch.begin(); // batch. // batch.draw(imgfg, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.draw(imgfg, 0, 0, 800, 480); batch.end(); } private void drawShapes() { float x = 5; float y = 5; float x2 = 10; float y2 = 10; float radius = 3; float width = 3; float height = 3; // shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(cam.combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Line); shapeRenderer.setColor(1, 1, 0, 1); shapeRenderer.line(x, y, x2, y2); shapeRenderer.line(x, y, 1, x2, y2, 1); shapeRenderer.rect(x, y, width, height); shapeRenderer.circle(x, y, radius); shapeRenderer.end(); } private void drawFlashes(float flash) { float x = 5; float y = 5; float x2 = 10; float y2 = 10; float radius = 3; float width = 100; float height = 100; // shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); shapeRenderer.setColor(flash, 1, 0, flash); // shapeRenderer.line(x, y, x2, y2); // shapeRenderer.line(x, y, 1, x2, y2, 1); shapeRenderer.rect(x, y, width, height); shapeRenderer.circle(x, y, radius); shapeRenderer.end(); } private void collision(Thing thing1, Thing thing2) { if (thing1 == thing2) { return; } if (thing1.pos.dst2(thing2.pos) < 1) { Vector3 pos = new Vector3(thing1.pos); // cam.project(pos); // pos.prj(cam.combined); pos.prj(cam.view); // float pan = (2f * pos.x / Gdx.graphics.getWidth()) - 1; float volume = (float) Math.exp(0.1f * pos.z); Gdx.app.log("touch ", "collision " + pos + " vol " + volume); dropSound.play(volume, 1, pos.x); thing1.setDirection(getRandomVector()); thing2.setDirection(getRandomVector()); } } /** * @param thingp projectile * @param thingt target - what is being hit */ private void collisionP(Thing thingp, Thing thingt) { assert thingp.type == TYPE_P; assert thingt.type == TYPE_BASIC; if (thingp.pos.dst2(thingt.pos) < 1) { playHitSound(thingt.pos, cam); thingp.dead = true; thingt.dead = true; flash += 1f; Vector3 direction = thingp.getDirection(new Vector3()); for (int i = 0; i < 3; i++) { shootP(thingt.pos, getRandomVector(1f).add(direction)); } } } private Thing shootP(Vector3 from, Vector3 direction) { Thing t = new Thing(TYPE_P); // t.setDirection(randomize(new Vector3())); t.pos.set(from); t.adjustToSphere(); t.setDirection(direction); things.add(t); return t; } /** * Plays sound in world depending on where camera is * * @param worldPos * @param povCam */ private void playHitSound(Vector3 worldPos, PerspectiveCamera povCam) { Vector3 camPos = new Vector3(worldPos); // cam.project(pos); // pos.prj(cam.combined); // position in camera coordinates camPos.prj(povCam.view); // float pan = (2f * pos.x / Gdx.graphics.getWidth()) - 1; float volume = (float) Math.exp(0.1f * camPos.z); Gdx.app.log("touch ", "collision " + camPos + " vol " + volume); dropSound.play(volume, 1, camPos.x); } private Vector3 randomize(Vector3 random, float m) { return random.set(MathUtils.random(-m, m), MathUtils.random(-m, m), MathUtils.random(-m, m)); } class Thing { final Vector3 pos = new Vector3(5, 0, 0); final Quaternion quat = new Quaternion(); final Quaternion quatv = new Quaternion(); final int type; boolean dead = false; ModelInstance modelInstance; Thing(int type) { this.type = type; switch (type) { case TYPE_BASIC: modelInstance = new ModelInstance(model); break; case TYPE_P: modelInstance = new ModelInstance(projectileModel); break; } } public void update() { Quaternion q = new Quaternion(); q.slerp(quatv, 1f); quat.mul(q); pos.mul(q); } private void getTransform(Matrix4 transform) { transform.idt(); // transform.translate(5, 0, 0); transform.setTranslation(pos); // transform.setTranslation(pos) ; // transform.translate(pos); transform.rotate(quat); // Vector3 vector3 = new Vector3(); // thing.quat.getAxisAngle(vector3); } /** * Sets absolute direction of movement * * @param direction */ public void setDirection(Vector3 direction) { Vector3 axis = new Vector3(pos); axis.crs(direction); float speed = direction.len(); quatv.set(axis, speed); } /** * Absolute direction of movement * * @param direction */ public Vector3 getDirection(Vector3 direction) { // predict move to find the direction return direction.set(pos).mul(quatv).sub(pos); } void adjustToSphere() { pos.nor().scl(RADIUS); } } }
core/src/main/java/com/badlogic/gradletest/HelloApp.java
package com.badlogic.gradletest; import com.badlogic.gdx.*; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g3d.*; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HelloApp extends ApplicationAdapter { public static final int RADIUS = 8; public static final int TYPE_BASIC = 0; public static final int TYPE_P = 1; public static final float P_SIZE = 0.5f; private SpriteBatch batch; private Texture img; private OrthographicCamera camera; private Rectangle bucket; private Sound dropSound; private Music rainMusic; private Model model; private ModelInstance instance; private ModelBatch modelBatch; private PerspectiveCamera cam; private Environment environment; private CameraInputController camController; private List<Thing> things = new ArrayList<Thing>(); private Model sphereModel; private ModelInstance sphereInstance; private long frame; private Material thingMaterial; private Texture imgfg; private ShapeRenderer shapeRenderer; private Model projectileModel; float flash = 0; private Vector3 swipe; private HelloApp.Thing firstParticle; @Override public void create() { batch = new SpriteBatch(); modelBatch = new ModelBatch(); shapeRenderer = new ShapeRenderer(); img = new Texture("background.png"); imgfg = new Texture("foreground.png"); // try { // new FreeTypeFontGenerator(Gdx.files.internal("test.fnt")); // } catch(Exception e) { // e.printStackTrace(); // } // Bullet.init(); camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 480); cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // cam.position.set(10f, 10f, 10f); cam.position.set(0f, 0f, 15f); cam.lookAt(0, 0, 0); cam.near = 0.1f; cam.far = 300f; cam.update(); bucket = new Rectangle(); bucket.x = 800 / 2 - 64 / 2; bucket.y = 20; bucket.width = 64; bucket.height = 64; // Thing e1 = new Thing(); // things.add(e1); // e1.quat.set(new Vector3(1, 0, 0), 1); // e1.quatv.set(new Vector3(1, 1, 1), 1f); // Thing e = new Thing(); // e.quatv.set(new Vector3(0, 0, 5), 1); // things.add(e); // Thing e3 = new Thing(); // e3.quatv.set(new Vector3(1, 0.1f, 0), 1); // things.add(e3); // Thing e4 = new Thing(); // e4.setDirection(new Vector3(0, 0, 1)); // Vector3 direction = new Vector3(0, 0, 1); // e4.getDirection(direction); // things.add(e4); // load the drop sound effect and the rain background "music" dropSound = Gdx.audio.newSound(Gdx.files.internal("clap.wav")); rainMusic = Gdx.audio.newMusic(Gdx.files.internal("noise.wav")); // can be mp3 environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f)); environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f)); ModelBuilder modelBuilder = new ModelBuilder(); thingMaterial = new Material(ColorAttribute.createDiffuse(Color.GREEN)); model = modelBuilder.createBox(1f, 1f, 1f, thingMaterial, VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); instance = new ModelInstance(model); sphereModel = modelBuilder.createSphere(3f, 3f, 3f, 20, 20, // new Material(ColorAttribute.createDiffuse(Color.ORANGE)), new Material(ColorAttribute.createDiffuse(1, 1, 0, 0.5f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); sphereInstance = new ModelInstance(sphereModel); projectileModel = modelBuilder.createSphere(P_SIZE, P_SIZE, P_SIZE, 5, 5, new Material(ColorAttribute.createDiffuse(Color.RED)), // new Material(ColorAttribute.createDiffuse(1, 1, 0, 0.1f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); // start the playback of the background music immediately rainMusic.setLooping(true); rainMusic.play(); camController = new CameraInputController(cam); Gdx.input.setInputProcessor(new InputMultiplexer( camController, new InputAdapter() { @Override public boolean keyDown(int keycode) { // dropSound.play(); return super.keyDown(keycode); } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { swipe = new Vector3(screenX, screenY, 0); Vector3 pos1 = new Vector3(0, 0, 1); pos1.prj(cam.view.cpy().inv()); // pos1.prj(cam.view); firstParticle = shootP(pos1, new Vector3()); return super.touchDown(screenX, screenY, pointer, button); } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { swipe.sub(screenX, screenY, 0); swipe.x *= -1; swipe.prj(cam.view.cpy().inv()); // cam.unproject(swipe); swipe.nor(); // shootP(getRandomVector(), getRandomVector()); firstParticle.setDirection(swipe); // float pan = (2f * screenX / Gdx.graphics.getWidth()) - 1; // Gdx.app.log("touch ", "pan " + pan); // dropSound.play((float) screenY / Gdx.graphics.getHeight(), 1, pan); playHitSound(firstParticle.pos, cam); // shootP(new Vector3(0, 0, 1), swipe); return super.touchUp(screenX, screenY, pointer, button); } })); for (int i = 0; i < 10; i++) { Thing t = new Thing(TYPE_BASIC); // t.setDirection(randomize(new Vector3())); randomize(t.pos); t.adjustToSphere(); things.add(t); } } private Vector3 getRandomVector() { return randomize(new Vector3()); } @Override public void render() { frame++; // frame = 1; camController.update(); camera.update(); Gdx.gl.glEnable(GL10.GL_BLEND); Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); Gdx.gl.glClearColor(0.5f * flash, 0.7f + 0.5f * flash, 0.6f + 0.5f * flash, 0.0f); // Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT // | GL10.GL_ALPHA_BITS ); if (Gdx.input.isTouched()) { Vector3 touchPos = new Vector3(); touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0); camera.unproject(touchPos); bucket.x = touchPos.x - 64 / 2; } if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) bucket.x -= 200 * Gdx.graphics.getDeltaTime(); if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) bucket.x += 200 * Gdx.graphics.getDeltaTime(); if (bucket.x < 0) bucket.x = 0; if (bucket.x > 800 - 64) bucket.x = 800 - 64; drawBackground(); batch.setProjectionMatrix(camera.combined); batch.begin(); batch.draw(img, bucket.x, bucket.y); batch.end(); updateThings(); checkCollicions1(); checkCollisionsP(); modelBatch.begin(cam); instance.transform.idt(); modelBatch.render(instance, environment); instance.transform.setToTranslation(1, 0, 0); modelBatch.render(instance, environment); instance.transform.setToTranslation(0, 0, 1); modelBatch.render(instance, environment); instance.transform.setToTranslation(2, 0, 0); modelBatch.render(instance, environment); modelBatch.end(); // instance.materials. drawThings(); drawCore(); drawForeground(); drawShapes(); drawFlashes(flash); flash *= 0.95f; } private void updateThings() { for (Iterator<Thing> iterator = things.iterator(); iterator.hasNext(); ) { Thing thing = iterator.next(); if (thing.dead) { iterator.remove(); } else { thing.update(); } } } private void checkCollicions1() { for (int i = 0; i < things.size(); i++) { Thing thing1 = things.get(i); for (int j = i + 1; j < things.size(); j++) { Thing thing2 = things.get(j); // collision(thing1, thing2); } } } private void checkCollisionsP() { final List<Thing> snapshot = new ArrayList<Thing>(things); for (Thing thingp : snapshot) { if (thingp.type == TYPE_P) { for (Thing thingt : snapshot) { if (thingt.type == TYPE_BASIC) { collisionP(thingp, thingt); } } } } } private void drawThings() { modelBatch.begin(cam); for (Thing thing : things) { // if (frame % 60 == 0) { // thing.modelInstance.materials.get(0).set(ColorAttribute.createDiffuse(new Color(MathUtils.random(), MathUtils.random(), MathUtils.random(), MathUtils.random()))); // } thing.getTransform(thing.modelInstance.transform); modelBatch.render(thing.modelInstance, environment); } modelBatch.end(); } private void drawCore() { // if (frame % 2 == 1) { Gdx.gl.glEnable(GL10.GL_BLEND); modelBatch.begin(cam); sphereInstance.transform.setToScaling(2, 2, 2); modelBatch.render(sphereInstance, environment); modelBatch.end(); Gdx.gl.glDisable(GL10.GL_BLEND); } } private void drawBackground() { batch.begin(); // batch.draw(img, 0, 0); batch.draw(img, 0, 0, 800, 480); batch.end(); } private void drawForeground() { batch.setProjectionMatrix(camera.combined); batch.begin(); // batch. // batch.draw(imgfg, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.draw(imgfg, 0, 0, 800, 480); batch.end(); } private void drawShapes() { float x = 5; float y = 5; float x2 = 10; float y2 = 10; float radius = 3; float width = 3; float height = 3; // shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(cam.combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Line); shapeRenderer.setColor(1, 1, 0, 1); shapeRenderer.line(x, y, x2, y2); shapeRenderer.line(x, y, 1, x2, y2, 1); shapeRenderer.rect(x, y, width, height); shapeRenderer.circle(x, y, radius); shapeRenderer.end(); } private void drawFlashes(float flash) { float x = 5; float y = 5; float x2 = 10; float y2 = 10; float radius = 3; float width = 100; float height = 100; // shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(camera.combined); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); shapeRenderer.setColor(flash, 1, 0, flash); // shapeRenderer.line(x, y, x2, y2); // shapeRenderer.line(x, y, 1, x2, y2, 1); shapeRenderer.rect(x, y, width, height); shapeRenderer.circle(x, y, radius); shapeRenderer.end(); } private void collision(Thing thing1, Thing thing2) { if (thing1 == thing2) { return; } if (thing1.pos.dst2(thing2.pos) < 1) { Vector3 pos = new Vector3(thing1.pos); // cam.project(pos); // pos.prj(cam.combined); pos.prj(cam.view); // float pan = (2f * pos.x / Gdx.graphics.getWidth()) - 1; float volume = (float) Math.exp(0.1f * pos.z); Gdx.app.log("touch ", "collision " + pos + " vol " + volume); dropSound.play(volume, 1, pos.x); thing1.setDirection(getRandomVector()); thing2.setDirection(getRandomVector()); } } /** * @param thingp projectile * @param thingt target - what is being hit */ private void collisionP(Thing thingp, Thing thingt) { assert thingp.type == TYPE_P; assert thingt.type == TYPE_BASIC; if (thingp.pos.dst2(thingt.pos) < 1) { playHitSound(thingt.pos, cam); thingp.dead = true; thingt.dead = true; flash += 1f; for (int i = 0; i < 3; i++) { shootP(thingt.pos, thingt.getDirection(new Vector3()).add(getRandomVector())); } } } private Thing shootP(Vector3 from, Vector3 direction) { Thing t = new Thing(TYPE_P); // t.setDirection(randomize(new Vector3())); t.pos.set(from); t.adjustToSphere(); t.setDirection(direction); things.add(t); return t; } /** * Plays sound in world depending on where camera is * * @param worldPos * @param povCam */ private void playHitSound(Vector3 worldPos, PerspectiveCamera povCam) { Vector3 camPos = new Vector3(worldPos); // cam.project(pos); // pos.prj(cam.combined); // position in camera coordinates camPos.prj(povCam.view); // float pan = (2f * pos.x / Gdx.graphics.getWidth()) - 1; float volume = (float) Math.exp(0.1f * camPos.z); Gdx.app.log("touch ", "collision " + camPos + " vol " + volume); dropSound.play(volume, 1, camPos.x); } private Vector3 randomize(Vector3 random) { return random.set(MathUtils.random(-1f, 1f), MathUtils.random(-1f, 1f), MathUtils.random(-1f, 1f)); } class Thing { final Vector3 pos = new Vector3(5, 0, 0); final Quaternion quat = new Quaternion(); final Quaternion quatv = new Quaternion(); final int type; boolean dead = false; ModelInstance modelInstance; Thing(int type) { this.type = type; switch (type) { case TYPE_BASIC: modelInstance = new ModelInstance(model); break; case TYPE_P: modelInstance = new ModelInstance(projectileModel); break; } } public void update() { Quaternion q = new Quaternion(); q.slerp(quatv, 1f); quat.mul(q); pos.mul(q); } private void getTransform(Matrix4 transform) { transform.idt(); // transform.translate(5, 0, 0); transform.setTranslation(pos); // transform.setTranslation(pos) ; // transform.translate(pos); transform.rotate(quat); // Vector3 vector3 = new Vector3(); // thing.quat.getAxisAngle(vector3); } /** * Sets absolute direction of movement * * @param direction */ public void setDirection(Vector3 direction) { Vector3 axis = new Vector3(pos); axis.crs(direction); float speed = direction.len(); quatv.set(axis, speed); } /** * Absolute direction of movement * * @param direction */ public Vector3 getDirection(Vector3 direction) { // predict move to find the direction return direction.set(pos).mul(quatv).sub(pos); } void adjustToSphere() { pos.nor().scl(RADIUS); } } }
hidden some useless graphics, fixed collision exit direction
core/src/main/java/com/badlogic/gradletest/HelloApp.java
hidden some useless graphics, fixed collision exit direction
<ide><path>ore/src/main/java/com/badlogic/gradletest/HelloApp.java <ide> for (int i = 0; i < 10; i++) { <ide> Thing t = new Thing(TYPE_BASIC); <ide> // t.setDirection(randomize(new Vector3())); <del> randomize(t.pos); <add> randomize(t.pos, 1f); <ide> t.adjustToSphere(); <ide> things.add(t); <ide> } <ide> } <ide> <ide> private Vector3 getRandomVector() { <del> return randomize(new Vector3()); <add> return getRandomVector(1f); <add> } <add> <add> private Vector3 getRandomVector(float m) { <add> return randomize(new Vector3(), m); <ide> } <ide> <ide> @Override <ide> drawBackground(); <ide> <ide> batch.setProjectionMatrix(camera.combined); <del> batch.begin(); <del> batch.draw(img, bucket.x, bucket.y); <del> batch.end(); <add>// batch.begin(); <add>// batch.draw(img, bucket.x, bucket.y); <add>// batch.end(); <ide> <ide> updateThings(); <ide> <ide> <ide> checkCollisionsP(); <ide> <del> modelBatch.begin(cam); <del> <del> instance.transform.idt(); <del> modelBatch.render(instance, environment); <del> <del> instance.transform.setToTranslation(1, 0, 0); <del> modelBatch.render(instance, environment); <del> <del> instance.transform.setToTranslation(0, 0, 1); <del> modelBatch.render(instance, environment); <del> <del> instance.transform.setToTranslation(2, 0, 0); <del> modelBatch.render(instance, environment); <del> <del> modelBatch.end(); <add>// modelBatch.begin(cam); <add> <add>// instance.transform.idt(); <add>// modelBatch.render(instance, environment); <add>// <add>// instance.transform.setToTranslation(1, 0, 0); <add>// modelBatch.render(instance, environment); <add>// <add>// instance.transform.setToTranslation(0, 0, 1); <add>// modelBatch.render(instance, environment); <add>// <add>// instance.transform.setToTranslation(2, 0, 0); <add>// modelBatch.render(instance, environment); <add>// <add>// modelBatch.end(); <ide> <ide> // instance.materials. <ide> <ide> <ide> flash += 1f; <ide> <add> Vector3 direction = thingp.getDirection(new Vector3()); <add> <ide> for (int i = 0; i < 3; i++) { <del> shootP(thingt.pos, thingt.getDirection(new Vector3()).add(getRandomVector())); <add> shootP(thingt.pos, getRandomVector(1f).add(direction)); <ide> } <ide> <ide> } <ide> dropSound.play(volume, 1, camPos.x); <ide> } <ide> <del> private Vector3 randomize(Vector3 random) { <del> return random.set(MathUtils.random(-1f, 1f), MathUtils.random(-1f, 1f), MathUtils.random(-1f, 1f)); <add> private Vector3 randomize(Vector3 random, float m) { <add> return random.set(MathUtils.random(-m, m), MathUtils.random(-m, m), MathUtils.random(-m, m)); <ide> } <ide> <ide> class Thing {
Java
bsd-3-clause
9832b47d44199f19e37373556d8f5c01c1757581
0
Team-2502/RobotCode2014
package com.team2502.subsystems; import com.team2502.RobotMap; import com.team2502.black_box.BlackBoxProtocol; import edu.wpi.first.wpilibj.AnalogChannel; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.can.CANTimeoutException; import edu.wpi.first.wpilibj.command.Subsystem; /** * @author Jackson Turner * */ public class ShooterSubsystem extends Subsystem { private static final double LOADED_THRESHOLD = 0; // Analog trigger threshold private static final double WINCH_SPEED = 1; // Winch speed (between -1 and 1) private CANJaguar winch; private Solenoid latch; private AnalogChannel loadedSensor; private Compressor compressor; private double topWinchPosition = 1; private double bottomWinchPosition = 0; private double targetPosition; public ShooterSubsystem() { initalizeCANJaguar(); latch = new Solenoid(RobotMap.SHOOTER_LATCH); loadedSensor = new AnalogChannel(RobotMap.SHOOTER_LOADED_SENSOR); compressor = new Compressor(RobotMap.COMPRESSOR_SWITCH, RobotMap.COMPRESSOR_RELAY); compressor.start(); } private void initalizeCANJaguar() { boolean retry = true; while (retry) { try { winch = new CANJaguar(RobotMap.SHOOTER_WINCH_CAN_PORT); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } @Override protected void initDefaultCommand() { } @Deprecated public void moveToPosition(double position) { targetPosition = position; if (targetPosition < getWinchProgress()) moveWinchDown(); else if (targetPosition > getWinchProgress()) moveWinchUp(); else stopWinch(); } public void moveWinchDown() { boolean retry = true; while (retry) { try { winch.setX(-WINCH_SPEED); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public void moveWinchUp() { boolean retry = true; while (retry) { try { winch.setX(WINCH_SPEED); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public void stopWinch() { boolean retry = true; while (retry) { try { winch.setX(0); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public boolean isDown() { boolean retry = true; while (retry) { try { return !winch.getReverseLimitOK(); } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } return false; } public boolean isUp() { boolean retry = true; while (retry) { try { return !winch.getForwardLimitOK(); } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } return false; } public boolean isLoaded() { return (loadedSensor.getVoltage() > LOADED_THRESHOLD); } public boolean isLatched() { return latch.get(); } public double getWinchProgress() { boolean retry = true; while (retry) { try { return 1 - (winch.getPosition() - bottomWinchPosition) / topWinchPosition; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } return 0; } public void activateLatch() { latch.set(true); } public void deactivateLatch() { latch.set(false); } public void setCurrentEncoderPositionAsBottom() { boolean retry = true; while (retry) { try { bottomWinchPosition = winch.getPosition(); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public void setCurrentEncoderPositionAsTop() { boolean retry = true; while (retry) { try { topWinchPosition = winch.getPosition(); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } }
src/com/team2502/subsystems/ShooterSubsystem.java
package com.team2502.subsystems; import com.team2502.RobotMap; import com.team2502.black_box.BlackBoxProtocol; import edu.wpi.first.wpilibj.AnalogChannel; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.CANJaguar; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.can.CANTimeoutException; import edu.wpi.first.wpilibj.command.Subsystem; /** * @author Jackson Turner * */ public class ShooterSubsystem extends Subsystem { private static final double LOADED_THRESHOLD = 0; // Analog trigger threshold private static final double WINCH_SPEED = 1; // Winch speed (between -1 and 1) private CANJaguar winch; private Solenoid latch; private AnalogChannel loadedSensor; private Compressor compressor; private double topWinchPosition = 1; private double bottomWinchPosition = 0; private double targetPosition; public ShooterSubsystem() { initalizeCAMJaguar(); latch = new Solenoid(RobotMap.SHOOTER_LATCH); loadedSensor = new AnalogChannel(RobotMap.SHOOTER_LOADED_SENSOR); compressor = new Compressor(RobotMap.COMPRESSOR_SWITCH, RobotMap.COMPRESSOR_RELAY); compressor.start(); } private void initalizeCAMJaguar() { boolean retry = true; while (retry) { try { winch = new CANJaguar(RobotMap.SHOOTER_WINCH_CAN_PORT); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); retry = true; } } } @Override protected void initDefaultCommand() { } @Deprecated public void moveToPosition(double position) { targetPosition = position; if (targetPosition < getWinchProgress()) moveWinchDown(); else if (targetPosition > getWinchProgress()) moveWinchUp(); else stopWinch(); } public void moveWinchDown() { boolean retry = true; while (retry) { try { winch.setX(-WINCH_SPEED); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public void moveWinchUp() { boolean retry = true; while (retry) { try { winch.setX(WINCH_SPEED); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public void stopWinch() { boolean retry = true; while (retry) { try { winch.setX(0); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public boolean isDown() { boolean retry = true; while (retry) { try { return !winch.getReverseLimitOK(); } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } return false; } public boolean isUp() { boolean retry = true; while (retry) { try { return !winch.getForwardLimitOK(); } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } return false; } public boolean isLoaded() { return (loadedSensor.getVoltage() > LOADED_THRESHOLD); } public boolean isLatched() { return latch.get(); } public double getWinchProgress() { boolean retry = true; while (retry) { try { return 1 - (winch.getPosition() - bottomWinchPosition) / topWinchPosition; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } return 0; } public void activateLatch() { latch.set(true); } public void deactivateLatch() { latch.set(false); } public void setCurrentEncoderPositionAsBottom() { boolean retry = true; while (retry) { try { bottomWinchPosition = winch.getPosition(); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } public void setCurrentEncoderPositionAsTop() { boolean retry = true; while (retry) { try { topWinchPosition = winch.getPosition(); retry = false; } catch (CANTimeoutException e){ BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); } } } }
Fixed typo and removed unnecessary code
src/com/team2502/subsystems/ShooterSubsystem.java
Fixed typo and removed unnecessary code
<ide><path>rc/com/team2502/subsystems/ShooterSubsystem.java <ide> private double targetPosition; <ide> <ide> public ShooterSubsystem() { <del> initalizeCAMJaguar(); <add> initalizeCANJaguar(); <ide> latch = new Solenoid(RobotMap.SHOOTER_LATCH); <ide> loadedSensor = new AnalogChannel(RobotMap.SHOOTER_LOADED_SENSOR); <ide> compressor = new Compressor(RobotMap.COMPRESSOR_SWITCH, RobotMap.COMPRESSOR_RELAY); <ide> compressor.start(); <ide> } <ide> <del> private void initalizeCAMJaguar() { <add> private void initalizeCANJaguar() { <ide> boolean retry = true; <ide> while (retry) { <ide> try { <ide> retry = false; <ide> } catch (CANTimeoutException e){ <ide> BlackBoxProtocol.log("CAN-Jaguar initilization failed: " + e.toString()); <del> retry = true; <ide> } <ide> } <ide> }
JavaScript
mit
761f2888c440ac71d973bb7463b9e49dbce00d72
0
aesprice/personifi
angular.module('myApp.main.avatar', ['ui.router']) .config(function ($stateProvider) { $stateProvider .state('myApp.main.avatar', { url: '/avatar', templateUrl: 'avatar/avatar.tpl.html', controller: 'AvatarController' }); }) .factory('AvatarFactory', function($http){ var methods = {}; methods.sendMood = function(userMood, callback){ var data = {userMood: userMood}; $http.post('/mood', data) .success(function(data){ callback(data); }) .error(function(){ console.log('no mood from server :['); }); }; return methods; }) .controller('AvatarController', function ($scope, AvatarFactory) { $scope.sendMood = AvatarFactory.sendMood; $scope.serverMood; $scope.emoteStyle = {}; $scope.sendMood($scope.$parent.mood, function(data){ $scope.serverMood = data.serverMood; var y = Math.floor(191 * $scope.serverMood) + 64; // will be used for red and green, making yellow var b = Math.floor(32 * (1 - $scope.serverMood)) + 128; $scope.emoteStyle = { backgroundColor: 'rgb(' + y + ',' + y + ',' + b + ')' }; }); });
client/avatar/avatar.js
angular.module('myApp.main.avatar', ['ui.router']) .config(function ($stateProvider) { $stateProvider .state('myApp.main.avatar', { url: '/avatar', templateUrl: 'avatar/avatar.tpl.html', controller: 'AvatarController' }); }) .factory('AvatarFactory', function($http){ var methods = {}; methods.sendMood = function(userMood, callback){ var data = {userMood: userMood}; $http.post('/mood', data) .success(function(data){ callback(data); }) .error(function(){ console.log('no mood from server :['); }); }; return methods; }) .controller('AvatarController', function ($scope, AvatarFactory) { $scope.sendMood = AvatarFactory.sendMood; $scope.serverMood; $scope.emoteStyle = {}; $scope.sendMood($scope.$parent.mood, function(data){ $scope.serverMood = data.serverMood; $scope.emoteStyle = { backgroundColor: 'rgb(' + Math.floor(255 * (1 - $scope.serverMood)) + ',128,' + Math.floor(255 * $scope.serverMood) + ')' }; }); });
Revised color scheme and parsing
client/avatar/avatar.js
Revised color scheme and parsing
<ide><path>lient/avatar/avatar.js <ide> $scope.emoteStyle = {}; <ide> $scope.sendMood($scope.$parent.mood, function(data){ <ide> $scope.serverMood = data.serverMood; <add> var y = Math.floor(191 * $scope.serverMood) + 64; // will be used for red and green, making yellow <add> var b = Math.floor(32 * (1 - $scope.serverMood)) + 128; <ide> $scope.emoteStyle = { <del> backgroundColor: 'rgb(' + Math.floor(255 * (1 - $scope.serverMood)) + ',128,' + Math.floor(255 * $scope.serverMood) + ')' <add> backgroundColor: 'rgb(' + y + ',' + y + ',' + b + ')' <ide> }; <ide> }); <ide> });
Java
apache-2.0
5268977b0cac428fd3dd229716b865a58faff4ca
0
whitesource/agents,whitesource/agents
/** * Copyright (C) 2017 White Source Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.whitesource.agent.hash; import org.apache.commons.lang.builder.CompareToBuilder; import java.util.Objects; /** * This object holds the various hashes calculated for a single file. * * @author tom.shapira */ public class HashCalculationResult implements Comparable { /* --- Members --- */ private String fullHash; private String mostSigBitsHash; private String leastSigBitsHash; /* --- Constructors --- */ public HashCalculationResult(String fullHash) { this.fullHash = fullHash; } public HashCalculationResult(String fullHash, String mostSigBitsHash, String leastSigBitsHash) { this.fullHash = fullHash; this.mostSigBitsHash = mostSigBitsHash; this.leastSigBitsHash = leastSigBitsHash; } /* --- Overridden --- */ @Override public int compareTo(Object o) { HashCalculationResult myClass = (HashCalculationResult) o; return new CompareToBuilder() .append(this.fullHash, myClass.fullHash) .append(this.mostSigBitsHash, myClass.mostSigBitsHash) .append(this.leastSigBitsHash, myClass.leastSigBitsHash) .toComparison(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof HashCalculationResult)) return false; HashCalculationResult that = (HashCalculationResult) o; return Objects.equals(fullHash, that.fullHash) && Objects.equals(mostSigBitsHash, that.mostSigBitsHash) && Objects.equals(leastSigBitsHash, that.leastSigBitsHash); } @Override public int hashCode() { return Objects.hash(fullHash, mostSigBitsHash, leastSigBitsHash); } /* --- Getters / Setters --- */ public String getFullHash() { return fullHash; } public void setFullHash(String fullHash) { this.fullHash = fullHash; } public String getMostSigBitsHash() { return mostSigBitsHash; } public void setMostSigBitsHash(String mostSigBitsHash) { this.mostSigBitsHash = mostSigBitsHash; } public String getLeastSigBitsHash() { return leastSigBitsHash; } public void setLeastSigBitsHash(String leastSigBitsHash) { this.leastSigBitsHash = leastSigBitsHash; } }
wss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/HashCalculationResult.java
/** * Copyright (C) 2017 White Source Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.whitesource.agent.hash; import org.apache.commons.lang.builder.CompareToBuilder; /** * This object holds the various hashes calculated for a single file. * * @author tom.shapira */ public class HashCalculationResult implements Comparable { /* --- Members --- */ private String fullHash; private String mostSigBitsHash; private String leastSigBitsHash; /* --- Constructors --- */ public HashCalculationResult(String fullHash) { this.fullHash = fullHash; } public HashCalculationResult(String fullHash, String mostSigBitsHash, String leastSigBitsHash) { this.fullHash = fullHash; this.mostSigBitsHash = mostSigBitsHash; this.leastSigBitsHash = leastSigBitsHash; } /* --- Overridden --- */ @Override public int compareTo(Object o) { HashCalculationResult myClass = (HashCalculationResult) o; return new CompareToBuilder() .append(this.fullHash, myClass.fullHash) .append(this.mostSigBitsHash, myClass.mostSigBitsHash) .append(this.leastSigBitsHash, myClass.leastSigBitsHash) .toComparison(); } /* --- Getters / Setters --- */ public String getFullHash() { return fullHash; } public void setFullHash(String fullHash) { this.fullHash = fullHash; } public String getMostSigBitsHash() { return mostSigBitsHash; } public void setMostSigBitsHash(String mostSigBitsHash) { this.mostSigBitsHash = mostSigBitsHash; } public String getLeastSigBitsHash() { return leastSigBitsHash; } public void setLeastSigBitsHash(String leastSigBitsHash) { this.leastSigBitsHash = leastSigBitsHash; } }
Add equals and hashCode to HashCalculationResult
wss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/HashCalculationResult.java
Add equals and hashCode to HashCalculationResult
<ide><path>ss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/HashCalculationResult.java <ide> package org.whitesource.agent.hash; <ide> <ide> import org.apache.commons.lang.builder.CompareToBuilder; <add> <add>import java.util.Objects; <ide> <ide> /** <ide> * This object holds the various hashes calculated for a single file. <ide> .toComparison(); <ide> } <ide> <add> @Override <add> public boolean equals(Object o) { <add> if (this == o) return true; <add> if (!(o instanceof HashCalculationResult)) return false; <add> HashCalculationResult that = (HashCalculationResult) o; <add> return Objects.equals(fullHash, that.fullHash) && <add> Objects.equals(mostSigBitsHash, that.mostSigBitsHash) && <add> Objects.equals(leastSigBitsHash, that.leastSigBitsHash); <add> } <add> <add> @Override <add> public int hashCode() { <add> return Objects.hash(fullHash, mostSigBitsHash, leastSigBitsHash); <add> } <add> <ide> /* --- Getters / Setters --- */ <ide> <ide> public String getFullHash() {
Java
apache-2.0
54cb7bea25bf7ef68a0bef4f4162285db7b3a5c6
0
debezium/debezium,debezium/debezium,debezium/debezium,debezium/debezium
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.oracle.logminer.processor; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.DebeziumException; import io.debezium.connector.oracle.BlobChunkList; import io.debezium.connector.oracle.OracleConnectorConfig; import io.debezium.connector.oracle.OracleDatabaseSchema; import io.debezium.connector.oracle.OracleValueConverters; import io.debezium.connector.oracle.logminer.LogMinerHelper; import io.debezium.connector.oracle.logminer.events.DmlEvent; import io.debezium.connector.oracle.logminer.events.EventType; import io.debezium.connector.oracle.logminer.events.LobWriteEvent; import io.debezium.connector.oracle.logminer.events.LogMinerEvent; import io.debezium.connector.oracle.logminer.events.SelectLobLocatorEvent; import io.debezium.function.BlockingConsumer; import io.debezium.relational.Table; /** * A consumer of transaction events at commit time that is capable of inspecting the event stream, * merging events that should be merged when LOB support is enabled, and then delegating the final * stream of events to a delegate consumer. * * When a table has a LOB field, Oracle LogMiner often supplies us with synthetic events that deal * with sub-tasks that occur in the database as a result of writing LOB data to the database. We * would prefer to emit these synthetic events as a part of the overall logical event, whether that * is an insert or update. * * An example of a scenario would be the following logical user action: * INSERT INTO my_table (id,lob_field) values (1, 'some clob data'); * * Oracle LogMiner provides the connector with the following events: * INSERT INTO my_table (id,lob_field) values (1, EMPTY_CLOB()); * UPDATE my_table SET lob_field = 'some clob data' where id = 1; * * When LOB support is enabled, this consumer implementation will detect that the update is an * event that should be merged with the previous insert event so that the emitted change events * consists a single logical change, an insert that have an after section like: * * <pre> * "after": { * "id": 1, * "lob_field": "some clob data" * } * </pre> * * When LOB support isn't enabled, events are simply passed through to the delegate and no event * inspection, merging, or buffering occurs. * * @author Chris Cranford */ public class TransactionCommitConsumer implements AutoCloseable, BlockingConsumer<LogMinerEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(TransactionCommitConsumer.class); private final BlockingConsumer<LogMinerEvent> delegate; private final OracleConnectorConfig connectorConfig; private final OracleDatabaseSchema schema; private final List<String> lobWriteData; /** * Describes the current LOB event buffering state, whether we're working on a series of * {@code LOB_WRITE} events, {@code LOB_ERASE} events, or any other type of event that * does not require special handling. */ enum LobState { WRITE, ERASE, OTHER }; private LogMinerEvent lastEvent; private SelectLobLocatorEvent lastSelectLobLocatorEvent; private LobState lobState; public TransactionCommitConsumer(BlockingConsumer<LogMinerEvent> delegate, OracleConnectorConfig connectorConfig, OracleDatabaseSchema schema) { this.delegate = delegate; this.lobState = LobState.OTHER; this.lobWriteData = new ArrayList<>(); this.connectorConfig = connectorConfig; this.schema = schema; } @Override public void close() throws InterruptedException { if (lastEvent != null) { if (!lobWriteData.isEmpty()) { mergeLobWriteData(lastEvent); } dispatchChangeEvent(lastEvent); } } @Override public void accept(LogMinerEvent event) throws InterruptedException { if (!connectorConfig.isLobEnabled()) { // LOB support is not enabled, perform immediate dispatch dispatchChangeEvent(event); return; } if (lastEvent == null) { // Always cache first event, follow-up events will dictate merge/dispatch status this.lastEvent = event; if (EventType.SELECT_LOB_LOCATOR == event.getEventType()) { this.lastSelectLobLocatorEvent = (SelectLobLocatorEvent) event; } } else { // Check whether the LOB data queue needs to be drained to the last event LobState currentLobState = resolveLobStateByCurrentEvent(event); if (currentLobState != this.lobState) { if (this.lobState == LobState.WRITE) { mergeLobWriteData(lastEvent); } this.lobState = currentLobState; } if (!isMerged(event, lastEvent)) { LOGGER.trace("\tMerged skipped."); // Events were not merged, dispatch last one and cache new dispatchChangeEvent(lastEvent); this.lastEvent = event; } else { LOGGER.trace("\tMerged successfully."); } } } private void dispatchChangeEvent(LogMinerEvent event) throws InterruptedException { LOGGER.trace("\tEmitting event {} {}", event.getEventType(), event); delegate.accept(event); } private LobState resolveLobStateByCurrentEvent(LogMinerEvent event) { switch (event.getEventType()) { case LOB_WRITE: return LobState.WRITE; case LOB_ERASE: return LobState.ERASE; default: return LobState.OTHER; } } private boolean isMerged(LogMinerEvent event, LogMinerEvent prevEvent) { LOGGER.trace("\tVerifying merge eligibility for event {} with {}", event.getEventType(), prevEvent.getEventType()); if (EventType.SELECT_LOB_LOCATOR == event.getEventType()) { SelectLobLocatorEvent locatorEvent = (SelectLobLocatorEvent) event; this.lastSelectLobLocatorEvent = locatorEvent; if (EventType.INSERT == prevEvent.getEventType()) { // Previous event is an INSERT // Only merge the SEL_LOB_LOCATOR event if the previous INSERT is for the same table/row // and if the INSERT's column value is either EMPTY_CLOB() or EMPTY_BLOB() if (isForSameTableOrScn(event, prevEvent)) { LOGGER.trace("\tMerging SEL_LOB_LOCATOR with previous INSERT event"); return true; } } else if (EventType.UPDATE == prevEvent.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tUpdating SEL_LOB_LOCATOR column '{}' to previous UPDATE event", locatorEvent.getColumnName()); return true; } } else if (EventType.SELECT_LOB_LOCATOR == prevEvent.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tAdding column '{}' to previous SEL_LOB_LOCATOR event", locatorEvent.getColumnName()); return true; } } } else if (EventType.LOB_WRITE == event.getEventType()) { final LobWriteEvent writeEvent = (LobWriteEvent) event; if (lastSelectLobLocatorEvent.isBinary()) { if (!writeEvent.getData().startsWith("HEXTORAW('") && !writeEvent.getData().endsWith("')")) { throw new DebeziumException("Unexpected LOB data chunk: " + writeEvent.getData()); } } LOGGER.trace("\tAdded LOB_WRITE data to internal LOB queue."); lobWriteData.add(writeEvent.getData()); return true; } else if (EventType.LOB_ERASE == event.getEventType()) { // nothing is done with the event, its just consumed and treated as merged. LOGGER.warn("\tLOB_ERASE for table '{}' column '{}' is not supported.", lastSelectLobLocatorEvent.getTableId(), lastSelectLobLocatorEvent.getColumnName()); if (lastEvent != null && EventType.SELECT_LOB_LOCATOR == lastEvent.getEventType()) { LOGGER.trace("\tSkipped LOB_ERASE, discarding it and the prior SELECT_LOB_LOCATOR"); lastEvent = null; return true; } LOGGER.trace("\tSkipped LOB_ERASE, treated as merged."); return true; } else if (EventType.LOB_TRIM == event.getEventType()) { // nothing is done with the event, its just consumed and treated as merged. LOGGER.trace("\tSkipped LOB_TRIM, treated as merged."); return true; } else if (EventType.INSERT == event.getEventType() || EventType.UPDATE == event.getEventType()) { // Previous event is an INSERT // The only valid combination here would be if the current event is an UPDATE since an INSERT // cannot be merged with a prior INSERT. if (EventType.INSERT == prevEvent.getEventType()) { if (EventType.UPDATE == event.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tMerging UPDATE event with previous INSERT event"); mergeNewColumns((DmlEvent) event, (DmlEvent) prevEvent); return true; } } } else if (EventType.UPDATE == prevEvent.getEventType()) { // Previous event is an UPDATE // This will happen if there are non LOB and inline LOB fields updated in the same SQL. // The inline LOB values should be merged with the previous UPDATE event if (EventType.UPDATE == event.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tMerging UPDATE event with previous UPDATE event"); mergeNewColumns((DmlEvent) event, (DmlEvent) prevEvent); return true; } } } else if (EventType.SELECT_LOB_LOCATOR == prevEvent.getEventType()) { // Previous event is a SEL_LOB_LOCATOR // SQL contains both non-inline LOB and inline-LOB field changes if (EventType.UPDATE == event.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { for (int i = 0; i < ((DmlEvent) event).getDmlEntry().getNewValues().length; ++i) { Object value = ((DmlEvent) event).getDmlEntry().getNewValues()[i]; Object prevValue = ((DmlEvent) prevEvent).getDmlEntry().getNewValues()[i]; if (prevValue == null && value != null) { LOGGER.trace("\tAdding column index {} to previous SEL_LOB_LOCATOR event", i); ((DmlEvent) prevEvent).getDmlEntry().getNewValues()[i] = value; } } return true; } } } } LOGGER.trace("\tEvent {} is for a different row, merge skipped.", event.getEventType()); return false; } private void mergeLobWriteData(LogMinerEvent event) { final Object data; if (this.lastSelectLobLocatorEvent.isBinary()) { // For BLOB we pass the list of chunks as-is to the value converter data = new BlobChunkList(lobWriteData); } else { // For CLOB we go ahead and pre-process the list into a single string data = String.join("", lobWriteData); } final DmlEvent dmlEvent = (DmlEvent) event; final String columnName = lastSelectLobLocatorEvent.getColumnName(); final int columnIndex = getSelectLobLocatorColumnIndex(); LOGGER.trace("\tSet LOB data for column '{}' on table {} in event {}", columnName, event.getTableId(), event.getEventType()); dmlEvent.getDmlEntry().getNewValues()[columnIndex] = data; lobWriteData.clear(); } private int getSelectLobLocatorColumnIndex() { final String columnName = lastSelectLobLocatorEvent.getColumnName(); return LogMinerHelper.getColumnIndexByName(columnName, schema.tableFor(lastSelectLobLocatorEvent.getTableId())); } private boolean isForSameTableOrScn(LogMinerEvent event, LogMinerEvent prevEvent) { if (prevEvent != null) { if (event.getTableId().equals(prevEvent.getTableId())) { return true; } return event.getScn().equals(prevEvent.getScn()) && event.getRsId().equals(prevEvent.getRsId()); } return false; } private boolean isSameTableRow(LogMinerEvent event, LogMinerEvent prevEvent) { final Table table = schema.tableFor(event.getTableId()); if (table == null) { LOGGER.trace("Unable to locate table '{}' schema, unable to detect if same row.", event.getTableId()); return false; } for (String columnName : table.primaryKeyColumnNames()) { int position = LogMinerHelper.getColumnIndexByName(columnName, table); Object prevValue = ((DmlEvent) prevEvent).getDmlEntry().getNewValues()[position]; if (prevValue == null) { throw new DebeziumException("Could not find column " + columnName + " in previous event"); } Object value = ((DmlEvent) event).getDmlEntry().getNewValues()[position]; if (value == null) { throw new DebeziumException("Could not find column " + columnName + " in event"); } if (!Objects.equals(value, prevValue)) { return false; } } return true; } private void mergeNewColumns(DmlEvent event, DmlEvent prevEvent) { final boolean prevEventIsInsert = EventType.INSERT == prevEvent.getEventType(); for (int i = 0; i < event.getDmlEntry().getNewValues().length; ++i) { Object value = event.getDmlEntry().getNewValues()[i]; Object prevValue = prevEvent.getDmlEntry().getNewValues()[i]; if (prevEventIsInsert && "EMPTY_CLOB()".equals(prevValue)) { LOGGER.trace("\tAssigning column index {} with updated CLOB value.", i); prevEvent.getDmlEntry().getNewValues()[i] = value; } else if (prevEventIsInsert && "EMPTY_BLOB()".equals(prevValue)) { LOGGER.trace("\tAssigning column index {} with updated BLOB value.", i); prevEvent.getDmlEntry().getNewValues()[i] = value; } else if (!prevEventIsInsert && OracleValueConverters.UNAVAILABLE_VALUE.equals(value)) { LOGGER.trace("\tSkipped column index {} with unavailable column value.", i); } else if (!prevEventIsInsert && value != null) { LOGGER.trace("\tUpdating column index {} in previous event", i); prevEvent.getDmlEntry().getNewValues()[i] = value; } } } }
debezium-connector-oracle/src/main/java/io/debezium/connector/oracle/logminer/processor/TransactionCommitConsumer.java
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.oracle.logminer.processor; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.DebeziumException; import io.debezium.connector.oracle.BlobChunkList; import io.debezium.connector.oracle.OracleConnectorConfig; import io.debezium.connector.oracle.OracleDatabaseSchema; import io.debezium.connector.oracle.OracleValueConverters; import io.debezium.connector.oracle.logminer.LogMinerHelper; import io.debezium.connector.oracle.logminer.events.DmlEvent; import io.debezium.connector.oracle.logminer.events.EventType; import io.debezium.connector.oracle.logminer.events.LobWriteEvent; import io.debezium.connector.oracle.logminer.events.LogMinerEvent; import io.debezium.connector.oracle.logminer.events.SelectLobLocatorEvent; import io.debezium.function.BlockingConsumer; import io.debezium.relational.Table; /** * A consumer of transaction events at commit time that is capable of inspecting the event stream, * merging events that should be merged when LOB support is enabled, and then delegating the final * stream of events to a delegate consumer. * * When a table has a LOB field, Oracle LogMiner often supplies us with synthetic events that deal * with sub-tasks that occur in the database as a result of writing LOB data to the database. We * would prefer to emit these synthetic events as a part of the overall logical event, whether that * is an insert or update. * * An example of a scenario would be the following logical user action: * INSERT INTO my_table (id,lob_field) values (1, 'some clob data'); * * Oracle LogMiner provides the connector with the following events: * INSERT INTO my_table (id,lob_field) values (1, EMPTY_CLOB()); * UPDATE my_table SET lob_field = 'some clob data' where id = 1; * * When LOB support is enabled, this consumer implementation will detect that the update is an * event that should be merged with the previous insert event so that the emitted change events * consists a single logical change, an insert that have an after section like: * * <pre> * "after": { * "id": 1, * "lob_field": "some clob data" * } * </pre> * * When LOB support isn't enabled, events are simply passed through to the delegate and no event * inspection, merging, or buffering occurs. * * @author Chris Cranford */ public class TransactionCommitConsumer implements AutoCloseable, BlockingConsumer<LogMinerEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(TransactionCommitConsumer.class); private final BlockingConsumer<LogMinerEvent> delegate; private final OracleConnectorConfig connectorConfig; private final OracleDatabaseSchema schema; private final List<String> lobWriteData; /** * Describes the current LOB event buffering state, whether we're working on a series of * {@code LOB_WRITE} events, {@code LOB_ERASE} events, or any other type of event that * does not require special handling. */ enum LobState { WRITE, ERASE, OTHER }; private LogMinerEvent lastEvent; private SelectLobLocatorEvent lastSelectLobLocatorEvent; private LobState lobState; public TransactionCommitConsumer(BlockingConsumer<LogMinerEvent> delegate, OracleConnectorConfig connectorConfig, OracleDatabaseSchema schema) { this.delegate = delegate; this.lobState = LobState.OTHER; this.lobWriteData = new ArrayList<>(); this.connectorConfig = connectorConfig; this.schema = schema; } @Override public void close() throws InterruptedException { if (lastEvent != null) { if (!lobWriteData.isEmpty()) { mergeLobWriteData(lastEvent); } dispatchChangeEvent(lastEvent); } } @Override public void accept(LogMinerEvent event) throws InterruptedException { if (!connectorConfig.isLobEnabled()) { // LOB support is not enabled, perform immediate dispatch dispatchChangeEvent(event); return; } if (lastEvent == null) { // Always cache first event, follow-up events will dictate merge/dispatch status this.lastEvent = event; if (EventType.SELECT_LOB_LOCATOR == event.getEventType()) { this.lastSelectLobLocatorEvent = (SelectLobLocatorEvent) event; } } else { // Check whether the LOB data queue needs to be drained to the last event LobState currentLobState = resolveLobStateByCurrentEvent(event); if (currentLobState != this.lobState) { if (this.lobState == LobState.WRITE) { mergeLobWriteData(lastEvent); } this.lobState = currentLobState; } if (!isMerged(event, lastEvent)) { LOGGER.trace("\tMerged skipped."); // Events were not merged, dispatch last one and cache new dispatchChangeEvent(lastEvent); this.lastEvent = event; } else { LOGGER.trace("\tMerged successfully."); } } } private void dispatchChangeEvent(LogMinerEvent event) throws InterruptedException { LOGGER.trace("\tEmitting event {} {}", event.getEventType(), event); delegate.accept(event); } private LobState resolveLobStateByCurrentEvent(LogMinerEvent event) { switch (event.getEventType()) { case LOB_WRITE: return LobState.WRITE; case LOB_ERASE: return LobState.ERASE; default: return LobState.OTHER; } } private boolean isMerged(LogMinerEvent event, LogMinerEvent prevEvent) { LOGGER.trace("\tVerifying merge eligibility for event {} with {}", event.getEventType(), prevEvent.getEventType()); if (EventType.SELECT_LOB_LOCATOR == event.getEventType()) { SelectLobLocatorEvent locatorEvent = (SelectLobLocatorEvent) event; this.lastSelectLobLocatorEvent = locatorEvent; if (EventType.INSERT == prevEvent.getEventType()) { // Previous event is an INSERT // Only merge the SEL_LOB_LOCATOR event if the previous INSERT is for the same table/row // and if the INSERT's column value is either EMPTY_CLOB() or EMPTY_BLOB() if (isForSameTableOrScn(event, prevEvent)) { LOGGER.trace("\tMerging SEL_LOB_LOCATOR with previous INSERT event"); return true; } } else if (EventType.UPDATE == prevEvent.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tUpdating SEL_LOB_LOCATOR column '{}' to previous UPDATE event", locatorEvent.getColumnName()); return true; } } else if (EventType.SELECT_LOB_LOCATOR == prevEvent.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tAdding column '{}' to previous SEL_LOB_LOCATOR event", locatorEvent.getColumnName()); return true; } } } else if (EventType.LOB_WRITE == event.getEventType()) { final LobWriteEvent writeEvent = (LobWriteEvent) event; if (lastSelectLobLocatorEvent.isBinary()) { if (!writeEvent.getData().startsWith("HEXTORAW('") && !writeEvent.getData().endsWith("')")) { throw new DebeziumException("Unexpected LOB data chunk: " + writeEvent.getData()); } } LOGGER.trace("\tAdded LOB_WRITE data to internal LOB queue."); lobWriteData.add(writeEvent.getData()); return true; } else if (EventType.LOB_ERASE == event.getEventType()) { // nothing is done with the event, its just consumed and treated as merged. LOGGER.warn("\tLOB_ERASE for table '{}' column '{}' is not supported.", lastSelectLobLocatorEvent.getTableId(), lastSelectLobLocatorEvent.getColumnName()); LOGGER.trace("\tSkipped LOB_ERASE, treated as merged."); return true; } else if (EventType.LOB_TRIM == event.getEventType()) { // nothing is done with the event, its just consumed and treated as merged. LOGGER.trace("\tSkipped LOB_TRIM, treated as merged."); return true; } else if (EventType.INSERT == event.getEventType() || EventType.UPDATE == event.getEventType()) { // Previous event is an INSERT // The only valid combination here would be if the current event is an UPDATE since an INSERT // cannot be merged with a prior INSERT. if (EventType.INSERT == prevEvent.getEventType()) { if (EventType.UPDATE == event.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tMerging UPDATE event with previous INSERT event"); mergeNewColumns((DmlEvent) event, (DmlEvent) prevEvent); return true; } } } else if (EventType.UPDATE == prevEvent.getEventType()) { // Previous event is an UPDATE // This will happen if there are non LOB and inline LOB fields updated in the same SQL. // The inline LOB values should be merged with the previous UPDATE event if (EventType.UPDATE == event.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { LOGGER.trace("\tMerging UPDATE event with previous UPDATE event"); mergeNewColumns((DmlEvent) event, (DmlEvent) prevEvent); return true; } } } else if (EventType.SELECT_LOB_LOCATOR == prevEvent.getEventType()) { // Previous event is a SEL_LOB_LOCATOR // SQL contains both non-inline LOB and inline-LOB field changes if (EventType.UPDATE == event.getEventType()) { if (isForSameTableOrScn(event, prevEvent) && isSameTableRow(event, prevEvent)) { for (int i = 0; i < ((DmlEvent) event).getDmlEntry().getNewValues().length; ++i) { Object value = ((DmlEvent) event).getDmlEntry().getNewValues()[i]; Object prevValue = ((DmlEvent) prevEvent).getDmlEntry().getNewValues()[i]; if (prevValue == null && value != null) { LOGGER.trace("\tAdding column index {} to previous SEL_LOB_LOCATOR event", i); ((DmlEvent) prevEvent).getDmlEntry().getNewValues()[i] = value; } } return true; } } } } LOGGER.trace("\tEvent {} is for a different row, merge skipped.", event.getEventType()); return false; } private void mergeLobWriteData(LogMinerEvent event) { final Object data; if (this.lastSelectLobLocatorEvent.isBinary()) { // For BLOB we pass the list of chunks as-is to the value converter data = new BlobChunkList(lobWriteData); } else { // For CLOB we go ahead and pre-process the list into a single string data = String.join("", lobWriteData); } final DmlEvent dmlEvent = (DmlEvent) event; final String columnName = lastSelectLobLocatorEvent.getColumnName(); final int columnIndex = getSelectLobLocatorColumnIndex(); LOGGER.trace("\tSet LOB data for column '{}' on table {} in event {}", columnName, event.getTableId(), event.getEventType()); dmlEvent.getDmlEntry().getNewValues()[columnIndex] = data; lobWriteData.clear(); } private int getSelectLobLocatorColumnIndex() { final String columnName = lastSelectLobLocatorEvent.getColumnName(); return LogMinerHelper.getColumnIndexByName(columnName, schema.tableFor(lastSelectLobLocatorEvent.getTableId())); } private boolean isForSameTableOrScn(LogMinerEvent event, LogMinerEvent prevEvent) { if (prevEvent != null) { if (event.getTableId().equals(prevEvent.getTableId())) { return true; } return event.getScn().equals(prevEvent.getScn()) && event.getRsId().equals(prevEvent.getRsId()); } return false; } private boolean isSameTableRow(LogMinerEvent event, LogMinerEvent prevEvent) { final Table table = schema.tableFor(event.getTableId()); if (table == null) { LOGGER.trace("Unable to locate table '{}' schema, unable to detect if same row.", event.getTableId()); return false; } for (String columnName : table.primaryKeyColumnNames()) { int position = LogMinerHelper.getColumnIndexByName(columnName, table); Object prevValue = ((DmlEvent) prevEvent).getDmlEntry().getNewValues()[position]; if (prevValue == null) { throw new DebeziumException("Could not find column " + columnName + " in previous event"); } Object value = ((DmlEvent) event).getDmlEntry().getNewValues()[position]; if (value == null) { throw new DebeziumException("Could not find column " + columnName + " in event"); } if (!Objects.equals(value, prevValue)) { return false; } } return true; } private void mergeNewColumns(DmlEvent event, DmlEvent prevEvent) { final boolean prevEventIsInsert = EventType.INSERT == prevEvent.getEventType(); for (int i = 0; i < event.getDmlEntry().getNewValues().length; ++i) { Object value = event.getDmlEntry().getNewValues()[i]; Object prevValue = prevEvent.getDmlEntry().getNewValues()[i]; if (prevEventIsInsert && "EMPTY_CLOB()".equals(prevValue)) { LOGGER.trace("\tAssigning column index {} with updated CLOB value.", i); prevEvent.getDmlEntry().getNewValues()[i] = value; } else if (prevEventIsInsert && "EMPTY_BLOB()".equals(prevValue)) { LOGGER.trace("\tAssigning column index {} with updated BLOB value.", i); prevEvent.getDmlEntry().getNewValues()[i] = value; } else if (!prevEventIsInsert && OracleValueConverters.UNAVAILABLE_VALUE.equals(value)) { LOGGER.trace("\tSkipped column index {} with unavailable column value.", i); } else if (!prevEventIsInsert && value != null) { LOGGER.trace("\tUpdating column index {} in previous event", i); prevEvent.getDmlEntry().getNewValues()[i] = value; } } } }
DBZ-4384 Correctly skip emitting events when LOB_ERASE is detected
debezium-connector-oracle/src/main/java/io/debezium/connector/oracle/logminer/processor/TransactionCommitConsumer.java
DBZ-4384 Correctly skip emitting events when LOB_ERASE is detected
<ide><path>ebezium-connector-oracle/src/main/java/io/debezium/connector/oracle/logminer/processor/TransactionCommitConsumer.java <ide> // nothing is done with the event, its just consumed and treated as merged. <ide> LOGGER.warn("\tLOB_ERASE for table '{}' column '{}' is not supported.", <ide> lastSelectLobLocatorEvent.getTableId(), lastSelectLobLocatorEvent.getColumnName()); <add> if (lastEvent != null && EventType.SELECT_LOB_LOCATOR == lastEvent.getEventType()) { <add> LOGGER.trace("\tSkipped LOB_ERASE, discarding it and the prior SELECT_LOB_LOCATOR"); <add> lastEvent = null; <add> return true; <add> } <ide> LOGGER.trace("\tSkipped LOB_ERASE, treated as merged."); <ide> return true; <ide> }
Java
apache-2.0
ef11af8676e6479189393541e74c7407987251fc
0
michael-simons/spring-boot,aahlenst/spring-boot,eddumelendez/spring-boot,scottfrederick/spring-boot,spring-projects/spring-boot,ilayaperumalg/spring-boot,wilkinsona/spring-boot,NetoDevel/spring-boot,jxblum/spring-boot,scottfrederick/spring-boot,tiarebalbi/spring-boot,mdeinum/spring-boot,Buzzardo/spring-boot,dreis2211/spring-boot,vpavic/spring-boot,htynkn/spring-boot,lburgazzoli/spring-boot,mbenson/spring-boot,eddumelendez/spring-boot,vpavic/spring-boot,NetoDevel/spring-boot,vpavic/spring-boot,michael-simons/spring-boot,joshiste/spring-boot,shakuzen/spring-boot,dreis2211/spring-boot,tiarebalbi/spring-boot,jxblum/spring-boot,tiarebalbi/spring-boot,dreis2211/spring-boot,spring-projects/spring-boot,htynkn/spring-boot,yangdd1205/spring-boot,chrylis/spring-boot,ilayaperumalg/spring-boot,mdeinum/spring-boot,mdeinum/spring-boot,vpavic/spring-boot,chrylis/spring-boot,Buzzardo/spring-boot,lburgazzoli/spring-boot,Buzzardo/spring-boot,lburgazzoli/spring-boot,joshiste/spring-boot,mbenson/spring-boot,spring-projects/spring-boot,shakuzen/spring-boot,mbenson/spring-boot,jxblum/spring-boot,spring-projects/spring-boot,scottfrederick/spring-boot,aahlenst/spring-boot,dreis2211/spring-boot,ilayaperumalg/spring-boot,yangdd1205/spring-boot,philwebb/spring-boot,chrylis/spring-boot,scottfrederick/spring-boot,NetoDevel/spring-boot,philwebb/spring-boot,spring-projects/spring-boot,mbenson/spring-boot,ilayaperumalg/spring-boot,aahlenst/spring-boot,royclarkson/spring-boot,joshiste/spring-boot,htynkn/spring-boot,dreis2211/spring-boot,philwebb/spring-boot,eddumelendez/spring-boot,yangdd1205/spring-boot,rweisleder/spring-boot,lburgazzoli/spring-boot,aahlenst/spring-boot,rweisleder/spring-boot,philwebb/spring-boot,shakuzen/spring-boot,shakuzen/spring-boot,joshiste/spring-boot,michael-simons/spring-boot,scottfrederick/spring-boot,Buzzardo/spring-boot,lburgazzoli/spring-boot,mbenson/spring-boot,wilkinsona/spring-boot,chrylis/spring-boot,aahlenst/spring-boot,michael-simons/spring-boot,mbenson/spring-boot,jxblum/spring-boot,ilayaperumalg/spring-boot,rweisleder/spring-boot,vpavic/spring-boot,michael-simons/spring-boot,tiarebalbi/spring-boot,rweisleder/spring-boot,dreis2211/spring-boot,wilkinsona/spring-boot,royclarkson/spring-boot,mdeinum/spring-boot,NetoDevel/spring-boot,mdeinum/spring-boot,aahlenst/spring-boot,htynkn/spring-boot,shakuzen/spring-boot,wilkinsona/spring-boot,royclarkson/spring-boot,philwebb/spring-boot,jxblum/spring-boot,ilayaperumalg/spring-boot,eddumelendez/spring-boot,royclarkson/spring-boot,wilkinsona/spring-boot,rweisleder/spring-boot,spring-projects/spring-boot,scottfrederick/spring-boot,tiarebalbi/spring-boot,royclarkson/spring-boot,chrylis/spring-boot,Buzzardo/spring-boot,joshiste/spring-boot,philwebb/spring-boot,Buzzardo/spring-boot,tiarebalbi/spring-boot,wilkinsona/spring-boot,vpavic/spring-boot,shakuzen/spring-boot,eddumelendez/spring-boot,rweisleder/spring-boot,chrylis/spring-boot,mdeinum/spring-boot,htynkn/spring-boot,joshiste/spring-boot,michael-simons/spring-boot,NetoDevel/spring-boot,jxblum/spring-boot,htynkn/spring-boot,eddumelendez/spring-boot
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.devtools.env; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DevToolsHomePropertiesPostProcessor}. * * @author Phillip Webb * @author Andy Wilkinson */ public class DevToolsHomePropertiesPostProcessorTests { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File home; @Before public void setup() throws IOException { this.home = this.temp.newFolder(); } @Test public void loadsHomeProperties() throws Exception { Properties properties = new Properties(); properties.put("abc", "def"); OutputStream out = new FileOutputStream( new File(this.home, ".spring-boot-devtools.properties")); properties.store(out, null); out.close(); ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); runPostProcessor(() -> postProcessor.postProcessEnvironment(environment, null)); assertThat(environment.getProperty("abc")).isEqualTo("def"); } @Test public void ignoresMissingHomeProperties() throws Exception { ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); runPostProcessor(() -> postProcessor.postProcessEnvironment(environment, null)); assertThat(environment.getProperty("abc")).isNull(); } protected void runPostProcessor(Runnable runnable) throws Exception { Thread thread = new Thread(runnable); thread.start(); thread.join(); } private class MockDevToolHomePropertiesPostProcessor extends DevToolsHomePropertiesPostProcessor { @Override protected File getHomeFolder() { return DevToolsHomePropertiesPostProcessorTests.this.home; } } }
spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.devtools.env; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DevToolsHomePropertiesPostProcessor}. * * @author Phillip Webb * @author Andy Wilkinson */ public class DevToolsHomePropertiesPostProcessorTests { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File home; @Before public void setup() throws IOException { this.home = this.temp.newFolder(); } @Test public void loadsHomeProperties() throws Exception { Properties properties = new Properties(); properties.put("abc", "def"); OutputStream out = new FileOutputStream( new File(this.home, ".spring-boot-devtools.properties")); properties.store(out, null); out.close(); ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); runPostProcessor(() -> postProcessor.postProcessEnvironment(environment, null)); assertThat(environment.getProperty("abc")).isEqualTo("def"); } @Test public void ignoresMissingHomeProperties() throws Exception { ConfigurableEnvironment environment = new MockEnvironment(); MockDevToolHomePropertiesPostProcessor postProcessor = new MockDevToolHomePropertiesPostProcessor(); runPostProcessor(() -> postProcessor.postProcessEnvironment(environment, null)); assertThat(environment.getProperty("abc")).isNull(); } protected void runPostProcessor(Runnable runnable) throws Exception { Thread thread = new Thread(() -> { runnable.run(); }); thread.start(); thread.join(); } private class MockDevToolHomePropertiesPostProcessor extends DevToolsHomePropertiesPostProcessor { @Override protected File getHomeFolder() { return DevToolsHomePropertiesPostProcessorTests.this.home; } } }
Polish "Remove unnecessary latches in tests" Closes gh-16733
spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java
Polish "Remove unnecessary latches in tests"
<ide><path>pring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsHomePropertiesPostProcessorTests.java <ide> /* <del> * Copyright 2012-2017 the original author or authors. <add> * Copyright 2012-2019 the original author or authors. <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. <ide> } <ide> <ide> protected void runPostProcessor(Runnable runnable) throws Exception { <del> Thread thread = new Thread(() -> { <del> runnable.run(); <del> }); <add> Thread thread = new Thread(runnable); <ide> thread.start(); <ide> thread.join(); <ide> }
Java
apache-2.0
c4efa8adfff87e0bd3420eec008ee7696d65f485
0
googleinterns/step128-2020,googleinterns/step128-2020,googleinterns/step128-2020
package com.google.sps; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Logger; import org.apache.spark.ml.evaluation.RegressionEvaluator; import org.apache.spark.ml.recommendation.ALS; import org.apache.spark.ml.recommendation.ALSModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; public class Recommend { // keep and use up to this many Interaction entities private static final int UPPER_LIMIT = 5_000_000; // multipliers for score calculation private static final double NO_INTERACTION = 1.5; private static final double ALREADY_VIEWED = 1.2; private static final double ALREADY_SAVED = 0.6; private static final float ZERO = 0.1f; // comparator to sort doubles in descending order private static final Comparator<Double> SCORE_DESCENDING = new Comparator<Double>() { @Override public int compare(Double a, Double b) { return Double.compare(b, a); } }; private static final Logger LOGGER = Logger.getLogger(Recommend.class.getName()); private static SparkSession spark; private static DatastoreService datastore; // keep track of ids and hashcodes -- spark requires numeric entries private static Map<Integer, String> userIdHash = new HashMap<>(); private static Map<Integer, Long> eventIdHash = new HashMap<>(); // keep track of metrics and location for each user and event private static Map<String, Map<String, Float>> userPrefs = new HashMap<>(); private static Map<Long, Map<String, Integer>> eventInfo = new HashMap<>(); private static Map<String, String> userLocations = new HashMap<>(); private static Map<Long, String> eventLocations = new HashMap<>(); /** Initializes the SparkSession, datastore, and other necessary items. */ private static void init() { if (spark == null) { spark = SparkSession.builder() .appName("Java Spark SQL basic example") .config("spark.master", "local[*]") .getOrCreate(); spark.sparkContext().setLogLevel("ERROR"); } if (datastore == null) { datastore = DatastoreServiceFactory.getDatastoreService(); } userIdHash = new HashMap<>(); eventIdHash = new HashMap<>(); userPrefs = new HashMap<>(); eventInfo = new HashMap<>(); userLocations = new HashMap<>(); eventLocations = new HashMap<>(); } /** Rebuilds recommendation model and calculates recommendations for users. */ public static void calculateRecommend() throws IOException { init(); getInfoFromDatastore(); List<Key> toDelete = new ArrayList<>(); Dataset<Row> ratings = makeDataframeAndPreprocess(userIdHash.keySet(), eventIdHash.keySet(), toDelete); // compute recommendations from matrix factorization ALSModel model = trainModel(null, ratings); Dataset<Row> userRecs = model.recommendForAllUsers(150); List<Row> userRecsList = userRecs.collectAsList(); for (Row recRow : userRecsList) { String userId = userIdHash.get(recRow.getInt(0)); List<Row> predScores = recRow.getList(1); Map<Double, List<Long>> userTopRecs = new TreeMap<>(SCORE_DESCENDING); for (Row itemRow : predScores) { long eventId = eventIdHash.get(itemRow.getInt(0)); float predScore = itemRow.getFloat(1); if (predScore == 0.0f) { predScore = ZERO; } double totalScore = computeScore(userId, eventId, predScore); // add item to ranking List<Long> eventsWithScore = userTopRecs.get(totalScore); if (eventsWithScore == null) { eventsWithScore = new ArrayList<>(); userTopRecs.put(totalScore, eventsWithScore); } eventsWithScore.add(eventId); } saveRecsToDatastore(userId, userTopRecs); userPrefs.remove(userId); } // handle users not accounted for by ALSModel for (String userId : userPrefs.keySet()) {} datastore.delete(toDelete); } /** * Trains an ALSModel on the provided training dataset. * * @param path If specified, will save the model parameters at this path * @param training Will fit the model to this training dataset */ public static ALSModel trainModel(String path, Dataset<Row> training) throws IOException { ALS als = new ALS().setMaxIter(5).setUserCol("userId").setItemCol("eventId").setRatingCol("rating"); ALSModel model = als.fit(training); model.setColdStartStrategy("drop"); if (path != null) { model.write().overwrite().save(path); LOGGER.info("model saved at " + path); } return model; } /** Uses RMSE to evaluate a set of predicted data. */ public static double evaluatePredictions(Dataset<Row> predictions) { RegressionEvaluator evaluator = new RegressionEvaluator() .setMetricName("rmse") .setLabelCol("rating") .setPredictionCol("prediction"); return evaluator.evaluate(predictions); } /** Queries datastore and populates data maps. */ private static void getInfoFromDatastore() { // get user entities with their preferences Iterable<Entity> queriedUsers = datastore.prepare(new Query("User")).asIterable(); for (Entity e : queriedUsers) { String id = e.getKey().getName(); userPrefs.put(id, Interactions.buildVectorForUser(e)); userIdHash.put(id.hashCode(), id); if (e.hasProperty("location")) { String location = e.getProperty("location").toString(); if (location.length() > 0) { userLocations.put(id, location); } } } // get event entities Iterable<Entity> queriedEvents = datastore.prepare(new Query("Event")).asIterable(); for (Entity e : queriedEvents) { long id = e.getKey().getId(); eventInfo.put(id, Interactions.buildVectorForEvent(e)); eventIdHash.put((Long.toString(id)).hashCode(), id); eventLocations.put(id, e.getProperty("address").toString()); } } /** * Constructs ratings dataframe. Also flushes outdated Interaction entities from datastore. * * @param users List of users that datastore is keeping track of. * @param events List of existing events that datastore is keeping track of. * @param toDelete Save list of keys to delete, if interaction entities need to be flushed. */ private static Dataset<Row> makeDataframeAndPreprocess( Set<Integer> users, Set<Integer> events, List<Key> toDelete) { Iterable<Entity> queriedInteractions = datastore .prepare(new Query("Interaction").addSort("timestamp", Query.SortDirection.DESCENDING)) .asIterable(); Iterator<Entity> itr = queriedInteractions.iterator(); int count = 0; List<EventRating> ratings = new ArrayList<>(); while (itr.hasNext() && count < UPPER_LIMIT) { Entity entity = itr.next(); // convert Entities to spark-friendly format EventRating rate = EventRating.parseEntity(entity); if (rate != null) { if (!users.contains(rate.getUserId()) || !events.contains(rate.getEventId())) { // delete interaction of user or event id is invalid toDelete.add(entity.getKey()); } else { count++; ratings.add(rate); } } else { // something wrong with this entry, delete it toDelete.add(entity.getKey()); } } // delete the oldest Interaction entries from datastore while (itr.hasNext()) { toDelete.add(itr.next().getKey()); } return spark.createDataFrame(ratings, EventRating.class); } /** * Computes cumulative total score for given user and event. * * @param predScore Base score to apply multipliers to. */ private static double computeScore(String userId, long eventId, float predScore) { float dotProduct = Interactions.dotProduct(userPrefs.get(userId), eventInfo.get(eventId)); double totalScore = dotProduct * predScore; // adjust scaling based on user's past interaction with event Entity interactionEntity = Interactions.hasInteraction(userId, eventId); if (interactionEntity == null) { totalScore *= NO_INTERACTION; } else { float interactionScore = Float.parseFloat(interactionEntity.getProperty("rating").toString()); if (interactionScore >= Interactions.SAVE_SCORE) { totalScore *= ALREADY_SAVED; } else if (interactionScore == Interactions.VIEW_SCORE) { totalScore *= ALREADY_VIEWED; } } String userLocation = userLocations.get(userId); if (userLocation != null) { // TODO: scale based on location } totalScore = Math.round(totalScore * 100.0) / 100.0; return totalScore; } /** Stores a recommendation datastore entry for the given user ID. */ private static void saveRecsToDatastore(String userId, Map<Double, List<Long>> recs) { List<Long> recsList = new ArrayList<>(); for (Double score : recs.keySet()) { for (Long l : recs.get(score)) { recsList.add(l); } } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key recKey = KeyFactory.createKey("Recommendation", userId); Entity recEntity = null; try { recEntity = datastore.get(recKey); } catch (EntityNotFoundException e) { recEntity = new Entity(recKey); } recEntity.setProperty("recs", recsList); datastore.put(recEntity); } public static class EventRating implements Serializable { private int userId; private int eventId; private float rating; private long timestamp; /** Creates an EventRating object. */ public EventRating(String userId, long eventId, float rating, long timestamp) { // all fields must be numeric this.userId = userId.hashCode(); // spark implicitly casts long to int otherwise this.eventId = (Long.toString(eventId)).hashCode(); this.rating = rating; this.timestamp = timestamp; } // need getters to work with spark.createDataFrame() public int getUserId() { return userId; } public int getEventId() { return eventId; } public float getRating() { return rating; } public long getTimestamp() { return timestamp; } /** Creates an EventRating object from an Interaction Entity. */ public static EventRating parseEntity(Entity entity) { if (!entity.getKind().equals("Interaction")) { return null; } Object userField = entity.getProperty("user"); Object eventField = entity.getProperty("event"); Object ratingField = entity.getProperty("rating"); Object timeField = entity.getProperty("timestamp"); if (userField == null || eventField == null || ratingField == null || timeField == null) { return null; } try { String userId = userField.toString(); long eventId = Long.parseLong(eventField.toString()); float rating = Float.parseFloat(ratingField.toString()); long timestamp = Long.parseLong(timeField.toString()); return new EventRating(userId, eventId, rating, timestamp); } catch (NumberFormatException e) { return null; } } public String toString() { return userId + " " + eventId + " " + rating + " " + timestamp; } } }
src/main/java/com/google/sps/Recommend.java
package com.google.sps; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Logger; import org.apache.spark.ml.evaluation.RegressionEvaluator; import org.apache.spark.ml.recommendation.ALS; import org.apache.spark.ml.recommendation.ALSModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; public class Recommend { // keep and use up to this many Interaction entities private static final int UPPER_LIMIT = 5_000_000; // multipliers for score calculation private static final double NO_INTERACTION = 1.5; private static final double ALREADY_VIEWED = 1.2; private static final double ALREADY_SAVED = 0.6; // comparator to sort doubles in descending order private static final Comparator<Double> SCORE_DESCENDING = new Comparator<Double>() { @Override public int compare(Double a, Double b) { return Double.compare(b, a); } }; private static final Logger LOGGER = Logger.getLogger(Recommend.class.getName()); private static SparkSession spark; private static DatastoreService datastore; /** Initializes the SparkSession. */ private static void init() { if (spark == null) { spark = SparkSession.builder() .appName("Java Spark SQL basic example") .config("spark.master", "local[*]") .getOrCreate(); spark.sparkContext().setLogLevel("ERROR"); } if (datastore == null) { datastore = DatastoreServiceFactory.getDatastoreService(); } } /** Rebuilds recommendation model and calculates recommendations for users. */ public static void calculateRecommend() throws IOException { init(); // keep track of ids and hashcodes -- spark requires numeric entries final Map<Integer, String> userIdHash = new HashMap<>(); final Map<Integer, Long> eventIdHash = new HashMap<>(); // keep track of metrics and location for each user and event final Map<String, Map<String, Float>> userPrefs = new HashMap<>(); final Map<Long, Map<String, Integer>> eventInfo = new HashMap<>(); final Map<String, String> userLocations = new HashMap<>(); final Map<Long, String> eventLocations = new HashMap<>(); // get user entities with their preferences Iterable<Entity> queriedUsers = datastore.prepare(new Query("User")).asIterable(); for (Entity e : queriedUsers) { String id = e.getKey().getName(); userPrefs.put(id, Interactions.buildVectorForUser(e)); userIdHash.put(id.hashCode(), id); if (e.hasProperty("location")) { String location = e.getProperty("location").toString(); if (location.length() > 0) { userLocations.put(id, location); } } } // get event entities Iterable<Entity> queriedEvents = datastore.prepare(new Query("Event")).asIterable(); for (Entity e : queriedEvents) { long id = e.getKey().getId(); eventInfo.put(id, Interactions.buildVectorForEvent(e)); eventIdHash.put((Long.toString(id)).hashCode(), id); eventLocations.put(id, e.getProperty("address").toString()); } List<Key> toDelete = new ArrayList<>(); Dataset<Row> ratings = makeDataframeAndPreprocess(userIdHash.keySet(), eventIdHash.keySet(), toDelete); // compute recommendations from matrix factorization ALSModel model = trainModel(null, ratings); Dataset<Row> userRecs = model.recommendForAllUsers(150); List<Row> userRecsList = userRecs.collectAsList(); for (Row recRow : userRecsList) { String userId = userIdHash.get(recRow.getInt(0)); List<Row> predScores = recRow.getList(1); Map<String, Float> userVector = userPrefs.get(userId); String userLocation = userLocations.get(userId); Map<Double, List<Long>> userTopRecs = new TreeMap<>(SCORE_DESCENDING); for (Row itemRow : predScores) { long eventId = eventIdHash.get(itemRow.getInt(0)); float predScore = itemRow.getFloat(1); // calculate score for this item float dotProduct = Interactions.dotProduct(userVector, eventInfo.get(eventId)); double totalScore = dotProduct * predScore; // todo: calculate // adjust scaling based on user's past interaction with event Entity interactionEntity = Interactions.hasInteraction(userId, eventId); if (interactionEntity == null) { totalScore *= NO_INTERACTION; } else { float interactionScore = Float.parseFloat(interactionEntity.getProperty("rating").toString()); if (interactionScore >= Interactions.SAVE_SCORE) { totalScore *= ALREADY_SAVED; } else if (interactionScore == Interactions.VIEW_SCORE) { totalScore *= ALREADY_VIEWED; } } // TODO: adjust scaling based on user's location, if location is saved // add item to ranking List<Long> eventsWithScore = userTopRecs.get(totalScore); if (eventsWithScore == null) { eventsWithScore = new ArrayList<>(); userTopRecs.put(totalScore, eventsWithScore); } eventsWithScore.add(eventId); } saveRecsToDatastore(userId, userTopRecs); userPrefs.remove(userId); } datastore.delete(toDelete); } /** * Trains an ALSModel on the provided training dataset. * * @param path If specified, will save the model parameters at this path * @param training Will fit the model to this training dataset */ public static ALSModel trainModel(String path, Dataset<Row> training) throws IOException { ALS als = new ALS().setMaxIter(5).setUserCol("userId").setItemCol("eventId").setRatingCol("rating"); ALSModel model = als.fit(training); model.setColdStartStrategy("drop"); if (path != null) { model.write().overwrite().save(path); LOGGER.info("model saved at " + path); } return model; } /** Uses RMSE to evaluate a set of predicted data. */ public static double evaluatePredictions(Dataset<Row> predictions) { RegressionEvaluator evaluator = new RegressionEvaluator() .setMetricName("rmse") .setLabelCol("rating") .setPredictionCol("prediction"); return evaluator.evaluate(predictions); } /** * Constructs ratings dataframe. Also flushes outdated Interaction entities from datastore. * * @param users List of users that datastore is keeping track of. * @param events List of existing events that datastore is keeping track of. * @param toDelete Save list of keys to delete, if interaction entities need to be flushed. */ private static Dataset<Row> makeDataframeAndPreprocess( Set<Integer> users, Set<Integer> events, List<Key> toDelete) { Iterable<Entity> queriedInteractions = datastore .prepare(new Query("Interaction").addSort("timestamp", Query.SortDirection.DESCENDING)) .asIterable(); Iterator<Entity> itr = queriedInteractions.iterator(); int count = 0; List<EventRating> ratings = new ArrayList<>(); while (itr.hasNext() && count < UPPER_LIMIT) { Entity entity = itr.next(); // convert Entities to spark-friendly format EventRating rate = EventRating.parseEntity(entity); if (rate != null) { if (!users.contains(rate.getUserId()) || !events.contains(rate.getEventId())) { // delete interaction of user or event id is invalid toDelete.add(entity.getKey()); } else { count++; ratings.add(rate); } } else { // something wrong with this entry, delete it toDelete.add(entity.getKey()); } } // delete the oldest Interaction entries from datastore while (itr.hasNext()) { toDelete.add(itr.next().getKey()); } return spark.createDataFrame(ratings, EventRating.class); } /** Stores a recommendation datastore entry for the given user ID. */ private static void saveRecsToDatastore(String userId, Map<Double, List<Long>> recs) { List<Long> recsList = new ArrayList<>(); for (Double score : recs.keySet()) { for (Long l : recs.get(score)) { recsList.add(l); } } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key recKey = KeyFactory.createKey("Recommendation", userId); Entity recEntity = null; try { recEntity = datastore.get(recKey); } catch (EntityNotFoundException e) { recEntity = new Entity(recKey); } recEntity.setProperty("recs", recsList); datastore.put(recEntity); } public static class EventRating implements Serializable { private int userId; private int eventId; private float rating; private long timestamp; /** Creates an EventRating object. */ public EventRating(String userId, long eventId, float rating, long timestamp) { // all fields must be numeric this.userId = userId.hashCode(); // spark implicitly casts long to int otherwise this.eventId = (Long.toString(eventId)).hashCode(); this.rating = rating; this.timestamp = timestamp; } // need getters to work with spark.createDataFrame() public int getUserId() { return userId; } public int getEventId() { return eventId; } public float getRating() { return rating; } public long getTimestamp() { return timestamp; } /** Creates an EventRating object from an Interaction Entity. */ public static EventRating parseEntity(Entity entity) { if (!entity.getKind().equals("Interaction")) { return null; } Object userField = entity.getProperty("user"); Object eventField = entity.getProperty("event"); Object ratingField = entity.getProperty("rating"); Object timeField = entity.getProperty("timestamp"); if (userField == null || eventField == null || ratingField == null || timeField == null) { return null; } try { String userId = userField.toString(); long eventId = Long.parseLong(eventField.toString()); float rating = Float.parseFloat(ratingField.toString()); long timestamp = Long.parseLong(timeField.toString()); return new EventRating(userId, eventId, rating, timestamp); } catch (NumberFormatException e) { return null; } } public String toString() { return userId + " " + eventId + " " + rating + " " + timestamp; } } }
Decompose into helpers
src/main/java/com/google/sps/Recommend.java
Decompose into helpers
<ide><path>rc/main/java/com/google/sps/Recommend.java <ide> private static final double NO_INTERACTION = 1.5; <ide> private static final double ALREADY_VIEWED = 1.2; <ide> private static final double ALREADY_SAVED = 0.6; <add> private static final float ZERO = 0.1f; <ide> <ide> // comparator to sort doubles in descending order <ide> private static final Comparator<Double> SCORE_DESCENDING = <ide> private static SparkSession spark; <ide> private static DatastoreService datastore; <ide> <del> /** Initializes the SparkSession. */ <add> // keep track of ids and hashcodes -- spark requires numeric entries <add> private static Map<Integer, String> userIdHash = new HashMap<>(); <add> private static Map<Integer, Long> eventIdHash = new HashMap<>(); <add> <add> // keep track of metrics and location for each user and event <add> private static Map<String, Map<String, Float>> userPrefs = new HashMap<>(); <add> private static Map<Long, Map<String, Integer>> eventInfo = new HashMap<>(); <add> private static Map<String, String> userLocations = new HashMap<>(); <add> private static Map<Long, String> eventLocations = new HashMap<>(); <add> <add> /** Initializes the SparkSession, datastore, and other necessary items. */ <ide> private static void init() { <ide> if (spark == null) { <ide> spark = <ide> if (datastore == null) { <ide> datastore = DatastoreServiceFactory.getDatastoreService(); <ide> } <add> <add> userIdHash = new HashMap<>(); <add> eventIdHash = new HashMap<>(); <add> userPrefs = new HashMap<>(); <add> eventInfo = new HashMap<>(); <add> userLocations = new HashMap<>(); <add> eventLocations = new HashMap<>(); <ide> } <ide> <ide> /** Rebuilds recommendation model and calculates recommendations for users. */ <ide> public static void calculateRecommend() throws IOException { <ide> init(); <del> <del> // keep track of ids and hashcodes -- spark requires numeric entries <del> final Map<Integer, String> userIdHash = new HashMap<>(); <del> final Map<Integer, Long> eventIdHash = new HashMap<>(); <del> <del> // keep track of metrics and location for each user and event <del> final Map<String, Map<String, Float>> userPrefs = new HashMap<>(); <del> final Map<Long, Map<String, Integer>> eventInfo = new HashMap<>(); <del> final Map<String, String> userLocations = new HashMap<>(); <del> final Map<Long, String> eventLocations = new HashMap<>(); <del> <del> // get user entities with their preferences <del> Iterable<Entity> queriedUsers = datastore.prepare(new Query("User")).asIterable(); <del> for (Entity e : queriedUsers) { <del> String id = e.getKey().getName(); <del> userPrefs.put(id, Interactions.buildVectorForUser(e)); <del> userIdHash.put(id.hashCode(), id); <del> if (e.hasProperty("location")) { <del> String location = e.getProperty("location").toString(); <del> if (location.length() > 0) { <del> userLocations.put(id, location); <del> } <del> } <del> } <del> <del> // get event entities <del> Iterable<Entity> queriedEvents = datastore.prepare(new Query("Event")).asIterable(); <del> for (Entity e : queriedEvents) { <del> long id = e.getKey().getId(); <del> eventInfo.put(id, Interactions.buildVectorForEvent(e)); <del> eventIdHash.put((Long.toString(id)).hashCode(), id); <del> eventLocations.put(id, e.getProperty("address").toString()); <del> } <add> getInfoFromDatastore(); <ide> <ide> List<Key> toDelete = new ArrayList<>(); <ide> Dataset<Row> ratings = <ide> for (Row recRow : userRecsList) { <ide> String userId = userIdHash.get(recRow.getInt(0)); <ide> List<Row> predScores = recRow.getList(1); <del> Map<String, Float> userVector = userPrefs.get(userId); <del> String userLocation = userLocations.get(userId); <ide> <ide> Map<Double, List<Long>> userTopRecs = new TreeMap<>(SCORE_DESCENDING); <del> <ide> for (Row itemRow : predScores) { <ide> long eventId = eventIdHash.get(itemRow.getInt(0)); <ide> float predScore = itemRow.getFloat(1); <del> <del> // calculate score for this item <del> float dotProduct = Interactions.dotProduct(userVector, eventInfo.get(eventId)); <del> double totalScore = dotProduct * predScore; // todo: calculate <del> <del> // adjust scaling based on user's past interaction with event <del> Entity interactionEntity = Interactions.hasInteraction(userId, eventId); <del> if (interactionEntity == null) { <del> totalScore *= NO_INTERACTION; <del> } else { <del> float interactionScore = <del> Float.parseFloat(interactionEntity.getProperty("rating").toString()); <del> if (interactionScore >= Interactions.SAVE_SCORE) { <del> totalScore *= ALREADY_SAVED; <del> } else if (interactionScore == Interactions.VIEW_SCORE) { <del> totalScore *= ALREADY_VIEWED; <del> } <del> } <del> <del> // TODO: adjust scaling based on user's location, if location is saved <add> if (predScore == 0.0f) { <add> predScore = ZERO; <add> } <add> double totalScore = computeScore(userId, eventId, predScore); <ide> <ide> // add item to ranking <ide> List<Long> eventsWithScore = userTopRecs.get(totalScore); <ide> saveRecsToDatastore(userId, userTopRecs); <ide> userPrefs.remove(userId); <ide> } <add> <add> // handle users not accounted for by ALSModel <add> for (String userId : userPrefs.keySet()) {} <ide> <ide> datastore.delete(toDelete); <ide> } <ide> .setLabelCol("rating") <ide> .setPredictionCol("prediction"); <ide> return evaluator.evaluate(predictions); <add> } <add> <add> /** Queries datastore and populates data maps. */ <add> private static void getInfoFromDatastore() { <add> // get user entities with their preferences <add> Iterable<Entity> queriedUsers = datastore.prepare(new Query("User")).asIterable(); <add> for (Entity e : queriedUsers) { <add> String id = e.getKey().getName(); <add> userPrefs.put(id, Interactions.buildVectorForUser(e)); <add> userIdHash.put(id.hashCode(), id); <add> if (e.hasProperty("location")) { <add> String location = e.getProperty("location").toString(); <add> if (location.length() > 0) { <add> userLocations.put(id, location); <add> } <add> } <add> } <add> <add> // get event entities <add> Iterable<Entity> queriedEvents = datastore.prepare(new Query("Event")).asIterable(); <add> for (Entity e : queriedEvents) { <add> long id = e.getKey().getId(); <add> eventInfo.put(id, Interactions.buildVectorForEvent(e)); <add> eventIdHash.put((Long.toString(id)).hashCode(), id); <add> eventLocations.put(id, e.getProperty("address").toString()); <add> } <ide> } <ide> <ide> /** <ide> return spark.createDataFrame(ratings, EventRating.class); <ide> } <ide> <add> /** <add> * Computes cumulative total score for given user and event. <add> * <add> * @param predScore Base score to apply multipliers to. <add> */ <add> private static double computeScore(String userId, long eventId, float predScore) { <add> float dotProduct = Interactions.dotProduct(userPrefs.get(userId), eventInfo.get(eventId)); <add> double totalScore = dotProduct * predScore; <add> <add> // adjust scaling based on user's past interaction with event <add> Entity interactionEntity = Interactions.hasInteraction(userId, eventId); <add> if (interactionEntity == null) { <add> totalScore *= NO_INTERACTION; <add> } else { <add> float interactionScore = Float.parseFloat(interactionEntity.getProperty("rating").toString()); <add> if (interactionScore >= Interactions.SAVE_SCORE) { <add> totalScore *= ALREADY_SAVED; <add> } else if (interactionScore == Interactions.VIEW_SCORE) { <add> totalScore *= ALREADY_VIEWED; <add> } <add> } <add> <add> String userLocation = userLocations.get(userId); <add> if (userLocation != null) { <add> // TODO: scale based on location <add> } <add> <add> totalScore = Math.round(totalScore * 100.0) / 100.0; <add> return totalScore; <add> } <add> <ide> /** Stores a recommendation datastore entry for the given user ID. */ <ide> private static void saveRecsToDatastore(String userId, Map<Double, List<Long>> recs) { <ide> List<Long> recsList = new ArrayList<>();
Java
mit
73134417d3f5e8a5a17427f1200bcb912056939e
0
webarata3/benrippoi
package link.webarata3.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; public class BenriCell { private Cell cell; public BenriCell(Sheet sheet, int x, int y) { cell = BenrippoiUtil.getCell(sheet, x, y); } public BenriCell(Sheet sheet, String cellLabel) { cell = BenrippoiUtil.getCell(sheet, cellLabel); } public String toStr() { return BenrippoiUtil.cellToString(cell); } public int toInt() { return BenrippoiUtil.cellToInt(cell); } public double toDouble() { return BenrippoiUtil.cellToDouble(cell); } public boolean toBoolean() { return BenrippoiUtil.cellToBoolean(cell); } public LocalDate toLocalDate() { return BenrippoiUtil.cellToLocalDate(cell); } public LocalTime toLocalTime() { return BenrippoiUtil.cellToLocalTime(cell); } public LocalDateTime toLocalDateTime() { return BenrippoiUtil.cellToLocalDateTime(cell); } public void set(String value) { cell.setCellValue(value); } public void set(int value) { cell.setCellValue(value); } public void set(double value) { cell.setCellValue(value); } public void set(boolean value) { cell.setCellValue(value); } private Date localDataTimeToDate(LocalDateTime localDateTime) { ZoneId zone = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zone); Instant instant = zonedDateTime.toInstant(); return Date.from(instant); } public void set(LocalDate value) { Workbook wb = cell.getSheet().getWorkbook(); cell.setCellValue(localDataTimeToDate(value.atStartOfDay())); CreationHelper createHelper = wb.getCreationHelper(); CellStyle cellStyle = wb.createCellStyle(); short style = createHelper.createDataFormat().getFormat("yyyy/mm/dd"); cellStyle.setDataFormat(style); cell.setCellStyle(cellStyle); } public void set(LocalTime value) { Workbook wb = cell.getSheet().getWorkbook(); cell.setCellValue(localDataTimeToDate(value.atDate(LocalDate.of(1900, 1, 1)))); CreationHelper createHelper = wb.getCreationHelper(); CellStyle cellStyle = wb.createCellStyle(); short style = createHelper.createDataFormat().getFormat("hh:mm:ss"); cellStyle.setDataFormat(style); cell.setCellStyle(cellStyle); } public void set(LocalDateTime value) { Workbook wb = cell.getSheet().getWorkbook(); cell.setCellValue(localDataTimeToDate(value)); CreationHelper createHelper = wb.getCreationHelper(); CellStyle cellStyle = wb.createCellStyle(); short style = createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss"); cellStyle.setDataFormat(style); cell.setCellStyle(cellStyle); } }
src/main/java/link/webarata3/poi/BenriCell.java
package link.webarata3.poi; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; public class BenriCell { private Cell cell; public BenriCell(Sheet sheet, int x, int y) { cell = BenrippoiUtil.getCell(sheet, x, y); } public BenriCell(Sheet sheet, String cellLabel) { cell = BenrippoiUtil.getCell(sheet, cellLabel); } public String toStr() { return BenrippoiUtil.cellToString(cell); } public int toInt() { return BenrippoiUtil.cellToInt(cell); } public double toDouble() { return BenrippoiUtil.cellToDouble(cell); } public boolean toBoolean() { return BenrippoiUtil.cellToBoolean(cell); } public LocalDate toLocalDate() { return BenrippoiUtil.cellToLocalDate(cell); } public LocalTime toLocalTime() { return BenrippoiUtil.cellToLocalTime(cell); } public LocalDateTime toLocalDateTime() { return BenrippoiUtil.cellToLocalDateTime(cell); } public void set(String value) { cell.setCellValue(value); } public void set(int value) { cell.setCellValue(value); } public void set(double value) { cell.setCellValue(value); } public void set(boolean value) { cell.setCellValue(value); } private Date localDataTimeToDate(LocalDateTime localDateTime) { ZoneId zone = ZoneId.systemDefault(); ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zone); Instant instant = zonedDateTime.toInstant(); return Date.from(instant); } public void set(LocalDate value) { Workbook wb = cell.getSheet().getWorkbook(); cell.setCellValue(localDataTimeToDate(value.atStartOfDay())); CreationHelper createHelper = wb.getCreationHelper(); CellStyle cellStyle = wb.createCellStyle(); short style = createHelper.createDataFormat().getFormat("yyyy/MM/dd"); cellStyle.setDataFormat(style); cell.setCellStyle(cellStyle); } public void set(LocalTime value) { Workbook wb = cell.getSheet().getWorkbook(); cell.setCellValue(localDataTimeToDate(value.atDate(LocalDate.of(1900, 1, 1)))); CreationHelper createHelper = wb.getCreationHelper(); CellStyle cellStyle = wb.createCellStyle(); short style = createHelper.createDataFormat().getFormat("HH:mm:ss"); cellStyle.setDataFormat(style); cell.setCellStyle(cellStyle); } public void set(LocalDateTime value) { Workbook wb = cell.getSheet().getWorkbook(); cell.setCellValue(localDataTimeToDate(value)); CreationHelper createHelper = wb.getCreationHelper(); CellStyle cellStyle = wb.createCellStyle(); short style = createHelper.createDataFormat().getFormat("yyyy/MM/dd HH:mm:ss"); cellStyle.setDataFormat(style); cell.setCellStyle(cellStyle); } }
書式を正しく
src/main/java/link/webarata3/poi/BenriCell.java
書式を正しく
<ide><path>rc/main/java/link/webarata3/poi/BenriCell.java <ide> cell.setCellValue(localDataTimeToDate(value.atStartOfDay())); <ide> CreationHelper createHelper = wb.getCreationHelper(); <ide> CellStyle cellStyle = wb.createCellStyle(); <del> short style = createHelper.createDataFormat().getFormat("yyyy/MM/dd"); <add> short style = createHelper.createDataFormat().getFormat("yyyy/mm/dd"); <ide> cellStyle.setDataFormat(style); <ide> cell.setCellStyle(cellStyle); <ide> } <ide> cell.setCellValue(localDataTimeToDate(value.atDate(LocalDate.of(1900, 1, 1)))); <ide> CreationHelper createHelper = wb.getCreationHelper(); <ide> CellStyle cellStyle = wb.createCellStyle(); <del> short style = createHelper.createDataFormat().getFormat("HH:mm:ss"); <add> short style = createHelper.createDataFormat().getFormat("hh:mm:ss"); <ide> cellStyle.setDataFormat(style); <ide> cell.setCellStyle(cellStyle); <ide> } <ide> cell.setCellValue(localDataTimeToDate(value)); <ide> CreationHelper createHelper = wb.getCreationHelper(); <ide> CellStyle cellStyle = wb.createCellStyle(); <del> short style = createHelper.createDataFormat().getFormat("yyyy/MM/dd HH:mm:ss"); <add> short style = createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss"); <ide> cellStyle.setDataFormat(style); <ide> cell.setCellStyle(cellStyle); <ide> }
Java
mpl-2.0
2faa6f782e9ef0b5434fd295d1c2dd8dada65148
0
vga101/gaiasky,vga101/gaiasky,langurmonkey/gaiasky,langurmonkey/gaiasky,langurmonkey/gaiasky,langurmonkey/gaiasky,vga101/gaiasky,vga101/gaiasky
package gaia.cu9.ari.gaiaorbit.desktop.render; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.bitfire.postprocessing.PostProcessor; import com.bitfire.postprocessing.effects.Bloom; import com.bitfire.postprocessing.effects.Fxaa; import com.bitfire.postprocessing.effects.LensFlare2; import com.bitfire.postprocessing.effects.LightScattering; import com.bitfire.postprocessing.effects.MotionBlur; import com.bitfire.postprocessing.effects.Nfaa; import com.bitfire.utils.ShaderLoader; import gaia.cu9.ari.gaiaorbit.event.EventManager; import gaia.cu9.ari.gaiaorbit.event.Events; import gaia.cu9.ari.gaiaorbit.event.IObserver; import gaia.cu9.ari.gaiaorbit.render.IPostProcessor; import gaia.cu9.ari.gaiaorbit.util.Constants; import gaia.cu9.ari.gaiaorbit.util.GlobalConf; import gaia.cu9.ari.gaiaorbit.util.I18n; import gaia.cu9.ari.gaiaorbit.util.Logger; public class DesktopPostProcessor implements IPostProcessor, IObserver { private PostProcessBean[] pps; float bloomFboScale = 0.5f; float lensFboScale = 0.3f; float scatteringFboScale = 1.0f; public DesktopPostProcessor() { ShaderLoader.BasePath = "shaders/"; pps = new PostProcessBean[RenderType.values().length]; pps[RenderType.screen.index] = newPostProcessor(getWidth(RenderType.screen), getHeight(RenderType.screen)); if (Constants.desktop) { pps[RenderType.screenshot.index] = newPostProcessor(getWidth(RenderType.screenshot), getHeight(RenderType.screenshot)); pps[RenderType.frame.index] = newPostProcessor(getWidth(RenderType.frame), getHeight(RenderType.frame)); } // Output AA info. if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -1) { Logger.info(this.getClass().getSimpleName(), I18n.bundle.format("notif.selected", "FXAA")); } else if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -2) { Logger.info(this.getClass().getSimpleName(), I18n.bundle.format("notif.selected", "NFAA")); } EventManager.instance.subscribe(this, Events.PROPERTIES_WRITTEN, Events.BLOOM_CMD, Events.LENS_FLARE_CMD, Events.MOTION_BLUR_CMD, Events.LIGHT_POS_2D_UPDATED, Events.LIGHT_SCATTERING_CMD); } private int getWidth(RenderType type) { switch (type) { case screen: return Gdx.graphics.getWidth(); case screenshot: return GlobalConf.screenshot.SCREENSHOT_WIDTH; case frame: return GlobalConf.frame.RENDER_WIDTH; } return 0; } private int getHeight(RenderType type) { switch (type) { case screen: return Gdx.graphics.getHeight(); case screenshot: return GlobalConf.screenshot.SCREENSHOT_HEIGHT; case frame: return GlobalConf.frame.RENDER_HEIGHT; } return 0; } private PostProcessBean newPostProcessor(int width, int height) { PostProcessBean ppb = new PostProcessBean(); ppb.pp = new PostProcessor(width, height, true, false, true); // MOTION BLUR ppb.motionblur = new MotionBlur(); ppb.motionblur.setBlurOpacity(GlobalConf.postprocess.POSTPROCESS_MOTION_BLUR); ppb.motionblur.setEnabled(GlobalConf.postprocess.POSTPROCESS_MOTION_BLUR > 0); ppb.pp.addEffect(ppb.motionblur); // BLOOM ppb.bloom = new Bloom((int) (width * bloomFboScale), (int) (height * bloomFboScale)); ppb.bloom.setBloomIntesity(GlobalConf.postprocess.POSTPROCESS_BLOOM_INTENSITY); ppb.bloom.setThreshold(0f); ppb.bloom.setEnabled(GlobalConf.postprocess.POSTPROCESS_BLOOM_INTENSITY > 0); ppb.pp.addEffect(ppb.bloom); // LIGHT SCATTERING int nsamples; float density; if (GlobalConf.scene.isHighQuality()) { nsamples = 150; density = 1.4f; } else if (GlobalConf.scene.isNormalQuality()) { nsamples = 80; density = 0.96f; } else { nsamples = 40; density = .9f; } ppb.lscatter = new LightScattering((int) (width * scatteringFboScale), (int) (height * scatteringFboScale)); ppb.lscatter.setScatteringIntesity(1f); ppb.lscatter.setScatteringSaturation(1f); ppb.lscatter.setBaseIntesity(1f); ppb.lscatter.setBias(-0.999f); ppb.lscatter.setBlurAmount(4f); ppb.lscatter.setBlurPasses(2); ppb.lscatter.setDensity(density); ppb.lscatter.setNumSamples(nsamples); ppb.lscatter.setEnabled(GlobalConf.postprocess.POSTPROCESS_LIGHT_SCATTERING); ppb.pp.addEffect(ppb.lscatter); // LENS FLARE int nghosts; if (GlobalConf.scene.isHighQuality()) { nghosts = 10; } else if (GlobalConf.scene.isNormalQuality()) { nghosts = 8; } else { nghosts = 6; } ppb.lens = new LensFlare2((int) (width * lensFboScale), (int) (height * lensFboScale)); ppb.lens.setGhosts(nghosts); ppb.lens.setHaloWidth(0.8f); ppb.lens.setLensColorTexture(new Texture(Gdx.files.internal("img/lenscolor.png"))); ppb.lens.setFlareIntesity(0.6f); ppb.lens.setFlareSaturation(0.7f); ppb.lens.setBaseIntesity(1f); ppb.lens.setBias(-0.996f); ppb.lens.setBlurAmount(0.9f); ppb.lens.setBlurPasses(5); ppb.lens.setEnabled(GlobalConf.postprocess.POSTPROCESS_LENS_FLARE); ppb.pp.addEffect(ppb.lens); // ANTIALIAS if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -1) { ppb.antialiasing = new Fxaa(width, height); ((Fxaa) ppb.antialiasing).setSpanMax(4f); } else if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -2) { ppb.antialiasing = new Nfaa(width, height); } if (ppb.antialiasing != null) { ppb.antialiasing.setEnabled(GlobalConf.postprocess.POSTPROCESS_ANTIALIAS < 0); ppb.pp.addEffect(ppb.antialiasing); } return ppb; } @Override public PostProcessBean getPostProcessBean(RenderType type) { return pps[type.index]; } @Override public void resize(final int width, final int height) { if (pps[RenderType.screen.index].antialiasing != null) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { replace(RenderType.screen.index, width, height); } }); } } @Override public void notify(Events event, final Object... data) { switch (event) { case PROPERTIES_WRITTEN: if (pps != null) if (changed(pps[RenderType.screenshot.index].pp, GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.screenshot.SCREENSHOT_HEIGHT)) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { replace(RenderType.screenshot.index, GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.screenshot.SCREENSHOT_HEIGHT); } }); } if (pps != null) if (changed(pps[RenderType.frame.index].pp, GlobalConf.frame.RENDER_WIDTH, GlobalConf.frame.RENDER_HEIGHT)) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { replace(RenderType.frame.index, GlobalConf.frame.RENDER_WIDTH, GlobalConf.frame.RENDER_HEIGHT); } }); } break; case BLOOM_CMD: Gdx.app.postRunnable(new Runnable() { @Override public void run() { float intensity = (float) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.bloom.setBloomIntesity(intensity); ppb.bloom.setEnabled(intensity > 0); } } } }); break; case LENS_FLARE_CMD: boolean active = (Boolean) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.lens.setEnabled(active); } } break; case LIGHT_SCATTERING_CMD: active = (Boolean) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.lscatter.setEnabled(active); } } break; case CAMERA_MOTION_UPDATED: // rts = RenderType.values(); // float strength = (float) MathUtilsd.lint(((double) data[1] * // Constants.KM_TO_U * Constants.U_TO_PC), 0, 100, 0, 0.05); // for (int i = 0; i < rts.length; i++) { // pps[i].zoomer.setBlurStrength(strength); // } break; case MOTION_BLUR_CMD: Gdx.app.postRunnable(new Runnable() { @Override public void run() { float opacity = (float) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.motionblur.setBlurOpacity(opacity); ppb.motionblur.setEnabled(opacity > 0); } } } }); break; case LIGHT_POS_2D_UPDATED: Integer nLights = (Integer) data[0]; float[] lightpos = (float[]) data[1]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.lscatter.setLightPositions(nLights, lightpos); } } break; } } /** * Reloads the postprocessor at the given index with the given width and * height. * * @param index * @param width * @param height */ private void replace(int index, final int width, final int height) { // pps[index].pp.dispose(false); pps[index] = newPostProcessor(width, height); } private boolean changed(PostProcessor postProcess, int width, int height) { return postProcess.getCombinedBuffer().width != width || postProcess.getCombinedBuffer().height != height; } @Override public boolean isLightScatterEnabled() { return pps[RenderType.screen.index].lscatter.isEnabled(); } }
desktop/src/gaia/cu9/ari/gaiaorbit/desktop/render/DesktopPostProcessor.java
package gaia.cu9.ari.gaiaorbit.desktop.render; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.bitfire.postprocessing.PostProcessor; import com.bitfire.postprocessing.effects.Bloom; import com.bitfire.postprocessing.effects.Fxaa; import com.bitfire.postprocessing.effects.LensFlare2; import com.bitfire.postprocessing.effects.LightScattering; import com.bitfire.postprocessing.effects.MotionBlur; import com.bitfire.postprocessing.effects.Nfaa; import com.bitfire.utils.ShaderLoader; import gaia.cu9.ari.gaiaorbit.event.EventManager; import gaia.cu9.ari.gaiaorbit.event.Events; import gaia.cu9.ari.gaiaorbit.event.IObserver; import gaia.cu9.ari.gaiaorbit.render.IPostProcessor; import gaia.cu9.ari.gaiaorbit.util.Constants; import gaia.cu9.ari.gaiaorbit.util.GlobalConf; import gaia.cu9.ari.gaiaorbit.util.I18n; import gaia.cu9.ari.gaiaorbit.util.Logger; public class DesktopPostProcessor implements IPostProcessor, IObserver { private PostProcessBean[] pps; float bloomFboScale = 0.5f; float lensFboScale = 0.3f; float scatteringFboScale = 1.0f; public DesktopPostProcessor() { ShaderLoader.BasePath = "shaders/"; pps = new PostProcessBean[RenderType.values().length]; pps[RenderType.screen.index] = newPostProcessor(getWidth(RenderType.screen), getHeight(RenderType.screen)); if (Constants.desktop) { pps[RenderType.screenshot.index] = newPostProcessor(getWidth(RenderType.screenshot), getHeight(RenderType.screenshot)); pps[RenderType.frame.index] = newPostProcessor(getWidth(RenderType.frame), getHeight(RenderType.frame)); } // Output AA info. if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -1) { Logger.info(this.getClass().getSimpleName(), I18n.bundle.format("notif.selected", "FXAA")); } else if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -2) { Logger.info(this.getClass().getSimpleName(), I18n.bundle.format("notif.selected", "NFAA")); } EventManager.instance.subscribe(this, Events.PROPERTIES_WRITTEN, Events.BLOOM_CMD, Events.LENS_FLARE_CMD, Events.MOTION_BLUR_CMD, Events.LIGHT_POS_2D_UPDATED, Events.LIGHT_SCATTERING_CMD); } private int getWidth(RenderType type) { switch (type) { case screen: return Gdx.graphics.getWidth(); case screenshot: return GlobalConf.screenshot.SCREENSHOT_WIDTH; case frame: return GlobalConf.frame.RENDER_WIDTH; } return 0; } private int getHeight(RenderType type) { switch (type) { case screen: return Gdx.graphics.getHeight(); case screenshot: return GlobalConf.screenshot.SCREENSHOT_HEIGHT; case frame: return GlobalConf.frame.RENDER_HEIGHT; } return 0; } private PostProcessBean newPostProcessor(int width, int height) { PostProcessBean ppb = new PostProcessBean(); ppb.pp = new PostProcessor(width, height, true, false, true); // MOTION BLUR ppb.motionblur = new MotionBlur(); ppb.motionblur.setBlurOpacity(GlobalConf.postprocess.POSTPROCESS_MOTION_BLUR); ppb.motionblur.setEnabled(GlobalConf.postprocess.POSTPROCESS_MOTION_BLUR > 0); ppb.pp.addEffect(ppb.motionblur); // BLOOM ppb.bloom = new Bloom((int) (width * bloomFboScale), (int) (height * bloomFboScale)); ppb.bloom.setBloomIntesity(GlobalConf.postprocess.POSTPROCESS_BLOOM_INTENSITY); ppb.bloom.setThreshold(0f); ppb.bloom.setEnabled(GlobalConf.postprocess.POSTPROCESS_BLOOM_INTENSITY > 0); ppb.pp.addEffect(ppb.bloom); // LIGHT SCATTERING int nsamples; float density; if (GlobalConf.scene.isHighQuality()) { nsamples = 150; density = 1.4f; } else if (GlobalConf.scene.isNormalQuality()) { nsamples = 80; density = 0.96f; } else { nsamples = 40; density = .9f; } ppb.lscatter = new LightScattering((int) (width * scatteringFboScale), (int) (height * scatteringFboScale)); ppb.lscatter.setScatteringIntesity(1f); ppb.lscatter.setScatteringSaturation(1f); ppb.lscatter.setBaseIntesity(1f); ppb.lscatter.setBias(-0.999f); ppb.lscatter.setBlurAmount(4f); ppb.lscatter.setBlurPasses(2); ppb.lscatter.setDensity(density); ppb.lscatter.setNumSamples(nsamples); ppb.lscatter.setEnabled(GlobalConf.postprocess.POSTPROCESS_LIGHT_SCATTERING); ppb.pp.addEffect(ppb.lscatter); // LENS FLARE int nghosts; if (GlobalConf.scene.isHighQuality()) { nghosts = 10; } else if (GlobalConf.scene.isNormalQuality()) { nghosts = 8; } else { nghosts = 6; } ppb.lens = new LensFlare2((int) (width * lensFboScale), (int) (height * lensFboScale)); ppb.lens.setGhosts(nghosts); ppb.lens.setHaloWidth(0.8f); ppb.lens.setLensColorTexture(new Texture(Gdx.files.internal("img/lenscolor.png"))); ppb.lens.setFlareIntesity(0.6f); ppb.lens.setFlareSaturation(0.7f); ppb.lens.setBaseIntesity(1f); ppb.lens.setBias(-0.996f); ppb.lens.setBlurAmount(0.9f); ppb.lens.setBlurPasses(5); ppb.lens.setEnabled(GlobalConf.postprocess.POSTPROCESS_LENS_FLARE); ppb.pp.addEffect(ppb.lens); // ANTIALIAS if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -1) { ppb.antialiasing = new Fxaa(width, height); ((Fxaa) ppb.antialiasing).setSpanMax(6f); } else if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -2) { ppb.antialiasing = new Nfaa(width, height); } if (ppb.antialiasing != null) { ppb.antialiasing.setEnabled(GlobalConf.postprocess.POSTPROCESS_ANTIALIAS < 0); ppb.pp.addEffect(ppb.antialiasing); } return ppb; } @Override public PostProcessBean getPostProcessBean(RenderType type) { return pps[type.index]; } @Override public void resize(final int width, final int height) { if (pps[RenderType.screen.index].antialiasing != null) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { replace(RenderType.screen.index, width, height); } }); } } @Override public void notify(Events event, final Object... data) { switch (event) { case PROPERTIES_WRITTEN: if (pps != null) if (changed(pps[RenderType.screenshot.index].pp, GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.screenshot.SCREENSHOT_HEIGHT)) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { replace(RenderType.screenshot.index, GlobalConf.screenshot.SCREENSHOT_WIDTH, GlobalConf.screenshot.SCREENSHOT_HEIGHT); } }); } if (pps != null) if (changed(pps[RenderType.frame.index].pp, GlobalConf.frame.RENDER_WIDTH, GlobalConf.frame.RENDER_HEIGHT)) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { replace(RenderType.frame.index, GlobalConf.frame.RENDER_WIDTH, GlobalConf.frame.RENDER_HEIGHT); } }); } break; case BLOOM_CMD: Gdx.app.postRunnable(new Runnable() { @Override public void run() { float intensity = (float) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.bloom.setBloomIntesity(intensity); ppb.bloom.setEnabled(intensity > 0); } } } }); break; case LENS_FLARE_CMD: boolean active = (Boolean) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.lens.setEnabled(active); } } break; case LIGHT_SCATTERING_CMD: active = (Boolean) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.lscatter.setEnabled(active); } } break; case CAMERA_MOTION_UPDATED: // rts = RenderType.values(); // float strength = (float) MathUtilsd.lint(((double) data[1] * // Constants.KM_TO_U * Constants.U_TO_PC), 0, 100, 0, 0.05); // for (int i = 0; i < rts.length; i++) { // pps[i].zoomer.setBlurStrength(strength); // } break; case MOTION_BLUR_CMD: Gdx.app.postRunnable(new Runnable() { @Override public void run() { float opacity = (float) data[0]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.motionblur.setBlurOpacity(opacity); ppb.motionblur.setEnabled(opacity > 0); } } } }); break; case LIGHT_POS_2D_UPDATED: Integer nLights = (Integer) data[0]; float[] lightpos = (float[]) data[1]; for (int i = 0; i < RenderType.values().length; i++) { if (pps[i] != null) { PostProcessBean ppb = pps[i]; ppb.lscatter.setLightPositions(nLights, lightpos); } } break; } } /** * Reloads the postprocessor at the given index with the given width and * height. * * @param index * @param width * @param height */ private void replace(int index, final int width, final int height) { // pps[index].pp.dispose(false); pps[index] = newPostProcessor(width, height); } private boolean changed(PostProcessor postProcess, int width, int height) { return postProcess.getCombinedBuffer().width != width || postProcess.getCombinedBuffer().height != height; } @Override public boolean isLightScatterEnabled() { return pps[RenderType.screen.index].lscatter.isEnabled(); } }
FXAA span max reduced to 4
desktop/src/gaia/cu9/ari/gaiaorbit/desktop/render/DesktopPostProcessor.java
FXAA span max reduced to 4
<ide><path>esktop/src/gaia/cu9/ari/gaiaorbit/desktop/render/DesktopPostProcessor.java <ide> // ANTIALIAS <ide> if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -1) { <ide> ppb.antialiasing = new Fxaa(width, height); <del> ((Fxaa) ppb.antialiasing).setSpanMax(6f); <add> ((Fxaa) ppb.antialiasing).setSpanMax(4f); <ide> } else if (GlobalConf.postprocess.POSTPROCESS_ANTIALIAS == -2) { <ide> ppb.antialiasing = new Nfaa(width, height); <ide> }
Java
agpl-3.0
5a0f606dca09a348d1179b6998c35dffe4f06272
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
38dff116-2e61-11e5-9284-b827eb9e62be
hello.java
38da57d8-2e61-11e5-9284-b827eb9e62be
38dff116-2e61-11e5-9284-b827eb9e62be
hello.java
38dff116-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>38da57d8-2e61-11e5-9284-b827eb9e62be <add>38dff116-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
1adc8650c943239cfba4d05b55197e91486781db
0
joshuairl/toothchat-client,joshuairl/toothchat-client,joshuairl/toothchat-client,joshuairl/toothchat-client
/** * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Lesser Public License (LGPL), * a copy of which is included in this distribution. */ package org.jivesoftware.sparkplugin; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.jingle.JingleNegotiator; import org.jivesoftware.smackx.jingle.JingleSession; import org.jivesoftware.smackx.jingle.OutgoingJingleSession; import org.jivesoftware.smackx.jingle.listeners.JingleSessionListener; import org.jivesoftware.smackx.jingle.listeners.JingleSessionStateListener; import org.jivesoftware.smackx.jingle.media.PayloadType; import org.jivesoftware.smackx.jingle.nat.TransportCandidate; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.FileDragLabel; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomClosingListener; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.util.log.Log; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.applet.Applet; import java.applet.AudioClip; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.SimpleDateFormat; import java.util.Date; /** * Handles UI controls for outgoing jingle calls. */ public class OutgoingCall extends JPanel implements JingleSessionStateListener, JingleSessionListener, ChatRoomClosingListener { private FileDragLabel imageLabel = new FileDragLabel(); private JLabel titleLabel = new JLabel(); private JLabel fileLabel = new JLabel(); private CallButton cancelButton = new CallButton(); private JingleSession session; private JingleRoom jingleRoom; private AudioClip ringing; private ChatRoom chatRoom; /** * Creates a new instance of OutgoingCall. */ public OutgoingCall() { try { ringing = Applet.newAudioClip(JinglePhoneRes.getURL("RINGING")); } catch (Exception e) { Log.error(e); } setLayout(new GridBagLayout()); setBackground(new Color(250, 249, 242)); add(imageLabel, new GridBagConstraints(0, 0, 1, 3, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); add(titleLabel, new GridBagConstraints(1, 0, 2, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); titleLabel.setFont(new Font("Dialog", Font.BOLD, 11)); titleLabel.setForeground(new Color(211, 174, 102)); cancelButton.setText("Cancel"); add(cancelButton, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); cancelButton.setForeground(new Color(73, 113, 196)); cancelButton.setFont(new Font("Dialog", Font.BOLD, 11)); cancelButton.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(73, 113, 196))); setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.white)); } /** * Handles a new outgoing call. * * @param session the JingleSession for the outgoing call. * @param chatRoom the room the session is associated with. * @param jid the users jid. */ public void handleOutgoingCall(final JingleSession session, ChatRoom chatRoom, final String jid) { this.chatRoom = chatRoom; JingleStateManager.getInstance().addJingleSession(chatRoom, JingleStateManager.JingleRoomState.ringing); chatRoom.addClosingListener(this); session.addListener(this); cancelButton.setVisible(true); this.session = session; this.session.addStateListener(this); fileLabel.setText(jid); ContactList contactList = SparkManager.getWorkspace().getContactList(); ContactItem contactItem = contactList.getContactItemByJID(jid); titleLabel.setText("Outgoing Voice Chat To " + contactItem.getNickname()); cancelButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { cancel(); } public void mouseEntered(MouseEvent e) { cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(MouseEvent e) { cancelButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); makeClickable(imageLabel); makeClickable(titleLabel); // Notify state change SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); } /** * Updates the UI to reflect the current state. */ private void updateOutgoingCallPanel() { if (session == null || session.isClosed()) { return; } else if (session instanceof OutgoingJingleSession) { showAlert(false); if (session.getState() instanceof OutgoingJingleSession.Pending) { titleLabel.setText("Calling user. Please wait..."); cancelButton.setVisible(true); } } } /** * Called when the call has been answered. Will append the JingleRoom to the * associated ChatRoom. */ private void showCallAnsweredState() { final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm a"); titleLabel.setText("Voice chat started on " + formatter.format(new Date())); cancelButton.setVisible(false); if (ringing != null) { ringing.stop(); } jingleRoom = new JingleRoom(session, chatRoom); chatRoom.getChatPanel().add(jingleRoom, new GridBagConstraints(1, 1, 1, 1, 0.05, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); chatRoom.getChatPanel().invalidate(); chatRoom.getChatPanel().validate(); chatRoom.getChatPanel().repaint(); // Add state JingleStateManager.getInstance().addJingleSession(chatRoom, JingleStateManager.JingleRoomState.inJingleCall); // Notify state change SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); } /** * Called when the call has ended. */ private void showCallEndedState(boolean answered) { if (answered) { final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm a"); titleLabel.setText("Voice chat ended on " + formatter.format(new Date())); } else { titleLabel.setText("Voice chat was rejected."); } showAlert(true); cancelButton.setVisible(false); if (ringing != null) { ringing.stop(); } if (chatRoom != null && jingleRoom != null) { chatRoom.getChatPanel().remove(jingleRoom); chatRoom.getChatPanel().invalidate(); chatRoom.getChatPanel().validate(); chatRoom.getChatPanel().repaint(); } // Add state JingleStateManager.getInstance().removeJingleSession(chatRoom); // Notify state change SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); } private void makeClickable(final JComponent component) { component.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { component.setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(MouseEvent e) { component.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); } private class CallButton extends JButton { public CallButton() { decorate(); } /** * Create a new RolloverButton. * * @param text the button text. * @param icon the button icon. */ public CallButton(String text, Icon icon) { super(text, icon); decorate(); } /** * Decorates the button with the approriate UI configurations. */ private void decorate() { setBorderPainted(false); setOpaque(true); setContentAreaFilled(false); setMargin(new Insets(1, 1, 1, 1)); } } /** * Changes the background color. If alert is true, the background will reflect that the ui * needs attention. * * @param alert true to notify users that their attention is needed. */ private void showAlert(boolean alert) { if (alert) { titleLabel.setForeground(new Color(211, 174, 102)); setBackground(new Color(250, 249, 242)); } else { setBackground(new Color(239, 245, 250)); titleLabel.setForeground(new Color(65, 139, 179)); } } /** * Call to cancel phone conversation. */ public void cancel() { if (session != null) { try { session.terminate(); session = null; } catch (XMPPException e) { Log.error(e); } } } public void beforeChange(JingleNegotiator.State old, JingleNegotiator.State newOne) throws JingleNegotiator.JingleException { } public void afterChanged(JingleNegotiator.State old, JingleNegotiator.State newOne) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateOutgoingCallPanel(); } }); } public void closing() { try { session.terminate(); } catch (XMPPException e) { Log.error(e); } JingleStateManager.getInstance().removeJingleSession(chatRoom); } public void sessionEstablished(PayloadType payloadType, TransportCandidate transportCandidate, TransportCandidate transportCandidate1, JingleSession jingleSession) { showCallAnsweredState(); } public void sessionDeclined(String string, JingleSession jingleSession) { } public void sessionRedirected(String string, JingleSession jingleSession) { } public void sessionClosed(String string, JingleSession jingleSession) { if (jingleSession instanceof OutgoingJingleSession) { OutgoingJingleSession session = (OutgoingJingleSession)jingleSession; if (session.getState() instanceof OutgoingJingleSession.Active) { showCallEndedState(true); } else if (session.getState() instanceof OutgoingJingleSession.Pending) { showCallEndedState(false); } } } public void sessionClosedOnError(XMPPException xmppException, JingleSession jingleSession) { } }
src/plugins/jingle/src/java/org/jivesoftware/sparkplugin/OutgoingCall.java
/** * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Lesser Public License (LGPL), * a copy of which is included in this distribution. */ package org.jivesoftware.sparkplugin; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.jingle.IncomingJingleSession; import org.jivesoftware.smackx.jingle.JingleNegotiator; import org.jivesoftware.smackx.jingle.JingleSession; import org.jivesoftware.smackx.jingle.OutgoingJingleSession; import org.jivesoftware.smackx.jingle.listeners.JingleSessionListener; import org.jivesoftware.smackx.jingle.listeners.JingleSessionStateListener; import org.jivesoftware.smackx.jingle.media.PayloadType; import org.jivesoftware.smackx.jingle.nat.TransportCandidate; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.FileDragLabel; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomClosingListener; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.util.log.Log; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.applet.Applet; import java.applet.AudioClip; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Handles UI controls for outgoing jingle calls. */ public class OutgoingCall extends JPanel implements JingleSessionStateListener, JingleSessionListener, ChatRoomClosingListener { private FileDragLabel imageLabel = new FileDragLabel(); private JLabel titleLabel = new JLabel(); private JLabel fileLabel = new JLabel(); private CallButton cancelButton = new CallButton(); private CallButton answerButton = new CallButton(); private JingleNegotiator.State lastState; private JingleSession session; private AudioClip ringing; private boolean answered; private ChatRoom chatRoom; private Map<ChatRoom, JingleRoom> callMap = new HashMap<ChatRoom, JingleRoom>(); /** * Creates a new instance of OutgoingCall. */ public OutgoingCall() { try { ringing = Applet.newAudioClip(JinglePhoneRes.getURL("RINGING")); } catch (Exception e) { Log.error(e); } setLayout(new GridBagLayout()); setBackground(new Color(250, 249, 242)); add(imageLabel, new GridBagConstraints(0, 0, 1, 3, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); add(titleLabel, new GridBagConstraints(1, 0, 2, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); titleLabel.setFont(new Font("Dialog", Font.BOLD, 11)); titleLabel.setForeground(new Color(211, 174, 102)); cancelButton.setText("Cancel"); answerButton.setText("Answer"); add(answerButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); add(cancelButton, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); answerButton.setVisible(false); answerButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { answered = true; } }); cancelButton.setForeground(new Color(73, 113, 196)); cancelButton.setFont(new Font("Dialog", Font.BOLD, 11)); cancelButton.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(73, 113, 196))); answerButton.setForeground(new Color(73, 113, 196)); answerButton.setFont(new Font("Dialog", Font.BOLD, 11)); answerButton.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(73, 113, 196))); setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.white)); } /** * Handles a new outgoing call. * * @param session the JingleSession for the outgoing call. * @param chatRoom the room the session is associated with. * @param jid the users jid. */ public void handleOutgoingCall(final JingleSession session, ChatRoom chatRoom, final String jid) { this.chatRoom = chatRoom; JingleStateManager.getInstance().addJingleSession(chatRoom, JingleStateManager.JingleRoomState.ringing); chatRoom.addClosingListener(this); session.addListener(this); cancelButton.setVisible(true); this.session = session; this.session.addStateListener(this); fileLabel.setText(jid); ContactList contactList = SparkManager.getWorkspace().getContactList(); ContactItem contactItem = contactList.getContactItemByJID(jid); titleLabel.setText("Outgoing Voice Chat To " + contactItem.getNickname()); cancelButton.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { cancel(); } public void mouseEntered(MouseEvent e) { cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(MouseEvent e) { cancelButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); makeClickable(imageLabel); makeClickable(titleLabel); makeClickable(answerButton); // Notify state change SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); } /** * Updates the UI to reflect the current state. */ private void updateOutgoingCallPanel() { if (session == null || session.isClosed()) { return; } else if (session instanceof OutgoingJingleSession) { answerButton.setVisible(false); showAlert(false); if (session.getState() instanceof OutgoingJingleSession.Active) { showCallAnsweredState(); } else if (session.getState() instanceof OutgoingJingleSession.Pending) { titleLabel.setText("Calling user. Please wait..."); cancelButton.setVisible(true); } lastState = session.getState(); } } /** * Called when the call has been answered. Will append the JingleRoom to the * associated ChatRoom. */ private void showCallAnsweredState() { final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm a"); titleLabel.setText("Voice chat started on " + formatter.format(new Date())); cancelButton.setVisible(false); lastState = session.getState(); if (ringing != null) { ringing.stop(); } final JingleRoom jingleRoom = new JingleRoom(session, chatRoom); chatRoom.getChatPanel().add(jingleRoom, new GridBagConstraints(1, 1, 1, 1, 0.05, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); chatRoom.getChatPanel().invalidate(); chatRoom.getChatPanel().validate(); chatRoom.getChatPanel().repaint(); callMap.put(chatRoom, jingleRoom); // Add state JingleStateManager.getInstance().addJingleSession(chatRoom, JingleStateManager.JingleRoomState.inJingleCall); // Notify state change SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); } /** * Called when the call has ended. */ private void showCallEndedState(boolean answered) { if (answered) { final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm a"); titleLabel.setText("Voice chat ended on " + formatter.format(new Date())); } else { titleLabel.setText("Voice chat was rejected."); } showAlert(true); cancelButton.setVisible(false); answerButton.setVisible(false); if (ringing != null) { ringing.stop(); } if (chatRoom != null) { JingleRoom room = callMap.get(chatRoom); if (room != null) { chatRoom.getChatPanel().remove(room); } callMap.remove(chatRoom); chatRoom.getChatPanel().invalidate(); chatRoom.getChatPanel().validate(); chatRoom.getChatPanel().repaint(); } // Add state JingleStateManager.getInstance().removeJingleSession(chatRoom); // Notify state change SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); } private void makeClickable(final JComponent component) { component.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { component.setCursor(new Cursor(Cursor.HAND_CURSOR)); } public void mouseExited(MouseEvent e) { component.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); } private class CallButton extends JButton { public CallButton() { decorate(); } /** * Create a new RolloverButton. * * @param text the button text. * @param icon the button icon. */ public CallButton(String text, Icon icon) { super(text, icon); decorate(); } /** * Decorates the button with the approriate UI configurations. */ private void decorate() { setBorderPainted(false); setOpaque(true); setContentAreaFilled(false); setMargin(new Insets(1, 1, 1, 1)); } } /** * Changes the background color. If alert is true, the background will reflect that the ui * needs attention. * * @param alert true to notify users that their attention is needed. */ private void showAlert(boolean alert) { if (alert) { titleLabel.setForeground(new Color(211, 174, 102)); setBackground(new Color(250, 249, 242)); } else { setBackground(new Color(239, 245, 250)); titleLabel.setForeground(new Color(65, 139, 179)); } } /** * Call to cancel phone conversation. */ public void cancel() { if (session != null) { try { session.terminate(); session = null; } catch (XMPPException e) { Log.error(e); } } } public void beforeChange(JingleNegotiator.State old, JingleNegotiator.State newOne) throws JingleNegotiator.JingleException { if (newOne != null && newOne instanceof IncomingJingleSession.Active) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (lastState == null && ringing != null) { ringing.loop(); } } }); while (!answered && (session != null && !session.isClosed())) { try { Thread.sleep(50); } catch (InterruptedException e) { Log.error(e); } } if (!answered) { cancel(); throw new JingleNegotiator.JingleException("Not Accepted"); } } } public void afterChanged(JingleNegotiator.State old, JingleNegotiator.State newOne) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateOutgoingCallPanel(); } }); } public void closing() { try { session.terminate(); } catch (XMPPException e) { Log.error(e); } JingleStateManager.getInstance().removeJingleSession(chatRoom); } public void sessionEstablished(PayloadType payloadType, TransportCandidate transportCandidate, TransportCandidate transportCandidate1, JingleSession jingleSession) { } public void sessionDeclined(String string, JingleSession jingleSession) { } public void sessionRedirected(String string, JingleSession jingleSession) { } public void sessionClosed(String string, JingleSession jingleSession) { if (jingleSession instanceof OutgoingJingleSession) { OutgoingJingleSession session = (OutgoingJingleSession)jingleSession; if (session.getState() instanceof OutgoingJingleSession.Active) { showCallEndedState(true); } else if (session.getState() instanceof OutgoingJingleSession.Pending) { showCallEndedState(false); } } } public void sessionClosedOnError(XMPPException xmppException, JingleSession jingleSession) { } }
Continue working on Jingle. git-svn-id: f13e20fb8540f76a08799c0051229138c0279aa7@7709 b35dd754-fafc-0310-a699-88a17e54d16e
src/plugins/jingle/src/java/org/jivesoftware/sparkplugin/OutgoingCall.java
Continue working on Jingle.
<ide><path>rc/plugins/jingle/src/java/org/jivesoftware/sparkplugin/OutgoingCall.java <ide> package org.jivesoftware.sparkplugin; <ide> <ide> import org.jivesoftware.smack.XMPPException; <del>import org.jivesoftware.smackx.jingle.IncomingJingleSession; <ide> import org.jivesoftware.smackx.jingle.JingleNegotiator; <ide> import org.jivesoftware.smackx.jingle.JingleSession; <ide> import org.jivesoftware.smackx.jingle.OutgoingJingleSession; <ide> import java.awt.event.MouseEvent; <ide> import java.text.SimpleDateFormat; <ide> import java.util.Date; <del>import java.util.HashMap; <del>import java.util.Map; <ide> <ide> /** <ide> * Handles UI controls for outgoing jingle calls. <ide> private JLabel fileLabel = new JLabel(); <ide> <ide> private CallButton cancelButton = new CallButton(); <del> private CallButton answerButton = new CallButton(); <del> <del> private JingleNegotiator.State lastState; <add> <ide> private JingleSession session; <add> private JingleRoom jingleRoom; <ide> <ide> private AudioClip ringing; <ide> <del> private boolean answered; <del> <ide> private ChatRoom chatRoom; <del> <del> private Map<ChatRoom, JingleRoom> callMap = new HashMap<ChatRoom, JingleRoom>(); <ide> <ide> /** <ide> * Creates a new instance of OutgoingCall. <ide> titleLabel.setForeground(new Color(211, 174, 102)); <ide> <ide> cancelButton.setText("Cancel"); <del> answerButton.setText("Answer"); <del> <del> add(answerButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); <ide> add(cancelButton, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); <del> <del> answerButton.setVisible(false); <del> <del> answerButton.addMouseListener(new MouseAdapter() { <del> public void mousePressed(MouseEvent e) { <del> answered = true; <del> } <del> }); <del> <ide> <ide> cancelButton.setForeground(new Color(73, 113, 196)); <ide> cancelButton.setFont(new Font("Dialog", Font.BOLD, 11)); <ide> cancelButton.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(73, 113, 196))); <del> <del> answerButton.setForeground(new Color(73, 113, 196)); <del> answerButton.setFont(new Font("Dialog", Font.BOLD, 11)); <del> answerButton.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(73, 113, 196))); <ide> <ide> setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.white)); <ide> } <ide> <ide> makeClickable(imageLabel); <ide> makeClickable(titleLabel); <del> makeClickable(answerButton); <ide> <ide> // Notify state change <ide> SparkManager.getChatManager().notifySparkTabHandlers(chatRoom); <ide> return; <ide> } <ide> else if (session instanceof OutgoingJingleSession) { <del> answerButton.setVisible(false); <ide> showAlert(false); <del> if (session.getState() instanceof OutgoingJingleSession.Active) { <del> showCallAnsweredState(); <del> } <del> else if (session.getState() instanceof OutgoingJingleSession.Pending) { <add> if (session.getState() instanceof OutgoingJingleSession.Pending) { <ide> titleLabel.setText("Calling user. Please wait..."); <ide> cancelButton.setVisible(true); <ide> } <del> lastState = session.getState(); <ide> } <ide> } <ide> <ide> final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy h:mm a"); <ide> titleLabel.setText("Voice chat started on " + formatter.format(new Date())); <ide> cancelButton.setVisible(false); <del> lastState = session.getState(); <ide> if (ringing != null) { <ide> ringing.stop(); <ide> } <ide> <del> final JingleRoom jingleRoom = new JingleRoom(session, chatRoom); <add> jingleRoom = new JingleRoom(session, chatRoom); <ide> chatRoom.getChatPanel().add(jingleRoom, new GridBagConstraints(1, 1, 1, 1, 0.05, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0)); <ide> chatRoom.getChatPanel().invalidate(); <ide> chatRoom.getChatPanel().validate(); <ide> chatRoom.getChatPanel().repaint(); <del> callMap.put(chatRoom, jingleRoom); <ide> <ide> // Add state <ide> JingleStateManager.getInstance().addJingleSession(chatRoom, JingleStateManager.JingleRoomState.inJingleCall); <ide> <ide> showAlert(true); <ide> cancelButton.setVisible(false); <del> answerButton.setVisible(false); <ide> if (ringing != null) { <ide> ringing.stop(); <ide> } <ide> <del> if (chatRoom != null) { <del> JingleRoom room = callMap.get(chatRoom); <del> if (room != null) { <del> chatRoom.getChatPanel().remove(room); <del> } <del> <del> callMap.remove(chatRoom); <add> if (chatRoom != null && jingleRoom != null) { <add> chatRoom.getChatPanel().remove(jingleRoom); <ide> chatRoom.getChatPanel().invalidate(); <ide> chatRoom.getChatPanel().validate(); <ide> chatRoom.getChatPanel().repaint(); <ide> } <ide> <ide> public void beforeChange(JingleNegotiator.State old, JingleNegotiator.State newOne) throws JingleNegotiator.JingleException { <del> if (newOne != null && newOne instanceof IncomingJingleSession.Active) { <del> SwingUtilities.invokeLater(new Runnable() { <del> public void run() { <del> if (lastState == null && ringing != null) { <del> ringing.loop(); <del> } <del> } <del> }); <del> <del> while (!answered && (session != null && !session.isClosed())) { <del> try { <del> Thread.sleep(50); <del> } <del> catch (InterruptedException e) { <del> Log.error(e); <del> } <del> } <del> if (!answered) { <del> cancel(); <del> throw new JingleNegotiator.JingleException("Not Accepted"); <del> } <del> } <del> <ide> <ide> } <ide> <ide> } <ide> <ide> public void sessionEstablished(PayloadType payloadType, TransportCandidate transportCandidate, TransportCandidate transportCandidate1, JingleSession jingleSession) { <add> showCallAnsweredState(); <ide> } <ide> <ide> public void sessionDeclined(String string, JingleSession jingleSession) {
Java
epl-1.0
51840031ff6c0fe952cf40a164b46e46bb780f72
0
Jenna3715/ChatBot
package utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.script.ScriptException; import chat.bot.ChatBot; import static utils.WebRequest.GET; public class Utils { private Utils(){} public static String eval(String input) { return eval2(input);/* try{ String response = GET("http://www4c.wolframalpha.com/input/json.jsp?"+ "output=JSON&includepodid=Result&format=image,plaintext&"+ "input="+urlencode(input)); String result = getStringValueJSON("plaintext", response) if(result.isEmpty()) { result = getStringValueJSON("src", response); if(result.isEmpty()) throw new IllegalArgumentException("No valid data to display: "+response); } return result; } catch(Exception e) { if(!e.getClass().equals(IllegalArgumentException.class)) e.printStackTrace(); //TODO return "I do not understand."; }*/ } private static String eval2(final String query) { String response = null; try { final String input = urlencode(query); final String inputurl = "http://www.wolframalpha.com/input/?i="+input; GET(inputurl); GET("http://www.wolframalpha.com/input/cookietest.jsp"); final String proxycode = getStringValueJSON("code", GET("https://www.wolframalpha.com/input/api/v1/code?" +System.currentTimeMillis()*1000)); HttpURLConnection connection = WebRequest.request(new URL("" +"https://www.wolframalpha.com/input/json.jsp" +"?async=false" +"&banners=raw" +"&debuggingdata=false" +"&format=image,plaintext" +"&formattimeout=16" +"&input="+input +"&output=JSON" +"&parsetimeout=10" +"&proxycode="+proxycode +"&scantimeout=1" +"&sponsorcategories=false" +"&statemethod=deploybutton" +"&storesubpodexprs=true")); connection.setRequestProperty("Host", "https://www.wolframalpha.com"); connection.setRequestProperty("Origin", "https://www.wolframalpha.com"); connection.setRequestProperty("Referer", inputurl); connection.setRequestMethod("GET"); response = WebRequest.read(connection); return parseResponse(response); } catch(IOException e) { e.printStackTrace(); return "I do not understand."; } catch(ScriptException | NullPointerException e) { // TODO Auto-generated catch block if(response!=null) { System.err.println("Failed to parse JSON:\n"+response); } e.printStackTrace(); return "Failed to parse response"; } } private static String parseResponse(String response) throws ScriptException, NullPointerException { if(response.matches("\\s*")) return ""; if(containsRegex("\"error\"\\s*:\\s*true",response)) //if(response.contains("\"error\" : true")) return "I encountered an error while processing your request."; if(containsRegex("\"success\"\\s*:\\s*false",response)) //if(response.contains("\"success\" : false")) return "I do not understand."; String jscmd = "var regex = /.*=image\\/([^&]*).*/g;\n" + "var httpsregex = /[^\\/]+\\/\\/.*/g;\n" + "var htsec = \"https:\";" + "var subst = \"&=.$1\";\n"//\u0060$0&=$1\u0060;\n" + "var pods="+response+".queryresult.pods;" + "for(var i=0;i<pods.length;++i){" + " if(pods[i].title==\"Result\" || pods[i].title==\"Response\"){" + " JSON.stringify(pods[i].subpods[0]);" + " /*var src = pods[i].subpods[0].img.src;" + " if(pods[i].subpods[0].plaintext==\"\"){ "// + " var msg = (src.match(regex) ? src.replace(regex, src+subst) : src);" + " (msg.match(httpsregex) ? msg : htsec+msg);" + " }else{" + " pods[i].subpods[0].plaintext;" + " }*/" + " }" + "}"; javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("js"); Object r = engine.eval(jscmd); String rawjson = (r==null ? "" : r.toString()); String plaintext = getStringValueJSON("plaintext", rawjson); String result = (plaintext.isEmpty() ? getStringValueJSON("src", rawjson) : plaintext) .replaceAll("\\\\n", "\n").replace("Wolfram|Alpha", ChatBot.getMyUserName()).replaceAll("Stephen Wolfram and his team", "somebody"); return result; } public static boolean containsRegex(String regex, String in) { return Pattern.compile(regex).matcher(in).find(); } private static HashMap<String, Matcher> jsonmatchers = new HashMap<>(); /** * * @param regex * @param in * @return The match in <code>in</code> for the first group in <code>regex</code>. * @throws IllegalArgumentException If no match was found or if there is no capturing group in the regex */ public static String search(String regex, String in) { try { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(in); m.find(); return m.group(1); } catch(Exception e) { throw new IllegalArgumentException(e); } } private static String searchJSON(String regex, String input){ Matcher m; if(!jsonmatchers.containsKey(regex)) { jsonmatchers.put(regex, m=Pattern.compile(regex).matcher(input)); } else { m = jsonmatchers.get(regex); m.reset(input); } m.find(); return m.group(1); } public static String urlencode(String text) { try { return URLEncoder.encode(text, "UTF-8"); } catch(UnsupportedEncodingException e) { throw new InternalError(e); } } public static String urlencode(String[] singlemap) { return urlencode(new String[][]{singlemap}); } public static String urlencode(String[][] map) { try { String encoded = ""; for(int i=0;i<map.length;++i){ String[] parmap = map[i]; if(parmap.length!=2) throw new IllegalArgumentException("Invalid parameter mapping "+java.util.Arrays.deepToString(parmap)); encoded += parmap[0] + "=" + URLEncoder.encode(parmap[1], "UTF-8") + (i+1<map.length ? "&" : ""); } return encoded; } catch(UnsupportedEncodingException e) { throw new InternalError(e); } } public static boolean getBooleanValueJSON(String parname, String rawjson) { try{ return Boolean.parseBoolean(searchJSON("\""+parname+"\":(?i)(true|false|null)", rawjson)); }catch(Exception e){ try{ return Boolean.parseBoolean(searchJSON("\'"+parname+"\':(?i)(true|false|null)", rawjson)); }catch(Exception e2){ String s = getStringValueJSON(parname, rawjson); return s.isEmpty() ? false : Boolean.parseBoolean(s); } } } public static long getNumValueJSON(String parname, String rawjson) { try{ return Long.parseLong(searchJSON("\""+parname+"\":(\\d*)", rawjson)); }catch(Exception e){ try{ return Long.parseLong(searchJSON("\'"+parname+"\':(\\d*)", rawjson)); }catch(Exception e2){ //String s = getStringValueJSON(parname, rawjson); return 0; } } } public static String getStringValueJSON(String parname, String rawjson) { String match = ""; char QUOTE = '\"'; int startindex = rawjson.indexOf(QUOTE+parname+QUOTE+':'); if(startindex<0) try{ return searchJSON("\""+parname+"\"\\s*:\\s*\"(([^\\\\\"]*(\\\\.)?)*)\"", rawjson); }catch(Exception e){ try{ return searchJSON("\""+parname+"\"\\\\s*:\\\\s*\'(([^\\\\\']*(\\\\.)?)*)\'", rawjson); }catch(Exception e2){ try{ return searchJSON("\'"+parname+"\'\\\\s*:\\\\s*\"(([^\\\\\"]*(\\\\.)?)*)\"", rawjson); }catch(Exception e3){ try{ return searchJSON("\'"+parname+"\'\\\\s*:\\\\s*\'(([^\\\\\']*(\\\\.)?)*)\'", rawjson); }catch(Exception e4){ return ""; } } } } int index = startindex+parname.length()+3; boolean escapenext = false; char nextchar=rawjson.charAt(++index); try{ while(nextchar!=QUOTE || escapenext){ escapenext=false; match+=nextchar; if(nextchar=='\\' && !escapenext) escapenext=true; nextchar=rawjson.charAt(++index); } }catch(Exception e){ System.err.println("Partial: "+match); e.printStackTrace(); } return match; } private static Matcher unicodematcher = Pattern.compile("\\\\u(....)").matcher(""); private static String replaceUnicodeEscapes(String text) { unicodematcher.reset(text); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); while(unicodematcher.find()) { String match = unicodematcher.group(1); text=text.replaceAll("\\\\u"+match, ""+((char)Integer.parseUnsignedInt(match, 16))); unicodematcher.reset(text); } Thread.currentThread().setPriority(Thread.NORM_PRIORITY); return text; } private static Matcher htmlescapematcher = Pattern.compile("\\&\\#(x?[A-Fa-f0-9]+);").matcher(""); private static String replaceHtmlEscapes(String text) { htmlescapematcher.reset(text); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); while(htmlescapematcher.find()) { String match = htmlescapematcher.group(1); text=text.replaceAll("&#"+match+";", ""+((char)Integer.parseUnsignedInt(match, match.startsWith("x")?16:10))); } Thread.currentThread().setPriority(Thread.NORM_PRIORITY); return text; } private static String replaceAllAll(String target, String[][] rr) { for(String[] r : rr) target=target.replaceAll(r[0], r[1]); return target; } /** * @see <a href="https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML"> * List of XML and HTML character entity references - Wikipedia</a> */ private static final String[][] replacementRegexes = { {"</?b>","**"}, {"</?strong>","**"}, {"</?i>","*"}, {"</?em>","*"}, {"</?strike>","---"},//Note: The <strike> tag is not supported in HTML5 {"</?del>","---"}, {"</?s>","---"}, {"\\\\\"","\""}, {"\\\\\'","\'"}, {"<\\/?code>","\u0060"}, }; private static final Matcher htmllinkmatcher = Pattern.compile("<a\\s+.*href=\"([^\"]+)\"(?>\\s+title=\"([^\"]+)\")?[^>]*>(.*)<\\/a>").matcher(""); public static String unescapeHtml(String text) { if(text==null) return ""; text = replaceAllAll( replaceAllAll( replaceHtmlEscapes( replaceUnicodeEscapes( text.replaceAll("&zwnj;&#8203;", ""))), replacementRegexes), htmlCharacterEntityReferences); return text; } public static String makeLinksMarkdown(String text) { if(text==null) return ""; htmllinkmatcher.reset(text); while(htmllinkmatcher.find()){ String optional = htmllinkmatcher.group(2); String replacement = "["+htmllinkmatcher.group(3)+"]("+ htmllinkmatcher.group(1)+(optional!=null?(" \""+optional+"\""):"")+")"; text=text.replace(htmllinkmatcher.group(), replacement); } return text; } private static final SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS"); static{ //new java.util.SimpleTimeZone(rawOffset, ID, startMonth, startDay, startDayOfWeek, startTime, startTimeMode, endMonth, endDay, endDayOfWeek, endTime, endTimeMode, dstSavings) dtf.setTimeZone(TimeZone.getDefault()); } public static String getDateTime(){ return dtf.format(System.currentTimeMillis()); } public static Long[] parseLongs(String str) { String[] strs = str.split("[, ;]"); Long[] vals = new Long[strs.length]; for(int i=0;i<strs.length;++i) vals[i]=new Long(strs[i]); return vals; } private static final String wotdFeedUrl = "http://www.dictionary.com/wordoftheday/wotd.rss"; private static final Matcher wotdMatcher = Pattern.compile("(?is)<item>.*?<link>(.*?)<\\/link>.*?<description>(.*?)<\\/description>.*?<\\/item>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(""); public static String getWotd(){ try { String text = GET(wotdFeedUrl); wotdMatcher.reset(text); wotdMatcher.find(); String output = "["+wotdMatcher.group(2)+"]("+wotdMatcher.group(1)+")"; return output; } catch(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } private static String[][] htmlCharacterEntityReferences = { //And here is the long list of html character entity references //See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references {"&quot;", "\""}, {"&amp;", "&"}, {"&apos;", "\'"}, {"&lt;", "<"}, {"&gt;", ">"}, {"&nbsp;", "\u00A0"}, {"&iexcl;", "\u00A1"}, {"&cent;", "\u00A2"}, {"&pound;", "\u00A3"}, {"&curren;", "\u00A4"}, {"&yen;", "\u00A5"}, {"&brvbar;", "\u00A6"}, {"&sect;", "\u00A7"}, {"&uml;", "\u00A8"}, {"&copy;", "\u00A9"}, {"&ordf;", "\u00AA"}, {"&laquo;", "\u00AB"}, {"&not;", "\u00AC"}, {"&shy;", "\u00AD"}, {"&reg;", "\u00AE"}, {"&macr;", "\u00AF"}, {"&deg;", "\u00B0"}, {"&plusmn;", "\u00B1"}, {"&sup2;", "\u00B2"}, {"&sup3;", "\u00B3"}, {"&acute;", "\u00B4"}, {"&micro;", "\u00B5"}, {"&para;", "\u00B6"}, {"&middot;", "\u00B7"}, {"&cedil;", "\u00B8"}, {"&sup1;", "\u00B9"}, {"&ordm;", "\u00BA"}, {"&raquo;", "\u00BB"}, {"&frac14;", "\u00BC"}, {"&frac12;", "\u00BD"}, {"&frac34;", "\u00BE"}, {"&iquest;", "\u00BF"}, {"&Agrave;", "\u00C0"}, {"&Aacute;", "\u00C1"}, {"&Acirc;", "\u00C2"}, {"&Atilde;", "\u00C3"}, {"&Auml;", "\u00C4"}, {"&Aring;", "\u00C5"}, {"&AElig;", "\u00C6"}, {"&Ccedil;", "\u00C7"}, {"&Egrave;", "\u00C8"}, {"&Eacute;", "\u00C9"}, {"&Ecirc;", "\u00CA"}, {"&Euml;", "\u00CB"}, {"&Igrave;", "\u00CC"}, {"&Iacute;", "\u00CD"}, {"&Icirc;", "\u00CE"}, {"&Iuml;", "\u00CF"}, {"&ETH;", "\u00D0"}, {"&Ntilde;", "\u00D1"}, {"&Ograve;", "\u00D2"}, {"&Oacute;", "\u00D3"}, {"&Ocirc;", "\u00D4"}, {"&Otilde;", "\u00D5"}, {"&Ouml;", "\u00D6"}, {"&times;", "\u00D7"}, {"&Oslash;", "\u00D8"}, {"&Ugrave;", "\u00D9"}, {"&Uacute;", "\u00DA"}, {"&Ucirc;", "\u00DB"}, {"&Uuml;", "\u00DC"}, {"&Yacute;", "\u00DD"}, {"&THORN;", "\u00DE"}, {"&szlig;", "\u00DF"}, {"&agrave;", "\u00E0"}, {"&aacute;", "\u00E1"}, {"&acirc;", "\u00E2"}, {"&atilde;", "\u00E3"}, {"&auml;", "\u00E4"}, {"&aring;", "\u00E5"}, {"&aelig;", "\u00E6"}, {"&ccedil;", "\u00E7"}, {"&egrave;", "\u00E8"}, {"&eacute;", "\u00E9"}, {"&ecirc;", "\u00EA"}, {"&euml;", "\u00EB"}, {"&igrave;", "\u00EC"}, {"&iacute;", "\u00ED"}, {"&icirc;", "\u00EE"}, {"&iuml;", "\u00EF"}, {"&eth;", "\u00F0"}, {"&ntilde;", "\u00F1"}, {"&ograve;", "\u00F2"}, {"&oacute;", "\u00F3"}, {"&ocirc;", "\u00F4"}, {"&otilde;", "\u00F5"}, {"&ouml;", "\u00F6"}, {"&divide;", "\u00F7"}, {"&oslash;", "\u00F8"}, {"&ugrave;", "\u00F9"}, {"&uacute;", "\u00FA"}, {"&ucirc;", "\u00FB"}, {"&uuml;", "\u00FC"}, {"&yacute;", "\u00FD"}, {"&thorn;", "\u00FE"}, {"&yuml;", "\u00FF"}, {"&OElig;", "\u0152"}, {"&oelig;", "\u0153"}, {"&Scaron;", "\u0160"}, {"&scaron;", "\u0161"}, {"&Yuml;", "\u0178"}, {"&fnof;", "\u0192"}, {"&circ;", "\u02C6"}, {"&tilde;", "\u02DC"}, {"&Alpha;", "\u0391"}, {"&Beta;", "\u0392"}, {"&Gamma;", "\u0393"}, {"&Delta;", "\u0394"}, {"&Epsilon;", "\u0395"}, {"&Zeta;", "\u0396"}, {"&Eta;", "\u0397"}, {"&Theta;", "\u0398"}, {"&Iota;", "\u0399"}, {"&Kappa;", "\u039A"}, {"&Lambda;", "\u039B"}, {"&Mu;", "\u039C"}, {"&Nu;", "\u039D"}, {"&Xi;", "\u039E"}, {"&Omicron;", "\u039F"}, {"&Pi;", "\u03A0"}, {"&Rho;", "\u03A1"}, {"&Sigma;", "\u03A3"}, {"&Tau;", "\u03A4"}, {"&Upsilon;", "\u03A5"}, {"&Phi;", "\u03A6"}, {"&Chi;", "\u03A7"}, {"&Psi;", "\u03A8"}, {"&Omega;", "\u03A9"}, {"&alpha;", "\u03B1"}, {"&beta;", "\u03B2"}, {"&gamma;", "\u03B3"}, {"&delta;", "\u03B4"}, {"&epsilon;", "\u03B5"}, {"&zeta;", "\u03B6"}, {"&eta;", "\u03B7"}, {"&theta;", "\u03B8"}, {"&iota;", "\u03B9"}, {"&kappa;", "\u03BA"}, {"&lambda;", "\u03BB"}, {"&mu;", "\u03BC"}, {"&nu;", "\u03BD"}, {"&xi;", "\u03BE"}, {"&omicron;", "\u03BF"}, {"&pi;", "\u03C0"}, {"&rho;", "\u03C1"}, {"&sigmaf;", "\u03C2"}, {"&sigma;", "\u03C3"}, {"&tau;", "\u03C4"}, {"&upsilon;", "\u03C5"}, {"&phi;", "\u03C6"}, {"&chi;", "\u03C7"}, {"&psi;", "\u03C8"}, {"&omega;", "\u03C9"}, {"&thetasym;", "\u03D1"}, {"&upsih;", "\u03D2"}, {"&piv;", "\u03D6"}, {"&ensp;", "\u2002"}, {"&emsp;", "\u2003"}, {"&thinsp;", "\u2009"}, {"&zwnj;", "\u200C"}, {"&zwj;", "\u200D"}, {"&lrm;", "\u200E"}, {"&rlm;", "\u200F"}, {"&ndash;", "\u2013"}, {"&mdash;", "\u2014"}, {"&lsquo;", "\u2018"}, {"&rsquo;", "\u2019"}, {"&sbquo;", "\u201A"}, {"&ldquo;", "\u201C"}, {"&rdquo;", "\u201D"}, {"&bdquo;", "\u201E"}, {"&dagger;", "\u2020"}, {"&Dagger;", "\u2021"}, {"&bull;", "\u2022"}, {"&hellip;", "\u2026"}, {"&permil;", "\u2030"}, {"&prime;", "\u2032"}, {"&Prime;", "\u2033"}, {"&lsaquo;", "\u2039"}, {"&rsaquo;", "\u203A"}, {"&oline;", "\u203E"}, {"&frasl;", "\u2044"}, {"&euro;", "\u20AC"}, {"&image;", "\u2111"}, {"&weierp;", "\u2118"}, {"&real;", "\u211C"}, {"&trade;", "\u2122"}, {"&alefsym;", "\u2135"}, {"&larr;", "\u2190"}, {"&uarr;", "\u2191"}, {"&rarr;", "\u2192"}, {"&darr;", "\u2193"}, {"&harr;", "\u2194"}, {"&crarr;", "\u21B5"}, {"&lArr;", "\u21D0"}, {"&uArr;", "\u21D1"}, {"&rArr;", "\u21D2"}, {"&dArr;", "\u21D3"}, {"&hArr;", "\u21D4"}, {"&forall;", "\u2200"}, {"&part;", "\u2202"}, {"&exist;", "\u2203"}, {"&empty;", "\u2205"}, {"&nabla;", "\u2207"}, {"&isin;", "\u2208"}, {"&notin;", "\u2209"}, {"&ni;", "\u220B"}, {"&prod;", "\u220F"}, {"&sum;", "\u2211"}, {"&minus;", "\u2212"}, {"&lowast;", "\u2217"}, {"&radic;", "\u221A"}, {"&prop;", "\u221D"}, {"&infin;", "\u221E"}, {"&ang;", "\u2220"}, {"&and;", "\u2227"}, {"&or;", "\u2228"}, {"&cap;", "\u2229"}, {"&cup;", "\u222A"}, {"&int;", "\u222B"}, {"&there4;", "\u2234"}, {"&sim;", "\u223C"}, {"&cong;", "\u2245"}, {"&asymp;", "\u2248"}, {"&ne;", "\u2260"}, {"&equiv;", "\u2261"}, {"&le;", "\u2264"}, {"&ge;", "\u2265"}, {"&sub;", "\u2282"}, {"&sup;", "\u2283"}, {"&nsub;", "\u2284"}, {"&sube;", "\u2286"}, {"&supe;", "\u2287"}, {"&oplus;", "\u2295"}, {"&otimes;", "\u2297"}, {"&perp;", "\u22A5"}, {"&sdot;", "\u22C5"}, {"&lceil;", "\u2308"}, {"&rceil;", "\u2309"}, {"&lfloor;", "\u230A"}, {"&rfloor;", "\u230B"}, {"&lang;", "\u2329"}, {"&rang;", "\u232A"}, {"&loz;", "\u25CA"}, {"&spades;", "\u2660"}, {"&clubs;", "\u2663"}, {"&hearts;", "\u2665"}, {"&diams;", "\u2666"} }; }
src/utils/Utils.java
package utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.script.ScriptException; import chat.bot.ChatBot; import static utils.WebRequest.GET; public class Utils { private Utils(){} public static String eval(String input) { return eval2(input);/* try{ String response = GET("http://www4c.wolframalpha.com/input/json.jsp?"+ "output=JSON&includepodid=Result&format=image,plaintext&"+ "input="+urlencode(input)); String result = getStringValueJSON("plaintext", response) if(result.isEmpty()) { result = getStringValueJSON("src", response); if(result.isEmpty()) throw new IllegalArgumentException("No valid data to display: "+response); } return result; } catch(Exception e) { if(!e.getClass().equals(IllegalArgumentException.class)) e.printStackTrace(); //TODO return "I do not understand."; }*/ } private static String eval2(final String query) { String response = null; try { final String input = urlencode(query); final String inputurl = "http://www.wolframalpha.com/input/?i="+input; GET(inputurl); GET("http://www.wolframalpha.com/input/cookietest.jsp"); final String proxycode = getStringValueJSON("code", GET("https://www.wolframalpha.com/input/api/v1/code?" +System.currentTimeMillis()*1000)); HttpURLConnection connection = WebRequest.request(new URL("" +"https://www.wolframalpha.com/input/json.jsp" +"?async=false" +"&banners=raw" +"&debuggingdata=false" +"&format=image,plaintext" +"&formattimeout=16" +"&input="+input +"&output=JSON" +"&parsetimeout=10" +"&proxycode="+proxycode +"&scantimeout=1" +"&sponsorcategories=false" +"&statemethod=deploybutton" +"&storesubpodexprs=true")); connection.setRequestProperty("Host", "https://www.wolframalpha.com"); connection.setRequestProperty("Origin", "https://www.wolframalpha.com"); connection.setRequestProperty("Referer", inputurl); connection.setRequestMethod("GET"); response = WebRequest.read(connection); if(response.matches("\\s*")) return ""; if(containsRegex("\"error\"\\s*:\\s*true",response)) //if(response.contains("\"error\" : true")) return "I encountered an error while processing your request."; if(containsRegex("\"success\"\\s*:\\s*true",response)) //if(response.contains("\"success\" : false")) return "I do not understand."; String jscmd = "var regex = /.*=image\\/([^&]*).*/g;\n" + "var httpsregex = /[^\\/]+\\/\\/.*/g;\n" + "var htsec = \"https:\";" + "var subst = \"&=.$1\";\n"//\u0060$0&=$1\u0060;\n" + "var pods="+response+".queryresult.pods;" + "for(var i=0;i<pods.length;++i){" + " if(pods[i].title==\"Result\"){" + " String(pods[i].subpods[0]);" + " //var src = pods[i].subpods[0].img.src;" + " //if(pods[i].subpods[0].plaintext==\"\"){ "// + " // var msg = (src.match(regex) ? src.replace(regex, src+subst) : src);" + " // (msg.match(httpsregex) ? msg : htsec+msg);" + " //}else{" + " // pods[i].subpods[0].plaintext;" + " //}" + " }" + "}"; javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("js"); Object r = engine.eval(jscmd); String result = (r==null ? "" : r.toString()); result = result.replaceAll("\\\\n", "\n").replace("Wolfram|Alpha", ChatBot.getMyUserName()).replaceAll("Stephen Wolfram and his team", "somebody"); return result; } catch(IOException e) { e.printStackTrace(); return "I do not understand."; } catch(ScriptException | NullPointerException e) { // TODO Auto-generated catch block if(response!=null) { System.err.println("Failed to parse JSON:\n"+response); } e.printStackTrace(); return "Failed to parse response"; } } public static boolean containsRegex(String regex, String in) { return Pattern.compile(regex).matcher(in).find(); } private static HashMap<String, Matcher> jsonmatchers = new HashMap<>(); /** * * @param regex * @param in * @return The match in <code>in</code> for the first group in <code>regex</code>. * @throws IllegalArgumentException If no match was found or if there is no capturing group in the regex */ public static String search(String regex, String in) { try { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(in); m.find(); return m.group(1); } catch(Exception e) { throw new IllegalArgumentException(e); } } private static String searchJSON(String regex, String input){ Matcher m; if(!jsonmatchers.containsKey(regex)) { jsonmatchers.put(regex, m=Pattern.compile(regex).matcher(input)); } else { m = jsonmatchers.get(regex); m.reset(input); } m.find(); return m.group(1); } public static String urlencode(String text) { try { return URLEncoder.encode(text, "UTF-8"); } catch(UnsupportedEncodingException e) { throw new InternalError(e); } } public static String urlencode(String[] singlemap) { return urlencode(new String[][]{singlemap}); } public static String urlencode(String[][] map) { try { String encoded = ""; for(int i=0;i<map.length;++i){ String[] parmap = map[i]; if(parmap.length!=2) throw new IllegalArgumentException("Invalid parameter mapping "+java.util.Arrays.deepToString(parmap)); encoded += parmap[0] + "=" + URLEncoder.encode(parmap[1], "UTF-8") + (i+1<map.length ? "&" : ""); } return encoded; } catch(UnsupportedEncodingException e) { throw new InternalError(e); } } public static boolean getBooleanValueJSON(String parname, String rawjson) { try{ return Boolean.parseBoolean(searchJSON("\""+parname+"\":(?i)(true|false|null)", rawjson)); }catch(Exception e){ try{ return Boolean.parseBoolean(searchJSON("\'"+parname+"\':(?i)(true|false|null)", rawjson)); }catch(Exception e2){ String s = getStringValueJSON(parname, rawjson); return s.isEmpty() ? false : Boolean.parseBoolean(s); } } } public static long getNumValueJSON(String parname, String rawjson) { try{ return Long.parseLong(searchJSON("\""+parname+"\":(\\d*)", rawjson)); }catch(Exception e){ try{ return Long.parseLong(searchJSON("\'"+parname+"\':(\\d*)", rawjson)); }catch(Exception e2){ //String s = getStringValueJSON(parname, rawjson); return 0; } } } public static String getStringValueJSON(String parname, String rawjson) { String match = ""; char QUOTE = '\"'; int startindex = rawjson.indexOf(QUOTE+parname+QUOTE+':'); if(startindex<0) try{ return searchJSON("\""+parname+"\"\\s*:\\s*\"(([^\\\\\"]*(\\\\.)?)*)\"", rawjson); }catch(Exception e){ try{ return searchJSON("\""+parname+"\"\\\\s*:\\\\s*\'(([^\\\\\']*(\\\\.)?)*)\'", rawjson); }catch(Exception e2){ try{ return searchJSON("\'"+parname+"\'\\\\s*:\\\\s*\"(([^\\\\\"]*(\\\\.)?)*)\"", rawjson); }catch(Exception e3){ try{ return searchJSON("\'"+parname+"\'\\\\s*:\\\\s*\'(([^\\\\\']*(\\\\.)?)*)\'", rawjson); }catch(Exception e4){ return ""; } } } } int index = startindex+parname.length()+3; boolean escapenext = false; char nextchar=rawjson.charAt(++index); try{ while(nextchar!=QUOTE || escapenext){ escapenext=false; match+=nextchar; if(nextchar=='\\' && !escapenext) escapenext=true; nextchar=rawjson.charAt(++index); } }catch(Exception e){ System.err.println("Partial: "+match); e.printStackTrace(); } return match; } private static Matcher unicodematcher = Pattern.compile("\\\\u(....)").matcher(""); private static String replaceUnicodeEscapes(String text) { unicodematcher.reset(text); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); while(unicodematcher.find()) { String match = unicodematcher.group(1); text=text.replaceAll("\\\\u"+match, ""+((char)Integer.parseUnsignedInt(match, 16))); unicodematcher.reset(text); } Thread.currentThread().setPriority(Thread.NORM_PRIORITY); return text; } private static Matcher htmlescapematcher = Pattern.compile("\\&\\#(x?[A-Fa-f0-9]+);").matcher(""); private static String replaceHtmlEscapes(String text) { htmlescapematcher.reset(text); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); while(htmlescapematcher.find()) { String match = htmlescapematcher.group(1); text=text.replaceAll("&#"+match+";", ""+((char)Integer.parseUnsignedInt(match, match.startsWith("x")?16:10))); } Thread.currentThread().setPriority(Thread.NORM_PRIORITY); return text; } private static String replaceAllAll(String target, String[][] rr) { for(String[] r : rr) target=target.replaceAll(r[0], r[1]); return target; } /** * @see <a href="https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML"> * List of XML and HTML character entity references - Wikipedia</a> */ private static final String[][] replacementRegexes = { {"</?b>","**"}, {"</?strong>","**"}, {"</?i>","*"}, {"</?em>","*"}, {"</?strike>","---"},//Note: The <strike> tag is not supported in HTML5 {"</?del>","---"}, {"</?s>","---"}, {"\\\\\"","\""}, {"\\\\\'","\'"}, {"<\\/?code>","\u0060"}, }; private static final Matcher htmllinkmatcher = Pattern.compile("<a\\s+.*href=\"([^\"]+)\"(?>\\s+title=\"([^\"]+)\")?[^>]*>(.*)<\\/a>").matcher(""); public static String unescapeHtml(String text) { if(text==null) return ""; text = replaceAllAll( replaceAllAll( replaceHtmlEscapes( replaceUnicodeEscapes( text.replaceAll("&zwnj;&#8203;", ""))), replacementRegexes), htmlCharacterEntityReferences); return text; } public static String makeLinksMarkdown(String text) { if(text==null) return ""; htmllinkmatcher.reset(text); while(htmllinkmatcher.find()){ String optional = htmllinkmatcher.group(2); String replacement = "["+htmllinkmatcher.group(3)+"]("+ htmllinkmatcher.group(1)+(optional!=null?(" \""+optional+"\""):"")+")"; text=text.replace(htmllinkmatcher.group(), replacement); } return text; } private static final SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS"); static{ //new java.util.SimpleTimeZone(rawOffset, ID, startMonth, startDay, startDayOfWeek, startTime, startTimeMode, endMonth, endDay, endDayOfWeek, endTime, endTimeMode, dstSavings) dtf.setTimeZone(TimeZone.getDefault()); } public static String getDateTime(){ return dtf.format(System.currentTimeMillis()); } public static Long[] parseLongs(String str) { String[] strs = str.split("[, ;]"); Long[] vals = new Long[strs.length]; for(int i=0;i<strs.length;++i) vals[i]=new Long(strs[i]); return vals; } private static final String wotdFeedUrl = "http://www.dictionary.com/wordoftheday/wotd.rss"; private static final Matcher wotdMatcher = Pattern.compile("(?is)<item>.*?<link>(.*?)<\\/link>.*?<description>(.*?)<\\/description>.*?<\\/item>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE).matcher(""); public static String getWotd(){ try { String text = GET(wotdFeedUrl); wotdMatcher.reset(text); wotdMatcher.find(); String output = "["+wotdMatcher.group(2)+"]("+wotdMatcher.group(1)+")"; return output; } catch(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } private static String[][] htmlCharacterEntityReferences = { //And here is the long list of html character entity references //See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references {"&quot;", "\""}, {"&amp;", "&"}, {"&apos;", "\'"}, {"&lt;", "<"}, {"&gt;", ">"}, {"&nbsp;", "\u00A0"}, {"&iexcl;", "\u00A1"}, {"&cent;", "\u00A2"}, {"&pound;", "\u00A3"}, {"&curren;", "\u00A4"}, {"&yen;", "\u00A5"}, {"&brvbar;", "\u00A6"}, {"&sect;", "\u00A7"}, {"&uml;", "\u00A8"}, {"&copy;", "\u00A9"}, {"&ordf;", "\u00AA"}, {"&laquo;", "\u00AB"}, {"&not;", "\u00AC"}, {"&shy;", "\u00AD"}, {"&reg;", "\u00AE"}, {"&macr;", "\u00AF"}, {"&deg;", "\u00B0"}, {"&plusmn;", "\u00B1"}, {"&sup2;", "\u00B2"}, {"&sup3;", "\u00B3"}, {"&acute;", "\u00B4"}, {"&micro;", "\u00B5"}, {"&para;", "\u00B6"}, {"&middot;", "\u00B7"}, {"&cedil;", "\u00B8"}, {"&sup1;", "\u00B9"}, {"&ordm;", "\u00BA"}, {"&raquo;", "\u00BB"}, {"&frac14;", "\u00BC"}, {"&frac12;", "\u00BD"}, {"&frac34;", "\u00BE"}, {"&iquest;", "\u00BF"}, {"&Agrave;", "\u00C0"}, {"&Aacute;", "\u00C1"}, {"&Acirc;", "\u00C2"}, {"&Atilde;", "\u00C3"}, {"&Auml;", "\u00C4"}, {"&Aring;", "\u00C5"}, {"&AElig;", "\u00C6"}, {"&Ccedil;", "\u00C7"}, {"&Egrave;", "\u00C8"}, {"&Eacute;", "\u00C9"}, {"&Ecirc;", "\u00CA"}, {"&Euml;", "\u00CB"}, {"&Igrave;", "\u00CC"}, {"&Iacute;", "\u00CD"}, {"&Icirc;", "\u00CE"}, {"&Iuml;", "\u00CF"}, {"&ETH;", "\u00D0"}, {"&Ntilde;", "\u00D1"}, {"&Ograve;", "\u00D2"}, {"&Oacute;", "\u00D3"}, {"&Ocirc;", "\u00D4"}, {"&Otilde;", "\u00D5"}, {"&Ouml;", "\u00D6"}, {"&times;", "\u00D7"}, {"&Oslash;", "\u00D8"}, {"&Ugrave;", "\u00D9"}, {"&Uacute;", "\u00DA"}, {"&Ucirc;", "\u00DB"}, {"&Uuml;", "\u00DC"}, {"&Yacute;", "\u00DD"}, {"&THORN;", "\u00DE"}, {"&szlig;", "\u00DF"}, {"&agrave;", "\u00E0"}, {"&aacute;", "\u00E1"}, {"&acirc;", "\u00E2"}, {"&atilde;", "\u00E3"}, {"&auml;", "\u00E4"}, {"&aring;", "\u00E5"}, {"&aelig;", "\u00E6"}, {"&ccedil;", "\u00E7"}, {"&egrave;", "\u00E8"}, {"&eacute;", "\u00E9"}, {"&ecirc;", "\u00EA"}, {"&euml;", "\u00EB"}, {"&igrave;", "\u00EC"}, {"&iacute;", "\u00ED"}, {"&icirc;", "\u00EE"}, {"&iuml;", "\u00EF"}, {"&eth;", "\u00F0"}, {"&ntilde;", "\u00F1"}, {"&ograve;", "\u00F2"}, {"&oacute;", "\u00F3"}, {"&ocirc;", "\u00F4"}, {"&otilde;", "\u00F5"}, {"&ouml;", "\u00F6"}, {"&divide;", "\u00F7"}, {"&oslash;", "\u00F8"}, {"&ugrave;", "\u00F9"}, {"&uacute;", "\u00FA"}, {"&ucirc;", "\u00FB"}, {"&uuml;", "\u00FC"}, {"&yacute;", "\u00FD"}, {"&thorn;", "\u00FE"}, {"&yuml;", "\u00FF"}, {"&OElig;", "\u0152"}, {"&oelig;", "\u0153"}, {"&Scaron;", "\u0160"}, {"&scaron;", "\u0161"}, {"&Yuml;", "\u0178"}, {"&fnof;", "\u0192"}, {"&circ;", "\u02C6"}, {"&tilde;", "\u02DC"}, {"&Alpha;", "\u0391"}, {"&Beta;", "\u0392"}, {"&Gamma;", "\u0393"}, {"&Delta;", "\u0394"}, {"&Epsilon;", "\u0395"}, {"&Zeta;", "\u0396"}, {"&Eta;", "\u0397"}, {"&Theta;", "\u0398"}, {"&Iota;", "\u0399"}, {"&Kappa;", "\u039A"}, {"&Lambda;", "\u039B"}, {"&Mu;", "\u039C"}, {"&Nu;", "\u039D"}, {"&Xi;", "\u039E"}, {"&Omicron;", "\u039F"}, {"&Pi;", "\u03A0"}, {"&Rho;", "\u03A1"}, {"&Sigma;", "\u03A3"}, {"&Tau;", "\u03A4"}, {"&Upsilon;", "\u03A5"}, {"&Phi;", "\u03A6"}, {"&Chi;", "\u03A7"}, {"&Psi;", "\u03A8"}, {"&Omega;", "\u03A9"}, {"&alpha;", "\u03B1"}, {"&beta;", "\u03B2"}, {"&gamma;", "\u03B3"}, {"&delta;", "\u03B4"}, {"&epsilon;", "\u03B5"}, {"&zeta;", "\u03B6"}, {"&eta;", "\u03B7"}, {"&theta;", "\u03B8"}, {"&iota;", "\u03B9"}, {"&kappa;", "\u03BA"}, {"&lambda;", "\u03BB"}, {"&mu;", "\u03BC"}, {"&nu;", "\u03BD"}, {"&xi;", "\u03BE"}, {"&omicron;", "\u03BF"}, {"&pi;", "\u03C0"}, {"&rho;", "\u03C1"}, {"&sigmaf;", "\u03C2"}, {"&sigma;", "\u03C3"}, {"&tau;", "\u03C4"}, {"&upsilon;", "\u03C5"}, {"&phi;", "\u03C6"}, {"&chi;", "\u03C7"}, {"&psi;", "\u03C8"}, {"&omega;", "\u03C9"}, {"&thetasym;", "\u03D1"}, {"&upsih;", "\u03D2"}, {"&piv;", "\u03D6"}, {"&ensp;", "\u2002"}, {"&emsp;", "\u2003"}, {"&thinsp;", "\u2009"}, {"&zwnj;", "\u200C"}, {"&zwj;", "\u200D"}, {"&lrm;", "\u200E"}, {"&rlm;", "\u200F"}, {"&ndash;", "\u2013"}, {"&mdash;", "\u2014"}, {"&lsquo;", "\u2018"}, {"&rsquo;", "\u2019"}, {"&sbquo;", "\u201A"}, {"&ldquo;", "\u201C"}, {"&rdquo;", "\u201D"}, {"&bdquo;", "\u201E"}, {"&dagger;", "\u2020"}, {"&Dagger;", "\u2021"}, {"&bull;", "\u2022"}, {"&hellip;", "\u2026"}, {"&permil;", "\u2030"}, {"&prime;", "\u2032"}, {"&Prime;", "\u2033"}, {"&lsaquo;", "\u2039"}, {"&rsaquo;", "\u203A"}, {"&oline;", "\u203E"}, {"&frasl;", "\u2044"}, {"&euro;", "\u20AC"}, {"&image;", "\u2111"}, {"&weierp;", "\u2118"}, {"&real;", "\u211C"}, {"&trade;", "\u2122"}, {"&alefsym;", "\u2135"}, {"&larr;", "\u2190"}, {"&uarr;", "\u2191"}, {"&rarr;", "\u2192"}, {"&darr;", "\u2193"}, {"&harr;", "\u2194"}, {"&crarr;", "\u21B5"}, {"&lArr;", "\u21D0"}, {"&uArr;", "\u21D1"}, {"&rArr;", "\u21D2"}, {"&dArr;", "\u21D3"}, {"&hArr;", "\u21D4"}, {"&forall;", "\u2200"}, {"&part;", "\u2202"}, {"&exist;", "\u2203"}, {"&empty;", "\u2205"}, {"&nabla;", "\u2207"}, {"&isin;", "\u2208"}, {"&notin;", "\u2209"}, {"&ni;", "\u220B"}, {"&prod;", "\u220F"}, {"&sum;", "\u2211"}, {"&minus;", "\u2212"}, {"&lowast;", "\u2217"}, {"&radic;", "\u221A"}, {"&prop;", "\u221D"}, {"&infin;", "\u221E"}, {"&ang;", "\u2220"}, {"&and;", "\u2227"}, {"&or;", "\u2228"}, {"&cap;", "\u2229"}, {"&cup;", "\u222A"}, {"&int;", "\u222B"}, {"&there4;", "\u2234"}, {"&sim;", "\u223C"}, {"&cong;", "\u2245"}, {"&asymp;", "\u2248"}, {"&ne;", "\u2260"}, {"&equiv;", "\u2261"}, {"&le;", "\u2264"}, {"&ge;", "\u2265"}, {"&sub;", "\u2282"}, {"&sup;", "\u2283"}, {"&nsub;", "\u2284"}, {"&sube;", "\u2286"}, {"&supe;", "\u2287"}, {"&oplus;", "\u2295"}, {"&otimes;", "\u2297"}, {"&perp;", "\u22A5"}, {"&sdot;", "\u22C5"}, {"&lceil;", "\u2308"}, {"&rceil;", "\u2309"}, {"&lfloor;", "\u230A"}, {"&rfloor;", "\u230B"}, {"&lang;", "\u2329"}, {"&rang;", "\u232A"}, {"&loz;", "\u25CA"}, {"&spades;", "\u2660"}, {"&clubs;", "\u2663"}, {"&hearts;", "\u2665"}, {"&diams;", "\u2666"} }; }
eval fix
src/utils/Utils.java
eval fix
<ide><path>rc/utils/Utils.java <ide> connection.setRequestProperty("Referer", inputurl); <ide> connection.setRequestMethod("GET"); <ide> response = WebRequest.read(connection); <del> if(response.matches("\\s*")) <del> return ""; <del> if(containsRegex("\"error\"\\s*:\\s*true",response)) <del> //if(response.contains("\"error\" : true")) <del> return "I encountered an error while processing your request."; <del> if(containsRegex("\"success\"\\s*:\\s*true",response)) <del> //if(response.contains("\"success\" : false")) <del> return "I do not understand."; <del> String jscmd = "var regex = /.*=image\\/([^&]*).*/g;\n" <del> + "var httpsregex = /[^\\/]+\\/\\/.*/g;\n" <del> + "var htsec = \"https:\";" <del> + "var subst = \"&=.$1\";\n"//\u0060$0&=$1\u0060;\n" <del> + "var pods="+response+".queryresult.pods;" <del> + "for(var i=0;i<pods.length;++i){" <del> + " if(pods[i].title==\"Result\"){" <del> + " String(pods[i].subpods[0]);" <del> + " //var src = pods[i].subpods[0].img.src;" <del> + " //if(pods[i].subpods[0].plaintext==\"\"){ "// <del> + " // var msg = (src.match(regex) ? src.replace(regex, src+subst) : src);" <del> + " // (msg.match(httpsregex) ? msg : htsec+msg);" <del> + " //}else{" <del> + " // pods[i].subpods[0].plaintext;" <del> + " //}" <del> + " }" <del> + "}"; <del> javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("js"); <del> Object r = engine.eval(jscmd); <del> String result = (r==null ? "" : r.toString()); <del> result = result.replaceAll("\\\\n", "\n").replace("Wolfram|Alpha", ChatBot.getMyUserName()).replaceAll("Stephen Wolfram and his team", "somebody"); <del> return result; <add> return parseResponse(response); <ide> } <ide> catch(IOException e) <ide> { <ide> } <ide> } <ide> <add> private static String parseResponse(String response) throws ScriptException, NullPointerException <add> { <add> if(response.matches("\\s*")) <add> return ""; <add> if(containsRegex("\"error\"\\s*:\\s*true",response)) <add> //if(response.contains("\"error\" : true")) <add> return "I encountered an error while processing your request."; <add> if(containsRegex("\"success\"\\s*:\\s*false",response)) <add> //if(response.contains("\"success\" : false")) <add> return "I do not understand."; <add> String jscmd = "var regex = /.*=image\\/([^&]*).*/g;\n" <add> + "var httpsregex = /[^\\/]+\\/\\/.*/g;\n" <add> + "var htsec = \"https:\";" <add> + "var subst = \"&=.$1\";\n"//\u0060$0&=$1\u0060;\n" <add> + "var pods="+response+".queryresult.pods;" <add> + "for(var i=0;i<pods.length;++i){" <add> + " if(pods[i].title==\"Result\" || pods[i].title==\"Response\"){" <add> + " JSON.stringify(pods[i].subpods[0]);" <add> + " /*var src = pods[i].subpods[0].img.src;" <add> + " if(pods[i].subpods[0].plaintext==\"\"){ "// <add> + " var msg = (src.match(regex) ? src.replace(regex, src+subst) : src);" <add> + " (msg.match(httpsregex) ? msg : htsec+msg);" <add> + " }else{" <add> + " pods[i].subpods[0].plaintext;" <add> + " }*/" <add> + " }" <add> + "}"; <add> javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("js"); <add> Object r = engine.eval(jscmd); <add> String rawjson = (r==null ? "" : r.toString()); <add> String plaintext = getStringValueJSON("plaintext", rawjson); <add> String result = (plaintext.isEmpty() ? getStringValueJSON("src", rawjson) : plaintext) <add> .replaceAll("\\\\n", "\n").replace("Wolfram|Alpha", ChatBot.getMyUserName()).replaceAll("Stephen Wolfram and his team", "somebody"); <add> return result; <add> } <add> <ide> public static boolean containsRegex(String regex, String in) <ide> { <ide> return Pattern.compile(regex).matcher(in).find();
Java
apache-2.0
ed084264153c6eef739771348eb5876f47ab1ba2
0
helyho/Voovan,helyho/Voovan,helyho/Voovan
package org.voovan.http.server.module.annontationRouter.router; import org.voovan.http.HttpContentType; import org.voovan.http.message.HttpStatic; import org.voovan.http.server.*; import org.voovan.http.server.exception.AnnotationRouterException; import org.voovan.http.server.module.annontationRouter.AnnotationModule; import org.voovan.http.server.module.annontationRouter.annotation.*; import org.voovan.http.websocket.WebSocketRouter; import org.voovan.tools.TEnv; import org.voovan.tools.TFile; import org.voovan.tools.TString; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * 通过注解实现的路由 * * @author: helyho * Voovan Framework. * WebSite: https://github.com/helyho/Voovan * Licence: Apache v2 License */ public class AnnotationRouter implements HttpRouter { private static Map<Class, Object> singletonObjs = new ConcurrentHashMap<Class, Object>(); private String urlPath; private String paramPath; private String path; private Class clazz; private Method method; private String methodName; private Router classRouter; private Router methodRoute; private AnnotationModule annotationModule; /** * 构造函数 * @param annotationModule AnnotationModule 对象 * @param clazz Class对象 * @param method 方法对象 * @param classRouter 类上的 Route 注解 * @param methodRoute 方法上的 Route 注解 * @param urlPath url 路径 * @param paramPath 带参数的 url 路径 */ public AnnotationRouter(AnnotationModule annotationModule, Class clazz, Method method, Router classRouter, Router methodRoute, String urlPath, String paramPath) { this.annotationModule = annotationModule; this.clazz = clazz; this.method = method; this.methodName = method.getName(); this.classRouter = classRouter; this.methodRoute = methodRoute; this.urlPath = urlPath; this.paramPath = paramPath; this.path = urlPath + paramPath; annotationModule.METHOD_URL_MAP.put(method, urlPath); annotationModule.URL_METHOD_MAP.put(urlPath, method); //如果是单例,则进行预实例化 if(classRouter.singleton() && !singletonObjs.containsKey(clazz)){ try { singletonObjs.put(clazz, clazz.newInstance()); } catch (Exception e) { Logger.error("New a singleton object error", e); } } } public String getUrlPath() { return urlPath; } public String getParamPath() { return paramPath; } public String getPath() { return path; } public Class getClazz() { return clazz; } public Method getMethod() { return method; } public Router getClassRouter() { return classRouter; } public Router getMethodRoute() { return methodRoute; } public AnnotationModule getAnnotationModule() { return annotationModule; } /** * 扫描包含Router注解的类 * * @param annotationModule AnnotationModule对象用于注册路由 */ public static void scanRouterClassAndRegister(AnnotationModule annotationModule) { int routeMethodNum = 0; String modulePath = annotationModule.getModuleConfig().getPath(); modulePath = HttpDispatcher.fixRoutePath(modulePath); WebServer webServer = annotationModule.getWebServer(); try { //查找包含 Router 注解的类 String[] scanRouterPackageArr = annotationModule.getScanRouterPackage().split(";"); for(String scanRouterPackage : scanRouterPackageArr) { scanRouterPackage = scanRouterPackage.trim(); List<Class> routerClasses = TEnv.searchClassInEnv(scanRouterPackage, new Class[]{Router.class}); for (Class routerClass : routerClasses) { Method[] methods = routerClass.getMethods(); Router[] annonClassRouters = (Router[]) routerClass.getAnnotationsByType(Router.class); //多个 Router 注解的迭代 for (Router annonClassRouter : annonClassRouters) { String classRouterPath = annonClassRouter.path().isEmpty() ? annonClassRouter.value() : annonClassRouter.path(); String[] classRouterMethods = annonClassRouter.method(); //多个请求方法的迭代 for (String classRouterMethod : classRouterMethods) { //使用类名指定默认路径 if (classRouterPath.isEmpty()) { //使用类名指定默认路径 classRouterPath = routerClass.getSimpleName(); } classRouterPath = HttpDispatcher.fixRoutePath(classRouterPath); //注册以采用静态方法低啊用 // if(methods.length > 0) { // TReflect.register(routerClass); // } //扫描包含 Router 注解的方法 for (Method method : methods) { Router[] annonMethodRouters = (Router[]) method.getAnnotationsByType(Router.class); if (annonMethodRouters != null) { //多个 Router 注解的迭代, 一个方法支持多个路由 for (Router annonMethodRouter : annonMethodRouters) { String methodRouterPath = annonMethodRouter.path().isEmpty() ? annonMethodRouter.value() : annonMethodRouter.path(); String[] methodRouterMethods = annonMethodRouter.method(); //多个请求方法的迭代, 一个路由支持多个 Http mehtod for (String methodRouterMethod : methodRouterMethods) { //使用方法名指定默认路径 if (methodRouterPath.isEmpty()) { //如果方法名为: index 则为默认路由 if (method.getName().equals("index")) { methodRouterPath = "/"; } else { methodRouterPath = method.getName(); } } //拼装方法路径 methodRouterPath = HttpDispatcher.fixRoutePath(methodRouterPath); //拼装 (类+方法) 路径 String routePath = classRouterPath + methodRouterPath; //如果方法上的注解指定了 Method 则使用方法上的注解指定的,否则使用类上的注解指定的 String routeMethod = methodRouterMethod.isEmpty() ? classRouterMethod : methodRouterMethod; routeMethod = routeMethod.isEmpty() ? HttpStatic.GET_STRING : routeMethod; //为方法的参数准备带参数的路径 String paramPath = ""; Annotation[][] paramAnnotationsArrary = method.getParameterAnnotations(); Class[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramAnnotationsArrary.length; i++) { Annotation[] paramAnnotations = paramAnnotationsArrary[i]; if (paramAnnotations.length == 0 && paramTypes[i] != HttpRequest.class && paramTypes[i] != HttpResponse.class && paramTypes[i] != HttpSession.class) { paramPath = paramPath + "/:param" + (i + 1); continue; } for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation instanceof Param) { paramPath = TString.assembly(paramPath, "/:", ((Param) paramAnnotation).value()); } //如果没有指定方法, 参数包含 BodyParam 注解则指定请求方法为 POST if ((paramAnnotation instanceof BodyParam || paramAnnotation instanceof Body) && routeMethod.equals(HttpStatic.GET_STRING)) { routeMethod = HttpStatic.POST_STRING; } } } /** * 注册路由部分代码在下面 */ if (webServer.getHttpRouters().get(routeMethod) == null) { webServer.getHttpDispatcher().addRouteMethod(routeMethod); } //生成完整的路由,用来检查路由是否存在 routePath = HttpDispatcher.fixRoutePath(routePath); //这里这么做是为了处理 TreeMap 的 containsKey 方法的 bug Map routerMaps = new HashMap(); routerMaps.putAll(webServer.getHttpRouters().get(routeMethod)); //构造注解路由器 AnnotationRouter annotationRouter = new AnnotationRouter(annotationModule, routerClass, method, annonClassRouter, annonMethodRouter, routePath, paramPath); String routeLog = null; //1.注册路由, 处理不带参数的路由 routePath = HttpDispatcher.fixRoutePath(routePath); String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routePath); //判断路由是否注册过 if (!routerMaps.containsKey(moduleRoutePath)) { //注册路由,不带路径参数的路由 annotationModule.otherMethod(routeMethod, routePath, annotationRouter); routeLog = "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + moduleRoutePath; routeMethodNum++; } //2.注册路由,带路径参数的路由 if(!paramPath.isEmpty()) { String routeParamPath = null; routeParamPath = routePath + paramPath; routeParamPath = HttpDispatcher.fixRoutePath(routeParamPath); String moduleRouteParamPath = HttpDispatcher.fixRoutePath(modulePath + routeParamPath); if (!routerMaps.containsKey(moduleRoutePath)) { annotationModule.otherMethod(routeMethod, routeParamPath, annotationRouter); routeLog = "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + moduleRouteParamPath; } } if(routeLog!=null) { Logger.simple(routeLog); } } } } } } } } //查找包含 WebSocket 注解的类 List<Class> webSocketClasses = TEnv.searchClassInEnv(annotationModule.getScanRouterPackage(), new Class[]{WebSocket.class}); for (Class webSocketClass : webSocketClasses) { if (TReflect.isExtendsByClass(webSocketClass, WebSocketRouter.class)) { WebSocket[] annonClassRouters = (WebSocket[]) webSocketClass.getAnnotationsByType(WebSocket.class); WebSocket annonClassRouter = annonClassRouters[0]; String classRouterPath = annonClassRouter.path().isEmpty() ? annonClassRouter.value() : annonClassRouter.path(); //使用类名指定默认路径 if (classRouterPath.isEmpty()) { //使用类名指定默认路径 classRouterPath = webSocketClass.getSimpleName(); } classRouterPath = HttpDispatcher.fixRoutePath(classRouterPath); String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + classRouterPath); if (!webServer.getWebSocketRouters().containsKey(moduleRoutePath)) { annotationModule.socket(classRouterPath, (WebSocketRouter) TReflect.newInstance(webSocketClass)); Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] add WebSocket: " + TString.leftPad(moduleRoutePath, 11, ' ')); routeMethodNum++; } } } if(routeMethodNum>0) { Logger.simple(TFile.getLineSeparator() + "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] Scan some class [" + scanRouterPackage + "] annotation by Router: " + routerClasses.size() + ". Register Router method annotation by route: " + routeMethodNum + "."); } } } catch (Exception e){ Logger.error("Scan router class error.", e); } } // /** // * 修复路由路径 // * @param routePath 路由路径 // * @return 修复后的路由路径 // */ // private static String fixAnnotationRoutePath(String routePath){ // routePath = routePath.startsWith("/") ? TString.removePrefix(routePath) : routePath; // routePath = routePath.endsWith("/") ? TString.removeSuffix(routePath) : routePath; // return routePath; // } /** * 将一个 Http 请求映射到一个类的方法调用 * @param request http 请求对象 * @param response http 响应对象 * @param clazz Class 对象 * @param method Method 对象 * @return 返回值 * @throws Exception 调用过程中的异常 */ public Object invokeRouterMethod(HttpRequest request, HttpResponse response, Class clazz, Method method) throws Exception { Object annotationObj = null; //如果是单例模式则使用预先初始话好的 if(this.classRouter.singleton()){ annotationObj = singletonObjs.get(clazz); } else { annotationObj = clazz.newInstance(); } Class[] parameterTypes = method.getParameterTypes(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); String bodyString = ""; Map bodyMap = null; if(request.body().size() > 0) { bodyString = request.body().getBodyString(); if(JSON.isJSONMap(bodyString)) { bodyMap = (Map) JSON.parse(bodyString); } } //准备参数 Object[] params = new Object[parameterTypes.length]; for(int i=0; i < parameterAnnotations.length; i++){ //请求对象 if(parameterTypes[i] == HttpRequest.class){ params[i] = request; continue; } //响应对象 if(parameterTypes[i] == HttpResponse.class){ params[i] = response; continue; } //会话对象 if(parameterTypes[i] == HttpSession.class){ params[i] = request.getSession(); continue; } for(Annotation annotation : parameterAnnotations[i]) { //请求的参数 if (annotation instanceof Param) { String paramName = ((Param) annotation).value(); try { params[i] = TString.toObject(request.getParameter(paramName), parameterTypes[i], true); continue; } catch (Exception e) { if(((Param) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Param [" + paramName + " = " + params[i] + "] error, data: " + request.getParameters(), e); } } } //请求的参数 if (annotation instanceof BodyParam) { String paramName = ((BodyParam) annotation).value(); try { if(bodyMap != null && bodyMap instanceof Map) { Object bodyParam = bodyMap.get(paramName); if(TReflect.isBasicType(bodyParam.getClass())) { params[i] = TString.toObject(bodyParam.toString(), parameterTypes[i], true); } else if(bodyParam instanceof Map){ params[i] = TReflect.getObjectFromMap(parameterTypes[i], (Map)bodyParam, true); } else { params[i] = bodyParam; } } continue; } catch (Exception e) { if(((BodyParam) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @BodyParam [" + paramName + " = " + params[i] + "] error, data: " + bodyMap.toString(), e); } } } //请求的头 if (annotation instanceof Head) { String headName = ((Head) annotation).value(); try { params[i] = TString.toObject(request.header().get(headName), parameterTypes[i], true); continue; } catch (Exception e) { if(((Head) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Head [" + headName + " = " + params[i] + "] error, data: " + request.header().toString(), e); } } } //请求的 Cookie if (annotation instanceof Cookie) { String cookieValue = null; String cookieName = ((Cookie) annotation).value(); try { org.voovan.http.message.packet.Cookie cookie = request.getCookie(cookieName); if (cookie != null) { cookieValue = cookie.getValue(); } params[i] = TString.toObject(cookieValue, parameterTypes[i], true); continue; } catch (Exception e) { if(((Cookie) annotation).isRequire()) { String cookieStr = request.cookies().parallelStream().map(cookie -> cookie.getName() + "=" + cookie.getName()).collect(Collectors.toList()).toString(); throw new AnnotationRouterException("Router annotation @Cookie [" + cookieName + " = " + params[i] + "] error, data: " + cookieStr, e); } } } //请求的 Body if (annotation instanceof Body) { try { params[i] = bodyMap == null ? TString.toObject(bodyString, parameterTypes[i], true) : TReflect.getObjectFromMap(parameterTypes[i], bodyMap, true); continue; } catch (Exception e) { if(((Body) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Body error \r\n data: " + bodyString, e); } } } //请求的头 if (annotation instanceof Attribute) { String attrName = ((Attribute) annotation).value(); try { params[i] = TString.toObject(request.getAttributes().get(attrName).toString(), parameterTypes[i], true); continue; } catch (Exception e) { if(((Attribute) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Attribute [" + attrName + " = " + params[i] + "] error, data: " + request.header().toString(), e); } } } //请求的头 if (annotation instanceof Session) { String sessionName = ((Session) annotation).value(); HttpSession httpSession = request.getSession(); try { if (httpSession.getAttribute(sessionName).getClass() == parameterTypes[i]) { params[i] = httpSession.getAttribute(sessionName); } continue; } catch (Exception e) { if(((Session) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Session [" + sessionName + " = " + params[i] + "] error, data: " + httpSession.attributes().toString(), e); } } } } //没有注解的参数,按顺序处理 if(params[i]==null) { try { String value = request.getParameter("param" + String.valueOf(i + 1)); params[i] = TString.toObject(value, parameterTypes[i], true); continue; } catch (Exception e) { throw new AnnotationRouterException("Router sequential injection param " + request.getParameters().toString() + " error", e); } } } //调用方法 return TReflect.invokeMethod(annotationObj, method, params); } @Override public void process(HttpRequest request, HttpResponse response) throws Exception { AnnotationRouterFilter annotationRouterFilter = annotationModule.getAnnotationRouterFilter(); Object responseObj = null; Object fliterResult = null; try { //根据 Router 注解的标记设置响应的Content-Type response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpContentType.getHttpContentType(methodRoute.contentType())); //过滤器前置处理 if(annotationRouterFilter!=null) { fliterResult = annotationRouterFilter.beforeInvoke(request, response, this); } //null: 执行请求路由方法 //非 null: 作为 http 请求的响应直接返回 if(fliterResult == null) { responseObj = invokeRouterMethod(request, response, clazz, method); } else { responseObj = fliterResult; } //过滤器后置处理 if(annotationRouterFilter!=null) { fliterResult = annotationRouterFilter.afterInvoke(request, response, this, responseObj); if(fliterResult!=null) { responseObj = fliterResult; } } } catch(Exception e) { //过滤器拦截异常 if(annotationRouterFilter!=null) { fliterResult = annotationRouterFilter.exception(request, response, this, e); } if(fliterResult !=null) { responseObj = fliterResult; } else { if (e.getCause() != null) { Throwable cause = e.getCause(); if (cause instanceof Exception) { e = (Exception) cause; } } Logger.error(e); if (e instanceof AnnotationRouterException) { throw e; } else { throw new AnnotationRouterException("Process annotation router error. URL: " + request.protocol().getPath(), e); } } } if (responseObj != null) { if (responseObj instanceof String) { response.write((String) responseObj); } else if (responseObj instanceof byte[]) { response.write((byte[]) responseObj); } else { response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpContentType.getHttpContentType(HttpContentType.JSON)); response.write(JSON.toJSON(responseObj)); } } } }
Web/src/main/java/org/voovan/http/server/module/annontationRouter/router/AnnotationRouter.java
package org.voovan.http.server.module.annontationRouter.router; import org.voovan.http.HttpContentType; import org.voovan.http.message.HttpStatic; import org.voovan.http.server.*; import org.voovan.http.server.exception.AnnotationRouterException; import org.voovan.http.server.module.annontationRouter.AnnotationModule; import org.voovan.http.server.module.annontationRouter.annotation.*; import org.voovan.http.websocket.WebSocketRouter; import org.voovan.tools.TEnv; import org.voovan.tools.TFile; import org.voovan.tools.TString; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * 通过注解实现的路由 * * @author: helyho * Voovan Framework. * WebSite: https://github.com/helyho/Voovan * Licence: Apache v2 License */ public class AnnotationRouter implements HttpRouter { private static Map<Class, Object> singletonObjs = new ConcurrentHashMap<Class, Object>(); private String urlPath; private String paramPath; private String path; private Class clazz; private Method method; private String methodName; private Router classRouter; private Router methodRoute; private AnnotationModule annotationModule; /** * 构造函数 * @param annotationModule AnnotationModule 对象 * @param clazz Class对象 * @param method 方法对象 * @param classRouter 类上的 Route 注解 * @param methodRoute 方法上的 Route 注解 * @param urlPath url 路径 * @param paramPath 带参数的 url 路径 */ public AnnotationRouter(AnnotationModule annotationModule, Class clazz, Method method, Router classRouter, Router methodRoute, String urlPath, String paramPath) { this.annotationModule = annotationModule; this.clazz = clazz; this.method = method; this.methodName = method.getName(); this.classRouter = classRouter; this.methodRoute = methodRoute; this.urlPath = urlPath; this.paramPath = paramPath; this.path = urlPath + paramPath; annotationModule.METHOD_URL_MAP.put(method, urlPath); annotationModule.URL_METHOD_MAP.put(urlPath, method); //如果是单例,则进行预实例化 if(classRouter.singleton() && !singletonObjs.containsKey(clazz)){ try { singletonObjs.put(clazz, clazz.newInstance()); } catch (Exception e) { Logger.error("New a singleton object error", e); } } } public String getUrlPath() { return urlPath; } public String getParamPath() { return paramPath; } public String getPath() { return path; } public Class getClazz() { return clazz; } public Method getMethod() { return method; } public Router getClassRouter() { return classRouter; } public Router getMethodRoute() { return methodRoute; } public AnnotationModule getAnnotationModule() { return annotationModule; } /** * 扫描包含Router注解的类 * * @param annotationModule AnnotationModule对象用于注册路由 */ public static void scanRouterClassAndRegister(AnnotationModule annotationModule) { int routeMethodNum = 0; String modulePath = annotationModule.getModuleConfig().getPath(); modulePath = HttpDispatcher.fixRoutePath(modulePath); WebServer webServer = annotationModule.getWebServer(); try { //查找包含 Router 注解的类 String[] scanRouterPackageArr = annotationModule.getScanRouterPackage().split(";"); for(String scanRouterPackage : scanRouterPackageArr) { scanRouterPackage = scanRouterPackage.trim(); List<Class> routerClasses = TEnv.searchClassInEnv(scanRouterPackage, new Class[]{Router.class}); for (Class routerClass : routerClasses) { Method[] methods = routerClass.getMethods(); Router[] annonClassRouters = (Router[]) routerClass.getAnnotationsByType(Router.class); //多个 Router 注解的迭代 for (Router annonClassRouter : annonClassRouters) { String classRouterPath = annonClassRouter.path().isEmpty() ? annonClassRouter.value() : annonClassRouter.path(); String[] classRouterMethods = annonClassRouter.method(); //多个请求方法的迭代 for (String classRouterMethod : classRouterMethods) { //使用类名指定默认路径 if (classRouterPath.isEmpty()) { //使用类名指定默认路径 classRouterPath = routerClass.getSimpleName(); } classRouterPath = HttpDispatcher.fixRoutePath(classRouterPath); //注册以采用静态方法低啊用 // if(methods.length > 0) { // TReflect.register(routerClass); // } //扫描包含 Router 注解的方法 for (Method method : methods) { Router[] annonMethodRouters = (Router[]) method.getAnnotationsByType(Router.class); if (annonMethodRouters != null) { //多个 Router 注解的迭代, 一个方法支持多个路由 for (Router annonMethodRouter : annonMethodRouters) { String methodRouterPath = annonMethodRouter.path().isEmpty() ? annonMethodRouter.value() : annonMethodRouter.path(); String[] methodRouterMethods = annonMethodRouter.method(); //多个请求方法的迭代, 一个路由支持多个 Http mehtod for (String methodRouterMethod : methodRouterMethods) { //使用方法名指定默认路径 if (methodRouterPath.isEmpty()) { //如果方法名为: index 则为默认路由 if (method.getName().equals("index")) { methodRouterPath = "/"; } else { methodRouterPath = method.getName(); } } //拼装方法路径 methodRouterPath = HttpDispatcher.fixRoutePath(methodRouterPath); //拼装 (类+方法) 路径 String routePath = classRouterPath + methodRouterPath; //如果方法上的注解指定了 Method 则使用方法上的注解指定的,否则使用类上的注解指定的 String routeMethod = methodRouterMethod.isEmpty() ? classRouterMethod : methodRouterMethod; routeMethod = routeMethod.isEmpty() ? HttpStatic.GET_STRING : routeMethod; //为方法的参数准备带参数的路径 String paramPath = ""; Annotation[][] paramAnnotationsArrary = method.getParameterAnnotations(); Class[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramAnnotationsArrary.length; i++) { Annotation[] paramAnnotations = paramAnnotationsArrary[i]; if (paramAnnotations.length == 0 && paramTypes[i] != HttpRequest.class && paramTypes[i] != HttpResponse.class && paramTypes[i] != HttpSession.class) { paramPath = paramPath + "/:param" + (i + 1); continue; } for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation instanceof Param) { paramPath = TString.assembly(paramPath, "/:", ((Param) paramAnnotation).value()); } //如果没有指定方法, 参数包含 BodyParam 注解则指定请求方法为 POST if ((paramAnnotation instanceof BodyParam || paramAnnotation instanceof Body) && routeMethod.equals(HttpStatic.GET_STRING)) { routeMethod = HttpStatic.POST_STRING; } } } /** * 注册路由部分代码在下面 */ if (webServer.getHttpRouters().get(routeMethod) == null) { webServer.getHttpDispatcher().addRouteMethod(routeMethod); } //生成完整的路由,用来检查路由是否存在 routePath = HttpDispatcher.fixRoutePath(routePath); //这里这么做是为了处理 TreeMap 的 containsKey 方法的 bug Map routerMaps = new HashMap(); routerMaps.putAll(webServer.getHttpRouters().get(routeMethod)); //构造注解路由器 AnnotationRouter annotationRouter = new AnnotationRouter(annotationModule, routerClass, method, annonClassRouter, annonMethodRouter, routePath, paramPath); //1.注册路由, 处理不带参数的路由 if (paramPath.isEmpty()) { routePath = HttpDispatcher.fixRoutePath(routePath); String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routePath); //判断路由是否注册过 if (!routerMaps.containsKey(moduleRoutePath)) { //注册路由,不带路径参数的路由 annotationModule.otherMethod(routeMethod, routePath, annotationRouter); Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + moduleRoutePath); routeMethodNum++; } } //2.注册路由,带路径参数的路由 else { String routeParamPath = null; routeParamPath = routePath + paramPath; routeParamPath = HttpDispatcher.fixRoutePath(routeParamPath); String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routeParamPath); if (!routerMaps.containsKey(moduleRoutePath)) { annotationModule.otherMethod(routeMethod, routeParamPath, annotationRouter); Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + moduleRoutePath); routeMethodNum++; } } } } } } } } } //查找包含 WebSocket 注解的类 List<Class> webSocketClasses = TEnv.searchClassInEnv(annotationModule.getScanRouterPackage(), new Class[]{WebSocket.class}); for (Class webSocketClass : webSocketClasses) { if (TReflect.isExtendsByClass(webSocketClass, WebSocketRouter.class)) { WebSocket[] annonClassRouters = (WebSocket[]) webSocketClass.getAnnotationsByType(WebSocket.class); WebSocket annonClassRouter = annonClassRouters[0]; String classRouterPath = annonClassRouter.path().isEmpty() ? annonClassRouter.value() : annonClassRouter.path(); //使用类名指定默认路径 if (classRouterPath.isEmpty()) { //使用类名指定默认路径 classRouterPath = webSocketClass.getSimpleName(); } classRouterPath = HttpDispatcher.fixRoutePath(classRouterPath); String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + classRouterPath); if (!webServer.getWebSocketRouters().containsKey(moduleRoutePath)) { annotationModule.socket(classRouterPath, (WebSocketRouter) TReflect.newInstance(webSocketClass)); Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] add WebSocket: " + TString.leftPad(moduleRoutePath, 11, ' ')); routeMethodNum++; } } } if(routeMethodNum>0) { Logger.simple(TFile.getLineSeparator() + "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + "] Scan some class [" + scanRouterPackage + "] annotation by Router: " + routerClasses.size() + ". Register Router method annotation by route: " + routeMethodNum + "."); } } } catch (Exception e){ Logger.error("Scan router class error.", e); } } // /** // * 修复路由路径 // * @param routePath 路由路径 // * @return 修复后的路由路径 // */ // private static String fixAnnotationRoutePath(String routePath){ // routePath = routePath.startsWith("/") ? TString.removePrefix(routePath) : routePath; // routePath = routePath.endsWith("/") ? TString.removeSuffix(routePath) : routePath; // return routePath; // } /** * 将一个 Http 请求映射到一个类的方法调用 * @param request http 请求对象 * @param response http 响应对象 * @param clazz Class 对象 * @param method Method 对象 * @return 返回值 * @throws Exception 调用过程中的异常 */ public Object invokeRouterMethod(HttpRequest request, HttpResponse response, Class clazz, Method method) throws Exception { Object annotationObj = null; //如果是单例模式则使用预先初始话好的 if(this.classRouter.singleton()){ annotationObj = singletonObjs.get(clazz); } else { annotationObj = clazz.newInstance(); } Class[] parameterTypes = method.getParameterTypes(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); String bodyString = ""; Map bodyMap = null; if(request.body().size() > 0) { bodyString = request.body().getBodyString(); if(JSON.isJSONMap(bodyString)) { bodyMap = (Map) JSON.parse(bodyString); } } //准备参数 Object[] params = new Object[parameterTypes.length]; for(int i=0; i < parameterAnnotations.length; i++){ //请求对象 if(parameterTypes[i] == HttpRequest.class){ params[i] = request; continue; } //响应对象 if(parameterTypes[i] == HttpResponse.class){ params[i] = response; continue; } //会话对象 if(parameterTypes[i] == HttpSession.class){ params[i] = request.getSession(); continue; } for(Annotation annotation : parameterAnnotations[i]) { //请求的参数 if (annotation instanceof Param) { String paramName = ((Param) annotation).value(); try { params[i] = TString.toObject(request.getParameter(paramName), parameterTypes[i], true); continue; } catch (Exception e) { if(((Param) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Param [" + paramName + " = " + params[i] + "] error, data: " + request.getParameters(), e); } } } //请求的参数 if (annotation instanceof BodyParam) { String paramName = ((BodyParam) annotation).value(); try { if(bodyMap != null && bodyMap instanceof Map) { Object bodyParam = bodyMap.get(paramName); if(TReflect.isBasicType(bodyParam.getClass())) { params[i] = TString.toObject(bodyParam.toString(), parameterTypes[i], true); } else if(bodyParam instanceof Map){ params[i] = TReflect.getObjectFromMap(parameterTypes[i], (Map)bodyParam, true); } else { params[i] = bodyParam; } } continue; } catch (Exception e) { if(((BodyParam) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @BodyParam [" + paramName + " = " + params[i] + "] error, data: " + bodyMap.toString(), e); } } } //请求的头 if (annotation instanceof Head) { String headName = ((Head) annotation).value(); try { params[i] = TString.toObject(request.header().get(headName), parameterTypes[i], true); continue; } catch (Exception e) { if(((Head) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Head [" + headName + " = " + params[i] + "] error, data: " + request.header().toString(), e); } } } //请求的 Cookie if (annotation instanceof Cookie) { String cookieValue = null; String cookieName = ((Cookie) annotation).value(); try { org.voovan.http.message.packet.Cookie cookie = request.getCookie(cookieName); if (cookie != null) { cookieValue = cookie.getValue(); } params[i] = TString.toObject(cookieValue, parameterTypes[i], true); continue; } catch (Exception e) { if(((Cookie) annotation).isRequire()) { String cookieStr = request.cookies().parallelStream().map(cookie -> cookie.getName() + "=" + cookie.getName()).collect(Collectors.toList()).toString(); throw new AnnotationRouterException("Router annotation @Cookie [" + cookieName + " = " + params[i] + "] error, data: " + cookieStr, e); } } } //请求的 Body if (annotation instanceof Body) { try { params[i] = bodyMap == null ? TString.toObject(bodyString, parameterTypes[i], true) : TReflect.getObjectFromMap(parameterTypes[i], bodyMap, true); continue; } catch (Exception e) { if(((Body) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Body error \r\n data: " + bodyString, e); } } } //请求的头 if (annotation instanceof Attribute) { String attrName = ((Attribute) annotation).value(); try { params[i] = TString.toObject(request.getAttributes().get(attrName).toString(), parameterTypes[i], true); continue; } catch (Exception e) { if(((Attribute) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Attribute [" + attrName + " = " + params[i] + "] error, data: " + request.header().toString(), e); } } } //请求的头 if (annotation instanceof Session) { String sessionName = ((Session) annotation).value(); HttpSession httpSession = request.getSession(); try { if (httpSession.getAttribute(sessionName).getClass() == parameterTypes[i]) { params[i] = httpSession.getAttribute(sessionName); } continue; } catch (Exception e) { if(((Session) annotation).isRequire()) { throw new AnnotationRouterException("Router annotation @Session [" + sessionName + " = " + params[i] + "] error, data: " + httpSession.attributes().toString(), e); } } } } //没有注解的参数,按顺序处理 if(params[i]==null) { try { String value = request.getParameter("param" + String.valueOf(i + 1)); params[i] = TString.toObject(value, parameterTypes[i], true); continue; } catch (Exception e) { throw new AnnotationRouterException("Router sequential injection param " + request.getParameters().toString() + " error", e); } } } //调用方法 return TReflect.invokeMethod(annotationObj, method, params); } @Override public void process(HttpRequest request, HttpResponse response) throws Exception { AnnotationRouterFilter annotationRouterFilter = annotationModule.getAnnotationRouterFilter(); Object responseObj = null; Object fliterResult = null; try { //根据 Router 注解的标记设置响应的Content-Type response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpContentType.getHttpContentType(methodRoute.contentType())); //过滤器前置处理 if(annotationRouterFilter!=null) { fliterResult = annotationRouterFilter.beforeInvoke(request, response, this); } //null: 执行请求路由方法 //非 null: 作为 http 请求的响应直接返回 if(fliterResult == null) { responseObj = invokeRouterMethod(request, response, clazz, method); } else { responseObj = fliterResult; } //过滤器后置处理 if(annotationRouterFilter!=null) { fliterResult = annotationRouterFilter.afterInvoke(request, response, this, responseObj); if(fliterResult!=null) { responseObj = fliterResult; } } } catch(Exception e) { //过滤器拦截异常 if(annotationRouterFilter!=null) { fliterResult = annotationRouterFilter.exception(request, response, this, e); } if(fliterResult !=null) { responseObj = fliterResult; } else { if (e.getCause() != null) { Throwable cause = e.getCause(); if (cause instanceof Exception) { e = (Exception) cause; } } Logger.error(e); if (e instanceof AnnotationRouterException) { throw e; } else { throw new AnnotationRouterException("Process annotation router error. URL: " + request.protocol().getPath(), e); } } } if (responseObj != null) { if (responseObj instanceof String) { response.write((String) responseObj); } else if (responseObj instanceof byte[]) { response.write((byte[]) responseObj); } else { response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpContentType.getHttpContentType(HttpContentType.JSON)); response.write(JSON.toJSON(responseObj)); } } } }
imp: 注解路由优化
Web/src/main/java/org/voovan/http/server/module/annontationRouter/router/AnnotationRouter.java
imp: 注解路由优化
<ide><path>eb/src/main/java/org/voovan/http/server/module/annontationRouter/router/AnnotationRouter.java <ide> AnnotationRouter annotationRouter = new AnnotationRouter(annotationModule, routerClass, method, <ide> annonClassRouter, annonMethodRouter, routePath, paramPath); <ide> <add> String routeLog = null; <add> <ide> //1.注册路由, 处理不带参数的路由 <del> if (paramPath.isEmpty()) { <del> routePath = HttpDispatcher.fixRoutePath(routePath); <del> String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routePath); <del> //判断路由是否注册过 <del> if (!routerMaps.containsKey(moduleRoutePath)) { <del> //注册路由,不带路径参数的路由 <del> annotationModule.otherMethod(routeMethod, routePath, annotationRouter); <del> Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + <del> "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + <del> moduleRoutePath); <del> routeMethodNum++; <del> } <add> routePath = HttpDispatcher.fixRoutePath(routePath); <add> String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routePath); <add> //判断路由是否注册过 <add> if (!routerMaps.containsKey(moduleRoutePath)) { <add> //注册路由,不带路径参数的路由 <add> annotationModule.otherMethod(routeMethod, routePath, annotationRouter); <add> routeLog = "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + <add> "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + <add> moduleRoutePath; <add> routeMethodNum++; <ide> } <ide> <ide> //2.注册路由,带路径参数的路由 <del> else { <add> if(!paramPath.isEmpty()) { <ide> String routeParamPath = null; <ide> routeParamPath = routePath + paramPath; <ide> routeParamPath = HttpDispatcher.fixRoutePath(routeParamPath); <del> String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routeParamPath); <add> String moduleRouteParamPath = HttpDispatcher.fixRoutePath(modulePath + routeParamPath); <ide> <ide> if (!routerMaps.containsKey(moduleRoutePath)) { <ide> annotationModule.otherMethod(routeMethod, routeParamPath, annotationRouter); <ide> <del> Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + <add> routeLog = "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() + <ide> "] add Router: " + TString.rightPad(routeMethod, 8, ' ') + <del> moduleRoutePath); <del> routeMethodNum++; <add> moduleRouteParamPath; <ide> } <add> } <add> <add> if(routeLog!=null) { <add> Logger.simple(routeLog); <ide> } <ide> } <ide> } <ide> } <ide> } <ide> } <add> <ide> //查找包含 WebSocket 注解的类 <ide> List<Class> webSocketClasses = TEnv.searchClassInEnv(annotationModule.getScanRouterPackage(), new Class[]{WebSocket.class}); <ide> for (Class webSocketClass : webSocketClasses) {
Java
apache-2.0
60b2f0abb81647e3333816c1a91f7f9bc2eacc9f
0
ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,slisson/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,kool79/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,kool79/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,jagguli/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,diorcety/intellij-community,caot/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,hurricup/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,da1z/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ryano144/intellij-community,clumsy/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,robovm/robovm-studio,clumsy/intellij-community,nicolargo/intellij-community,semonte/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,supersven/intellij-community,amith01994/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,da1z/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,signed/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ryano144/intellij-community,holmes/intellij-community,tmpgit/intellij-community,allotria/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,petteyg/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,caot/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,diorcety/intellij-community,signed/intellij-community,wreckJ/intellij-community,slisson/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,izonder/intellij-community,suncycheng/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,izonder/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,caot/intellij-community,signed/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,adedayo/intellij-community,slisson/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,izonder/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,samthor/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,da1z/intellij-community,fnouama/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,allotria/intellij-community,da1z/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,samthor/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,caot/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,asedunov/intellij-community,caot/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,slisson/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,da1z/intellij-community,samthor/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,samthor/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,supersven/intellij-community,semonte/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,nicolargo/intellij-community,izonder/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,kool79/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,signed/intellij-community,holmes/intellij-community,kool79/intellij-community,FHannes/intellij-community,slisson/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,ibinti/intellij-community,slisson/intellij-community,blademainer/intellij-community,signed/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ibinti/intellij-community,semonte/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,xfournet/intellij-community,slisson/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,FHannes/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,izonder/intellij-community,kool79/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,samthor/intellij-community,xfournet/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ryano144/intellij-community,jagguli/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,kool79/intellij-community,robovm/robovm-studio,amith01994/intellij-community,robovm/robovm-studio,caot/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,fnouama/intellij-community,xfournet/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,allotria/intellij-community,semonte/intellij-community,supersven/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,allotria/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,caot/intellij-community,supersven/intellij-community,asedunov/intellij-community,fitermay/intellij-community,caot/intellij-community,samthor/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,clumsy/intellij-community,diorcety/intellij-community,supersven/intellij-community,robovm/robovm-studio,robovm/robovm-studio,slisson/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,kool79/intellij-community,petteyg/intellij-community,clumsy/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,da1z/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,semonte/intellij-community,jagguli/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ahb0327/intellij-community,kool79/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,signed/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,caot/intellij-community,asedunov/intellij-community,holmes/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,asedunov/intellij-community,supersven/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,signed/intellij-community,slisson/intellij-community,apixandru/intellij-community,apixandru/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,adedayo/intellij-community,retomerz/intellij-community,jagguli/intellij-community,kdwink/intellij-community,supersven/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,robovm/robovm-studio,kdwink/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,kdwink/intellij-community,dslomov/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,adedayo/intellij-community,caot/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,vladmm/intellij-community,samthor/intellij-community,slisson/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,izonder/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,hurricup/intellij-community,petteyg/intellij-community,diorcety/intellij-community,ibinti/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,hurricup/intellij-community,allotria/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,asedunov/intellij-community,fitermay/intellij-community,kool79/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,signed/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,caot/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,gnuhub/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 org.jetbrains.plugins.groovy.intentions.conversions.strings; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrStringImpl; import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil; /** * @author Max Medvedev */ public class ConvertMultilineStringToSingleLineIntention extends Intention { private static final Logger LOG = Logger.getInstance(ConvertMultilineStringToSingleLineIntention.class); public static final String hint = GroovyIntentionsBundle.message("convert.multiline.string.to.single.line.intention.name"); @Override protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { String quote = element.getText().substring(0, 1); StringBuilder buffer = new StringBuilder(); buffer.append(quote); GrExpression old; if (element instanceof GrLiteralImpl) { appendSimpleStringValue(element, buffer, quote); old = (GrExpression)element; } else { final GrStringImpl gstring = (GrStringImpl)element; for (GroovyPsiElement child : gstring.getAllContentParts()) { if (child instanceof GrStringContent) { appendSimpleStringValue(child, buffer, "\""); } else if (child instanceof GrStringInjection) { buffer.append(child.getText()); } } old = gstring; } buffer.append(quote); try { final int offset = editor.getCaretModel().getOffset(); final TextRange range = old.getTextRange(); int shift; if (range.getStartOffset() == offset) { shift = 0; } else if (range.getStartOffset() == offset - 1) { shift = -1; } else if (range.getEndOffset() == offset) { shift = -4; } else if (range.getEndOffset() == offset + 1) { shift = -3; } else { shift = -2; } final GrExpression newLiteral = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(buffer.toString()); old.replaceWithExpression(newLiteral, true); if (shift != 0) { editor.getCaretModel().moveToOffset(offset + shift); } } catch (IncorrectOperationException e) { LOG.error(e); } } private static void appendSimpleStringValue(PsiElement element, StringBuilder buffer, String quote) { final String text = GrStringUtil.removeQuotes(element.getText()); if ("'".equals(quote)) { GrStringUtil.escapeAndUnescapeSymbols(text, "\n'", "", buffer); } else { GrStringUtil.escapeAndUnescapeSymbols(text, "\"\n", "", buffer); } } @NotNull @Override protected PsiElementPredicate getElementPredicate() { return new PsiElementPredicate() { @Override public boolean satisfiedBy(PsiElement element) { return GrStringUtil.isMultilineStringElement(element.getNode()); } }; } }
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertMultilineStringToSingleLineIntention.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 org.jetbrains.plugins.groovy.intentions.conversions.strings; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrStringImpl; import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil; /** * @author Max Medvedev */ public class ConvertMultilineStringToSingleLineIntention extends Intention { private static final Logger LOG = Logger.getInstance(ConvertMultilineStringToSingleLineIntention.class); public static final String hint = GroovyIntentionsBundle.message("convert.multiline.string.to.single.line.intention.name"); @Override protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { String quote = element.getText().substring(0, 1); StringBuilder buffer = new StringBuilder(); buffer.append(quote); GrExpression old; if (element instanceof GrLiteralImpl) { appendSimpleStringValue(element, buffer, quote); old = (GrExpression)element; } else { final GrStringImpl gstring = (GrStringImpl)element; for (GroovyPsiElement child : gstring.getAllContentParts()) { if (child instanceof GrStringContent) { appendSimpleStringValue(child, buffer, "\""); } else if (child instanceof GrStringInjection) { buffer.append(child); } } old = gstring; } buffer.append(quote); try { final int offset = editor.getCaretModel().getOffset(); final TextRange range = old.getTextRange(); int shift; if (range.getStartOffset() == offset) { shift = 0; } else if (range.getStartOffset() == offset - 1) { shift = -1; } else if (range.getEndOffset() == offset) { shift = -4; } else if (range.getEndOffset() == offset + 1) { shift = -3; } else { shift = -2; } final GrExpression newLiteral = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(buffer.toString()); old.replaceWithExpression(newLiteral, true); if (shift != 0) { editor.getCaretModel().moveToOffset(offset + shift); } } catch (IncorrectOperationException e) { LOG.error(e); } } private static void appendSimpleStringValue(PsiElement element, StringBuilder buffer, String quote) { final String text = GrStringUtil.removeQuotes(element.getText()); if ("'".equals(quote)) { GrStringUtil.escapeAndUnescapeSymbols(text, "\n'", "", buffer); } else { GrStringUtil.escapeAndUnescapeSymbols(text, "\"\n", "", buffer); } } @NotNull @Override protected PsiElementPredicate getElementPredicate() { return new PsiElementPredicate() { @Override public boolean satisfiedBy(PsiElement element) { if (element instanceof GrLiteralImpl) { final ASTNode node = element.getFirstChild().getNode(); final IElementType type = node.getElementType(); if (type == GroovyTokenTypes.mSTRING_LITERAL) { return GrStringUtil.isMultilineStringElement(element.getNode()); } if (type == GroovyTokenTypes.mGSTRING_LITERAL) { return GrStringUtil.isMultilineStringElement(element.getNode()); } } else if (element instanceof GrStringImpl) { final GrStringImpl gstring = (GrStringImpl)element; final GrStringInjection[] injections = gstring.getInjections(); for (GrStringInjection injection : injections) { if (injection.getText().indexOf('\n') >= 0) return false; } return !gstring.isPlainString(); } return false; } }; } }
IDEA-109053 Convert to single-line string fixed
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertMultilineStringToSingleLineIntention.java
IDEA-109053 Convert to single-line string fixed
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/strings/ConvertMultilineStringToSingleLineIntention.java <ide> */ <ide> package org.jetbrains.plugins.groovy.intentions.conversions.strings; <ide> <del>import com.intellij.lang.ASTNode; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.editor.Editor; <ide> import com.intellij.openapi.project.Project; <ide> import com.intellij.openapi.util.TextRange; <ide> import com.intellij.psi.PsiElement; <del>import com.intellij.psi.tree.IElementType; <ide> import com.intellij.util.IncorrectOperationException; <ide> import org.jetbrains.annotations.NotNull; <ide> import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; <ide> import org.jetbrains.plugins.groovy.intentions.base.Intention; <ide> import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; <del>import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; <ide> import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; <ide> import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; <ide> import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; <ide> appendSimpleStringValue(child, buffer, "\""); <ide> } <ide> else if (child instanceof GrStringInjection) { <del> buffer.append(child); <add> buffer.append(child.getText()); <ide> } <ide> } <ide> old = gstring; <ide> return new PsiElementPredicate() { <ide> @Override <ide> public boolean satisfiedBy(PsiElement element) { <del> if (element instanceof GrLiteralImpl) { <del> final ASTNode node = element.getFirstChild().getNode(); <del> final IElementType type = node.getElementType(); <del> if (type == GroovyTokenTypes.mSTRING_LITERAL) { <del> return GrStringUtil.isMultilineStringElement(element.getNode()); <del> } <del> if (type == GroovyTokenTypes.mGSTRING_LITERAL) { <del> return GrStringUtil.isMultilineStringElement(element.getNode()); <del> } <del> } <del> else if (element instanceof GrStringImpl) { <del> final GrStringImpl gstring = (GrStringImpl)element; <del> final GrStringInjection[] injections = gstring.getInjections(); <del> for (GrStringInjection injection : injections) { <del> if (injection.getText().indexOf('\n') >= 0) return false; <del> } <del> return !gstring.isPlainString(); <del> } <del> return false; <add> return GrStringUtil.isMultilineStringElement(element.getNode()); <ide> } <ide> }; <ide> }
Java
mpl-2.0
8563cd0d72407b16142c2fa484e5bea013547c2c
0
servinglynk/servinglynk-hmis,servinglynk/servinglynk-hmis,servinglynk/hmis-lynk-open-source,servinglynk/servinglynk-hmis,servinglynk/hmis-lynk-open-source,servinglynk/servinglynk-hmis,servinglynk/hmis-lynk-open-source,servinglynk/hmis-lynk-open-source,servinglynk/servinglynk-hmis,servinglynk/hmis-lynk-open-source,servinglynk/servinglynk-hmis,servinglynk/hmis-lynk-open-source
package com.servinglynk.hmis.warehouse.model.v2015; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.WeakHashMap; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Type; import org.hibernate.proxy.HibernateProxy; import com.servinglynk.hmis.warehouse.model.base.BulkUpload; /** * Object mapping for hibernate-handled table: export. * * * @author autogenerated */ @Entity(name = "export_v2015") @Table(name = "export", catalog = "hmis", schema = "v2015") public class Export implements Cloneable, Serializable { /** Serial Version UID. */ private static final long serialVersionUID = 42126664696688958L; /** Use a WeakHashMap so entries will be garbage collected once all entities referring to a saved hash are garbage collected themselves. */ private static final Map<Serializable, java.util.UUID> SAVED_HASHES = Collections.synchronizedMap(new WeakHashMap<Serializable, java.util.UUID>()); /** hashCode temporary storage. */ private volatile java.util.UUID hashCode; /** Field mapping. */ private Set<EnrollmentCoc> enrollmentCocs = new HashSet<EnrollmentCoc>(); /** Field mapping. */ private Set<Affiliation> affiliations = new HashSet<Affiliation>(); /** Field mapping. */ private Set<Bedinventory> bedinventories = new HashSet<Bedinventory>(); /** Field mapping. */ private Set<BulkUpload> bulkUploads = new HashSet<BulkUpload>(); /** Field mapping. */ private Set<Client> clients = new HashSet<Client>(); /** Field mapping. */ private Set<ClientVeteranInfo> clientVeteranInfoes = new HashSet<ClientVeteranInfo>(); /** Field mapping. */ private Set<Coc> cocs = new HashSet<Coc>(); /** Field mapping. */ private Set<Contact> contacts = new HashSet<Contact>(); /** Field mapping. */ private Set<Dateofengagement> dateofengagements = new HashSet<Dateofengagement>(); /** Field mapping. */ private Set<Disabilities> disabilitieses = new HashSet<Disabilities>(); /** Field mapping. */ private Set<Domesticviolence> domesticviolences = new HashSet<Domesticviolence>(); /** Field mapping. */ private Set<Employment> employments = new HashSet<Employment>(); /** Field mapping. */ private LocalDateTime endDate; /** Field mapping. */ private Set<Enrollment> enrollments = new HashSet<Enrollment>(); /** Field mapping. */ private Set<Entryrhsp> entryrhsps = new HashSet<Entryrhsp>(); /** Field mapping. */ private Set<Entryrhy> entryrhies = new HashSet<Entryrhy>(); /** Field mapping. */ private Set<Entryssvf> entryssvfs = new HashSet<Entryssvf>(); /** Field mapping. */ private Set<Exit> exits = new HashSet<Exit>(); /** Field mapping. */ private Set<Exithousingassessment> exithousingassessments = new HashSet<Exithousingassessment>(); /** Field mapping. */ private Set<Exitpath> exitpaths = new HashSet<Exitpath>(); /** Field mapping. */ private Set<Exitrhy> exitrhies = new HashSet<Exitrhy>(); /** Field mapping. */ private Set<Education> educations = new HashSet<Education>(); /** Field mapping. */ private String exportdirective; /** Field mapping. */ private String exportperiodtype; /** Field mapping. */ private LocalDateTime exportDate; /** Field mapping. */ private java.util.UUID exportId; /** Field mapping. */ private Set<Funder> funders = new HashSet<Funder>(); /** Field mapping. */ private Set<Healthinsurance> healthinsurances = new HashSet<Healthinsurance>(); /** Field mapping. */ private Set<HealthStatus> healthStatuses = new HashSet<HealthStatus>(); /** Field mapping. */ private Set<Housingassessmentdisposition> housingassessmentdispositions = new HashSet<Housingassessmentdisposition>(); /** Field mapping. */ private java.util.UUID id; /** Field mapping. */ private Set<Incomeandsources> incomeandsourceses = new HashSet<Incomeandsources>(); /** Field mapping. */ private Set<Inventory> inventories = new HashSet<Inventory>(); /** Field mapping. */ private Set<Medicalassistance> medicalassistances = new HashSet<Medicalassistance>(); /** Field mapping. */ private Set<Noncashbenefits> noncashbenefitss = new HashSet<Noncashbenefits>(); /** Field mapping. */ private Set<Organization> organizations = new HashSet<Organization>(); /** Field mapping. */ private java.util.UUID parentId; /** Field mapping. */ private Set<Pathstatus> pathStatuses = new HashSet<Pathstatus>(); /** Field mapping. */ private Set<Project> projects = new HashSet<Project>(); /** Field mapping. */ private Set<Residentialmoveindate> residentialmoveindates = new HashSet<Residentialmoveindate>(); /** Field mapping. */ private Set<RhybcpStatus> rhybcpStatuses = new HashSet<RhybcpStatus>(); /** Field mapping. */ private Set<ServiceFaReferral> serviceFaReferrals = new HashSet<ServiceFaReferral>(); /** Field mapping. */ private Set<Site> sites = new HashSet<Site>(); /** Field mapping. */ private Source source; /** Field mapping. */ private LocalDateTime startDate; /** Field mapping. */ /** * Default constructor, mainly for hibernate use. */ public Export() { // Default constructor } /** Constructor taking a given ID. * @param id to set */ public Export(java.util.UUID id) { this.id = id; } /** Return the type of this class. Useful for when dealing with proxies. * @return Defining class. */ @Transient public Class<?> getClassType() { return Export.class; } /** * Return the value associated with the column: affiliation. * @return A Set&lt;Affiliation&gt; object (this.affiliation) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Affiliation> getAffiliations() { return this.affiliations; } /** * Adds a bi-directional link of type Affiliation to the affiliations set. * @param affiliation item to add */ public void addAffiliation(Affiliation affiliation) { affiliation.setExport(this); this.affiliations.add(affiliation); } /** * Set the value related to the column: affiliation. * @param affiliation the affiliation value you wish to set */ public void setAffiliations(final Set<Affiliation> affiliation) { this.affiliations = affiliation; } /** * Return the value associated with the column: bedinventory. * @return A Set&lt;Bedinventory&gt; object (this.bedinventory) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Bedinventory> getBedinventories() { return this.bedinventories; } /** * Adds a bi-directional link of type Bedinventory to the bedinventories set. * @param bedinventory item to add */ public void addBedinventory(Bedinventory bedinventory) { bedinventory.setExport(this); this.bedinventories.add(bedinventory); } /** * Set the value related to the column: bedinventory. * @param bedinventory the bedinventory value you wish to set */ public void setBedinventories(final Set<Bedinventory> bedinventory) { this.bedinventories = bedinventory; } /** * Return the value associated with the column: bulkUpload. * @return A Set&lt;BulkUpload&gt; object (this.bulkUpload) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "exportId" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<BulkUpload> getBulkUploads() { return this.bulkUploads; } /** * Adds a bi-directional link of type BulkUpload to the bulkUploads set. * @param bulkUpload item to add */ public void addBulkUpload(BulkUpload bulkUpload) { this.bulkUploads.add(bulkUpload); } /** * Set the value related to the column: bulkUpload. * @param bulkUpload the bulkUpload value you wish to set */ public void setBulkUploads(final Set<BulkUpload> bulkUpload) { this.bulkUploads = bulkUpload; } /** * Return the value associated with the column: client. * @return A Set&lt;Client&gt; object (this.client) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column(nullable = true ) public Set<Client> getClients() { return this.clients; } /** * Adds a bi-directional link of type Client to the clients set. * @param client item to add */ public void addClient(Client client) { client.setExport(this); this.clients.add(client); } /** * Set the value related to the column: client. * @param client the client value you wish to set */ public void setClients(final Set<Client> client) { this.clients = client; } /** * Return the value associated with the column: clientVeteranInfo. * @return A Set&lt;ClientVeteranInfo&gt; object (this.clientVeteranInfo) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<ClientVeteranInfo> getClientVeteranInfoes() { return this.clientVeteranInfoes; } /** * Adds a bi-directional link of type ClientVeteranInfo to the clientVeteranInfoes set. * @param clientVeteranInfo item to add */ public void addClientVeteranInfo(ClientVeteranInfo clientVeteranInfo) { clientVeteranInfo.setExport(this); this.clientVeteranInfoes.add(clientVeteranInfo); } /** * Set the value related to the column: clientVeteranInfo. * @param clientVeteranInfo the clientVeteranInfo value you wish to set */ public void setClientVeteranInfoes(final Set<ClientVeteranInfo> clientVeteranInfo) { this.clientVeteranInfoes = clientVeteranInfo; } /** * Return the value associated with the column: coc. * @return A Set&lt;Coc&gt; object (this.coc) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Coc> getCocs() { return this.cocs; } /** * Adds a bi-directional link of type Coc to the cocs set. * @param coc item to add */ public void addCoc(Coc coc) { coc.setExport(this); this.cocs.add(coc); } /** * Set the value related to the column: coc. * @param coc the coc value you wish to set */ public void setCocs(final Set<Coc> coc) { this.cocs = coc; } /** * Return the value associated with the column: contact. * @return A Set&lt;Contact&gt; object (this.contact) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Contact> getContacts() { return this.contacts; } /** * Adds a bi-directional link of type Contact to the contacts set. * @param contact item to add */ public void addContact(Contact contact) { contact.setExport(this); this.contacts.add(contact); } /** * Set the value related to the column: contact. * @param contact the contact value you wish to set */ public void setContacts(final Set<Contact> contact) { this.contacts = contact; } /** * Return the value associated with the column: dateofengagement. * @return A Set&lt;Dateofengagement&gt; object (this.dateofengagement) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Dateofengagement> getDateofengagements() { return this.dateofengagements; } /** * Adds a bi-directional link of type Dateofengagement to the dateofengagements set. * @param dateofengagement item to add */ public void addDateofengagement(Dateofengagement dateofengagement) { dateofengagement.setExport(this); this.dateofengagements.add(dateofengagement); } /** * Set the value related to the column: dateofengagement. * @param dateofengagement the dateofengagement value you wish to set */ public void setDateofengagements(final Set<Dateofengagement> dateofengagement) { this.dateofengagements = dateofengagement; } /** * Return the value associated with the column: disabilities. * @return A Set&lt;Disabilities&gt; object (this.disabilities) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Disabilities> getDisabilitieses() { return this.disabilitieses; } /** * Adds a bi-directional link of type Disabilities to the disabilitieses set. * @param disabilities item to add */ public void addDisabilities(Disabilities disabilities) { disabilities.setExport(this); this.disabilitieses.add(disabilities); } /** * Set the value related to the column: disabilities. * @param disabilities the disabilities value you wish to set */ public void setDisabilitieses(final Set<Disabilities> disabilities) { this.disabilitieses = disabilities; } /** * Return the value associated with the column: domesticviolence. * @return A Set&lt;Domesticviolence&gt; object (this.domesticviolence) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Domesticviolence> getDomesticviolences() { return this.domesticviolences; } /** * Adds a bi-directional link of type Domesticviolence to the domesticviolences set. * @param domesticviolence item to add */ public void addDomesticviolence(Domesticviolence domesticviolence) { domesticviolence.setExport(this); this.domesticviolences.add(domesticviolence); } /** * Set the value related to the column: domesticviolence. * @param domesticviolence the domesticviolence value you wish to set */ public void setDomesticviolences(final Set<Domesticviolence> domesticviolence) { this.domesticviolences = domesticviolence; } /** * Return the value associated with the column: employment. * @return A Set&lt;Employment&gt; object (this.employment) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Employment> getEmployments() { return this.employments; } /** * Adds a bi-directional link of type Employment to the employments set. * @param employment item to add */ public void addEmployment(Employment employment) { employment.setExport(this); this.employments.add(employment); } /** * Set the value related to the column: employment. * @param employment the employment value you wish to set */ public void setEmployments(final Set<Employment> employment) { this.employments = employment; } /** * Return the value associated with the column: endDate. * @return A LocalDateTime object (this.endDate) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "end_date" ) public LocalDateTime getEndDate() { return this.endDate; } /** * Set the value related to the column: endDate. * @param endDate the endDate value you wish to set */ public void setEndDate(final LocalDateTime endDate) { this.endDate = endDate; } /** * Return the value associated with the column: enrollment. * @return A Set&lt;Enrollment&gt; object (this.enrollment) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Enrollment> getEnrollments() { return this.enrollments; } /** * Adds a bi-directional link of type Enrollment to the enrollments set. * @param enrollment item to add */ public void addEnrollment(Enrollment enrollment) { enrollment.setExport(this); this.enrollments.add(enrollment); } /** * Set the value related to the column: enrollment. * @param enrollment the enrollment value you wish to set */ public void setEnrollments(final Set<Enrollment> enrollment) { this.enrollments = enrollment; } /** * Return the value associated with the column: entryrhsp. * @return A Set&lt;Entryrhsp&gt; object (this.entryrhsp) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Entryrhsp> getEntryrhsps() { return this.entryrhsps; } /** * Adds a bi-directional link of type Entryrhsp to the entryrhsps set. * @param entryrhsp item to add */ public void addEntryrhsp(Entryrhsp entryrhsp) { entryrhsp.setExport(this); this.entryrhsps.add(entryrhsp); } /** * Set the value related to the column: entryrhsp. * @param entryrhsp the entryrhsp value you wish to set */ public void setEntryrhsps(final Set<Entryrhsp> entryrhsp) { this.entryrhsps = entryrhsp; } /** * Return the value associated with the column: entryrhy. * @return A Set&lt;Entryrhy&gt; object (this.entryrhy) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Entryrhy> getEntryrhies() { return this.entryrhies; } /** * Adds a bi-directional link of type Entryrhy to the entryrhies set. * @param entryrhy item to add */ public void addEntryrhy(Entryrhy entryrhy) { entryrhy.setExport(this); this.entryrhies.add(entryrhy); } /** * Set the value related to the column: entryrhy. * @param entryrhy the entryrhy value you wish to set */ public void setEntryrhies(final Set<Entryrhy> entryrhy) { this.entryrhies = entryrhy; } /** * Return the value associated with the column: entryssvf. * @return A Set&lt;Entryssvf&gt; object (this.entryssvf) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Entryssvf> getEntryssvfs() { return this.entryssvfs; } /** * Adds a bi-directional link of type Entryssvf to the entryssvfs set. * @param entryssvf item to add */ public void addEntryssvf(Entryssvf entryssvf) { entryssvf.setExport(this); this.entryssvfs.add(entryssvf); } /** * Set the value related to the column: entryssvf. * @param entryssvf the entryssvf value you wish to set */ public void setEntryssvfs(final Set<Entryssvf> entryssvf) { this.entryssvfs = entryssvf; } /** * Return the value associated with the column: exit. * @return A Set&lt;Exit&gt; object (this.exit) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exit> getExits() { return this.exits; } /** * Adds a bi-directional link of type Exit to the exits set. * @param exit item to add */ public void addExit(Exit exit) { exit.setExport(this); this.exits.add(exit); } /** * Set the value related to the column: exit. * @param exit the exit value you wish to set */ public void setExits(final Set<Exit> exit) { this.exits = exit; } /** * Return the value associated with the column: exithousingassessment. * @return A Set&lt;Exithousingassessment&gt; object (this.exithousingassessment) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exithousingassessment> getExithousingassessments() { return this.exithousingassessments; } /** * Adds a bi-directional link of type Exithousingassessment to the exithousingassessments set. * @param exithousingassessment item to add */ public void addExithousingassessment(Exithousingassessment exithousingassessment) { exithousingassessment.setExport(this); this.exithousingassessments.add(exithousingassessment); } /** * Set the value related to the column: exithousingassessment. * @param exithousingassessment the exithousingassessment value you wish to set */ public void setExithousingassessments(final Set<Exithousingassessment> exithousingassessment) { this.exithousingassessments = exithousingassessment; } /** * Return the value associated with the column: exitpath. * @return A Set&lt;Exitpath&gt; object (this.exitpath) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exitpath> getExitpaths() { return this.exitpaths; } /** * Adds a bi-directional link of type Exitpath to the exitpaths set. * @param exitpath item to add */ public void addExitpath(Exitpath exitpath) { exitpath.setExport(this); this.exitpaths.add(exitpath); } /** * Set the value related to the column: exitpath. * @param exitpath the exitpath value you wish to set */ public void setExitpaths(final Set<Exitpath> exitpath) { this.exitpaths = exitpath; } /** * Return the value associated with the column: exitrhy. * @return A Set&lt;Exitrhy&gt; object (this.exitrhy) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exitrhy> getExitrhies() { return this.exitrhies; } /** * Adds a bi-directional link of type Exitrhy to the exitrhies set. * @param exitrhy item to add */ public void addExitrhy(Exitrhy exitrhy) { exitrhy.setExport(this); this.exitrhies.add(exitrhy); } /** * Set the value related to the column: exitrhy. * @param exitrhy the exitrhy value you wish to set */ public void setExitrhies(final Set<Exitrhy> exitrhy) { this.exitrhies = exitrhy; } /** * Return the value associated with the column: exportdirective. * @return A String object (this.exportdirective) */ @Basic( optional = true ) @Column( length = 2147483647 ) public String getExportdirective() { return this.exportdirective; } /** * Set the value related to the column: exportdirective. * @param exportdirective the exportdirective value you wish to set */ public void setExportdirective(final String exportdirective) { this.exportdirective = exportdirective; } /** * Return the value associated with the column: exportperiodtype. * @return A String object (this.exportperiodtype) */ @Basic( optional = true ) @Column( length = 2147483647 ) public String getExportperiodtype() { return this.exportperiodtype; } /** * Set the value related to the column: exportperiodtype. * @param exportperiodtype the exportperiodtype value you wish to set */ public void setExportperiodtype(final String exportperiodtype) { this.exportperiodtype = exportperiodtype; } /** * Return the value associated with the column: exportDate. * @return A LocalDateTime object (this.exportDate) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "export_date" ) public LocalDateTime getExportDate() { return this.exportDate; } /** * Set the value related to the column: exportDate. * @param exportDate the exportDate value you wish to set */ public void setExportDate(final LocalDateTime exportDate) { this.exportDate = exportDate; } /** * Return the value associated with the column: exportId. * @return A java.util.UUID object (this.exportId) */ @Basic( optional = true ) @Column( name = "export_id" ) @org.hibernate.annotations.Type(type="pg-uuid") public java.util.UUID getExportId() { return this.exportId; } /** * Set the value related to the column: exportId. * @param exportId the exportId value you wish to set */ public void setExportId(final java.util.UUID exportId) { this.exportId = exportId; } /** * Return the value associated with the column: funder. * @return A Set&lt;Funder&gt; object (this.funder) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Funder> getFunders() { return this.funders; } /** * Adds a bi-directional link of type Funder to the funders set. * @param funder item to add */ public void addFunder(Funder funder) { funder.setExport(this); this.funders.add(funder); } /** * Set the value related to the column: funder. * @param funder the funder value you wish to set */ public void setFunders(final Set<Funder> funder) { this.funders = funder; } /** * Return the value associated with the column: healthinsurance. * @return A Set&lt;Healthinsurance&gt; object (this.healthinsurance) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Healthinsurance> getHealthinsurances() { return this.healthinsurances; } /** * Adds a bi-directional link of type Healthinsurance to the healthinsurances set. * @param healthinsurance item to add */ public void addHealthinsurance(Healthinsurance healthinsurance) { healthinsurance.setExport(this); this.healthinsurances.add(healthinsurance); } /** * Set the value related to the column: healthinsurance. * @param healthinsurance the healthinsurance value you wish to set */ public void setHealthinsurances(final Set<Healthinsurance> healthinsurance) { this.healthinsurances = healthinsurance; } /** * Return the value associated with the column: healthStatus. * @return A Set&lt;HealthStatus&gt; object (this.healthStatus) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<HealthStatus> getHealthStatuses() { return this.healthStatuses; } /** * Adds a bi-directional link of type HealthStatus to the healthStatuses set. * @param healthStatus item to add */ public void addHealthStatus(HealthStatus healthStatus) { healthStatus.setExport(this); this.healthStatuses.add(healthStatus); } /** * Set the value related to the column: healthStatus. * @param healthStatus the healthStatus value you wish to set */ public void setHealthStatuses(final Set<HealthStatus> healthStatus) { this.healthStatuses = healthStatus; } /** * Return the value associated with the column: housingassessmentdisposition. * @return A Set&lt;Housingassessmentdisposition&gt; object (this.housingassessmentdisposition) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Housingassessmentdisposition> getHousingassessmentdispositions() { return this.housingassessmentdispositions; } /** * Adds a bi-directional link of type Housingassessmentdisposition to the housingassessmentdispositions set. * @param housingassessmentdisposition item to add */ public void addHousingassessmentdisposition(Housingassessmentdisposition housingassessmentdisposition) { housingassessmentdisposition.setExport(this); this.housingassessmentdispositions.add(housingassessmentdisposition); } /** * Set the value related to the column: housingassessmentdisposition. * @param housingassessmentdisposition the housingassessmentdisposition value you wish to set */ public void setHousingassessmentdispositions(final Set<Housingassessmentdisposition> housingassessmentdisposition) { this.housingassessmentdispositions = housingassessmentdisposition; } /** * Return the value associated with the column: id. * @return A java.util.UUID object (this.id) */ @Id @Basic( optional = false ) @Column( name = "id", nullable = false ) @org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType") public java.util.UUID getId() { return this.id; } /** * Set the value related to the column: id. * @param id the id value you wish to set */ public void setId(final java.util.UUID id) { // If we've just been persisted and hashCode has been // returned then make sure other entities with this // ID return the already returned hash code if ( (this.id == null ) && (id != null) && (this.hashCode != null) ) { SAVED_HASHES.put( id, this.hashCode ); } this.id = id; } /** * Return the value associated with the column: incomeandsources. * @return A Set&lt;Incomeandsources&gt; object (this.incomeandsources) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Incomeandsources> getIncomeandsourceses() { return this.incomeandsourceses; } /** * Adds a bi-directional link of type Incomeandsources to the incomeandsourceses set. * @param incomeandsources item to add */ public void addIncomeandsources(Incomeandsources incomeandsources) { incomeandsources.setExport(this); this.incomeandsourceses.add(incomeandsources); } /** * Set the value related to the column: incomeandsources. * @param incomeandsources the incomeandsources value you wish to set */ public void setIncomeandsourceses(final Set<Incomeandsources> incomeandsources) { this.incomeandsourceses = incomeandsources; } /** * Return the value associated with the column: inventory. * @return A Set&lt;Inventory&gt; object (this.inventory) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Inventory> getInventories() { return this.inventories; } /** * Adds a bi-directional link of type Inventory to the inventories set. * @param inventory item to add */ public void addInventory(Inventory inventory) { inventory.setExport(this); this.inventories.add(inventory); } /** * Set the value related to the column: inventory. * @param inventory the inventory value you wish to set */ public void setInventories(final Set<Inventory> inventory) { this.inventories = inventory; } /** * Return the value associated with the column: medicalassistance. * @return A Set&lt;Medicalassistance&gt; object (this.medicalassistance) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Medicalassistance> getMedicalassistances() { return this.medicalassistances; } /** * Adds a bi-directional link of type Medicalassistance to the medicalassistances set. * @param medicalassistance item to add */ public void addMedicalassistance(Medicalassistance medicalassistance) { medicalassistance.setExport(this); this.medicalassistances.add(medicalassistance); } /** * Set the value related to the column: medicalassistance. * @param medicalassistance the medicalassistance value you wish to set */ public void setMedicalassistances(final Set<Medicalassistance> medicalassistance) { this.medicalassistances = medicalassistance; } /** * Return the value associated with the column: noncashbenefits. * @return A Set&lt;Noncashbenefits&gt; object (this.noncashbenefits) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Noncashbenefits> getNoncashbenefitss() { return this.noncashbenefitss; } /** * Adds a bi-directional link of type Noncashbenefits to the noncashbenefitss set. * @param noncashbenefits item to add */ public void addNoncashbenefits(Noncashbenefits noncashbenefits) { noncashbenefits.setExport(this); this.noncashbenefitss.add(noncashbenefits); } /** * Set the value related to the column: noncashbenefits. * @param noncashbenefits the noncashbenefits value you wish to set */ public void setNoncashbenefitss(final Set<Noncashbenefits> noncashbenefits) { this.noncashbenefitss = noncashbenefits; } /* *//** * Return the value associated with the column: organization. * @return A Set&lt;Organization&gt; object (this.organization) *//* @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Organization> getOrganizations() { return this.organizations; } *//** * Adds a bi-directional link of type Organization to the organizations set. * @param organization item to add *//* public void addOrganization(Organization organization) { // organization.setExport(this); this.organizations.add(organization); } *//** * Set the value related to the column: organization. * @param organization the organization value you wish to set *//* public void setOrganizations(final Set<Organization> organization) { this.organizations = organization; }*/ /** * Return the value associated with the column: parentId. * @return A java.util.UUID object (this.parentId) */ @Basic( optional = true ) @Column( name = "parent_id" ) @org.hibernate.annotations.Type(type="pg-uuid") public java.util.UUID getParentId() { return this.parentId; } /** * Set the value related to the column: parentId. * @param parentId the parentId value you wish to set */ public void setParentId(final java.util.UUID parentId) { this.parentId = parentId; } /** * Return the value associated with the column: pathStatus. * @return A Set&lt;PathStatus&gt; object (this.pathStatus) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Pathstatus> getPathStatuses() { return this.pathStatuses; } /** * Adds a bi-directional link of type PathStatus to the pathStatuses set. * @param pathStatus item to add */ public void addPathStatus(Pathstatus pathStatus) { pathStatus.setExport(this); this.pathStatuses.add(pathStatus); } /** * Set the value related to the column: pathStatus. * @param pathStatus the pathStatus value you wish to set */ public void setPathStatuses(final Set<Pathstatus> pathStatus) { this.pathStatuses = pathStatus; } /** * Return the value associated with the column: project. * @return A Set&lt;Project&gt; object (this.project) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Project> getProjects() { return this.projects; } /** * Adds a bi-directional link of type Project to the projects set. * @param project item to add */ public void addProject(Project project) { project.setExport(this); this.projects.add(project); } /** * Set the value related to the column: project. * @param project the project value you wish to set */ public void setProjects(final Set<Project> project) { this.projects = project; } /** * Return the value associated with the column: residentialmoveindate. * @return A Set&lt;Residentialmoveindate&gt; object (this.residentialmoveindate) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Residentialmoveindate> getResidentialmoveindates() { return this.residentialmoveindates; } /** * Adds a bi-directional link of type Residentialmoveindate to the residentialmoveindates set. * @param residentialmoveindate item to add */ public void addResidentialmoveindate(Residentialmoveindate residentialmoveindate) { residentialmoveindate.setExport(this); this.residentialmoveindates.add(residentialmoveindate); } /** * Set the value related to the column: residentialmoveindate. * @param residentialmoveindate the residentialmoveindate value you wish to set */ public void setResidentialmoveindates(final Set<Residentialmoveindate> residentialmoveindate) { this.residentialmoveindates = residentialmoveindate; } /** * Return the value associated with the column: rhybcpStatus. * @return A Set&lt;RhybcpStatus&gt; object (this.rhybcpStatus) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<RhybcpStatus> getRhybcpStatuses() { return this.rhybcpStatuses; } /** * Adds a bi-directional link of type RhybcpStatus to the rhybcpStatuses set. * @param rhybcpStatus item to add */ public void addRhybcpStatus(RhybcpStatus rhybcpStatus) { rhybcpStatus.setExport(this); this.rhybcpStatuses.add(rhybcpStatus); } /** * Set the value related to the column: rhybcpStatus. * @param rhybcpStatus the rhybcpStatus value you wish to set */ public void setRhybcpStatuses(final Set<RhybcpStatus> rhybcpStatus) { this.rhybcpStatuses = rhybcpStatus; } /** * Return the value associated with the column: serviceFaReferral. * @return A Set&lt;ServiceFaReferral&gt; object (this.serviceFaReferral) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<ServiceFaReferral> getServiceFaReferrals() { return this.serviceFaReferrals; } /** * Adds a bi-directional link of type ServiceFaReferral to the serviceFaReferrals set. * @param serviceFaReferral item to add */ public void addServiceFaReferral(ServiceFaReferral serviceFaReferral) { serviceFaReferral.setExport(this); this.serviceFaReferrals.add(serviceFaReferral); } /** * Set the value related to the column: serviceFaReferral. * @param serviceFaReferral the serviceFaReferral value you wish to set */ public void setServiceFaReferrals(final Set<ServiceFaReferral> serviceFaReferral) { this.serviceFaReferrals = serviceFaReferral; } /** * Return the value associated with the column: site. * @return A Set&lt;Site&gt; object (this.site) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Site> getSites() { return this.sites; } /** * Adds a bi-directional link of type Site to the sites set. * @param site item to add */ public void addSite(Site site) { site.setExport(this); this.sites.add(site); } /** * Set the value related to the column: site. * @param site the site value you wish to set */ public void setSites(final Set<Site> site) { this.sites = site; } /** * Return the value associated with the column: source. * @return A Source object (this.source) */ @ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = true ) @JoinColumn(name = "source_id", nullable = true ) public Source getSource() { return this.source; } /** * Set the value related to the column: source. * @param source the source value you wish to set */ public void setSource(final Source source) { this.source = source; } /** * Return the value associated with the column: startDate. * @return A LocalDateTime object (this.startDate) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "start_date" ) public LocalDateTime getStartDate() { return this.startDate; } /** * Set the value related to the column: startDate. * @param startDate the startDate value you wish to set */ public void setStartDate(final LocalDateTime startDate) { this.startDate = startDate; } /** * Return the value associated with the column: enrollmentCoc. * @return A Set&lt;EnrollmentCoc&gt; object (this.enrollmentCoc) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.ALL}) @Basic( optional = false ) @Column( nullable = false ) public Set<EnrollmentCoc> getEnrollmentCocs() { return this.enrollmentCocs; } /** * Adds a bi-directional link of type EnrollmentCoc to the enrollmentCocs set. * @param enrollmentCoc item to add */ public void addEnrollmentCoc(EnrollmentCoc enrollmentCoc) { enrollmentCoc.setExport(this); this.enrollmentCocs.add(enrollmentCoc); } /** * Set the value related to the column: enrollmentCoc. * @param enrollmentCoc the enrollmentCoc value you wish to set */ public void setEnrollmentCocs(final Set<EnrollmentCoc> enrollmentCoc) { this.enrollmentCocs = enrollmentCoc; } /** * Return the value associated with the column: affiliation. * @return A Set&lt;Affiliation&gt; object (this.affiliation) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<com.servinglynk.hmis.warehouse.model.v2015.Education> getEducations() { return this.educations; } /** * Adds a bi-directional link of type Affiliation to the affiliations set. * @param affiliation item to add */ public void addEducation(Education education) { education.setExport(this); this.educations.add(education); } /** * Set the value related to the column: affiliation. * @param affiliation the affiliation value you wish to set */ public void setEducations(final Set<Education> education) { this.educations = education; } /** Field mapping. */ private LocalDateTime dateCreated; /** Field mapping. */ private LocalDateTime dateUpdated; /** Field mapping. */ private LocalDateTime dateCreatedFromSource; /** Field mapping. */ private LocalDateTime dateUpdatedFromSource; /** Field mapping. */ private String projectGroupCode; private UUID userId; /** * Return the value associated with the column: dateCreated. * @return A LocalDateTime object (this.dateCreated) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_created" ) public LocalDateTime getDateCreated() { return this.dateCreated; } /** * Set the value related to the column: dateCreated. * @param dateCreated the dateCreated value you wish to set */ public void setDateCreated(final LocalDateTime dateCreated) { this.dateCreated = dateCreated; } /** * Return the value associated with the column: dateUpdated. * @return A LocalDateTime object (this.dateUpdated) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_updated" ) public LocalDateTime getDateUpdated() { return this.dateUpdated; } /** * Set the value related to the column: dateUpdated. * @param dateUpdated the dateUpdated value you wish to set */ public void setDateUpdated(final LocalDateTime dateUpdated) { this.dateUpdated = dateUpdated; } @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_created_from_source" ) public LocalDateTime getDateCreatedFromSource() { return dateCreatedFromSource; } public void setDateCreatedFromSource(LocalDateTime dateCreatedFromSource) { this.dateCreatedFromSource = dateCreatedFromSource; } @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_updated_from_source" ) public LocalDateTime getDateUpdatedFromSource() { return dateUpdatedFromSource; } public void setDateUpdatedFromSource(LocalDateTime dateUpdatedFromSource) { this.dateUpdatedFromSource = dateUpdatedFromSource; } @Column(name="project_group_code") public String getProjectGroupCode() { return projectGroupCode; } public void setProjectGroupCode(String projectGroupCode) { this.projectGroupCode = projectGroupCode; } private boolean deleted; private boolean sync; @Column(name="sync") public boolean isSync() { return sync; } public void setSync(boolean sync) { this.sync = sync; } @Column(name="deleted") public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } private Long version; @Basic( optional = true ) @Column( name = "version", nullable = true ) public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Basic( optional = true ) @Column( name = "user_id", nullable = true ) @org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType") public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } /** Field mapping. */ /** * Deep copy. * @return cloned object * @throws CloneNotSupportedException on error */ @Override public Export clone() throws CloneNotSupportedException { final Export copy = (Export)super.clone(); if (this.getAffiliations() != null) { copy.getAffiliations().addAll(this.getAffiliations()); } if (this.getBedinventories() != null) { copy.getBedinventories().addAll(this.getBedinventories()); } if (this.getBulkUploads() != null) { copy.getBulkUploads().addAll(this.getBulkUploads()); } /* if (this.getClients() != null) { copy.getClients().addAll(this.getClients()); }*/ if (this.getClientVeteranInfoes() != null) { copy.getClientVeteranInfoes().addAll(this.getClientVeteranInfoes()); } if (this.getCocs() != null) { copy.getCocs().addAll(this.getCocs()); } if (this.getContacts() != null) { copy.getContacts().addAll(this.getContacts()); } if (this.getDateofengagements() != null) { copy.getDateofengagements().addAll(this.getDateofengagements()); } copy.setDateCreated(this.getDateCreated()); copy.setDateCreatedFromSource(this.getDateCreatedFromSource()); copy.setDateUpdated(this.getDateUpdated()); copy.setDateUpdatedFromSource(this.getDateUpdatedFromSource()); copy.setDeleted(this.isDeleted()); if (this.getDisabilitieses() != null) { copy.getDisabilitieses().addAll(this.getDisabilitieses()); } if (this.getDomesticviolences() != null) { copy.getDomesticviolences().addAll(this.getDomesticviolences()); } if (this.getEmployments() != null) { copy.getEmployments().addAll(this.getEmployments()); } copy.setEndDate(this.getEndDate()); if (this.getEnrollments() != null) { copy.getEnrollments().addAll(this.getEnrollments()); } if (this.getEntryrhsps() != null) { copy.getEntryrhsps().addAll(this.getEntryrhsps()); } if (this.getEntryrhies() != null) { copy.getEntryrhies().addAll(this.getEntryrhies()); } if (this.getEntryssvfs() != null) { copy.getEntryssvfs().addAll(this.getEntryssvfs()); } if (this.getExits() != null) { copy.getExits().addAll(this.getExits()); } if (this.getExithousingassessments() != null) { copy.getExithousingassessments().addAll(this.getExithousingassessments()); } if (this.getExitpaths() != null) { copy.getExitpaths().addAll(this.getExitpaths()); } if (this.getExitrhies() != null) { copy.getExitrhies().addAll(this.getExitrhies()); } copy.setExportdirective(this.getExportdirective()); copy.setExportperiodtype(this.getExportperiodtype()); copy.setExportDate(this.getExportDate()); copy.setExportId(this.getExportId()); if (this.getFunders() != null) { copy.getFunders().addAll(this.getFunders()); } if (this.getHealthinsurances() != null) { copy.getHealthinsurances().addAll(this.getHealthinsurances()); } if (this.getHealthStatuses() != null) { copy.getHealthStatuses().addAll(this.getHealthStatuses()); } if (this.getHousingassessmentdispositions() != null) { copy.getHousingassessmentdispositions().addAll(this.getHousingassessmentdispositions()); } copy.setId(this.getId()); if (this.getIncomeandsourceses() != null) { copy.getIncomeandsourceses().addAll(this.getIncomeandsourceses()); } if (this.getInventories() != null) { copy.getInventories().addAll(this.getInventories()); } if (this.getMedicalassistances() != null) { copy.getMedicalassistances().addAll(this.getMedicalassistances()); } if (this.getNoncashbenefitss() != null) { copy.getNoncashbenefitss().addAll(this.getNoncashbenefitss()); } /* if (this.getOrganizations() != null) { copy.getOrganizations().addAll(this.getOrganizations()); }*/ copy.setParentId(this.getParentId()); if (this.getPathStatuses() != null) { copy.getPathStatuses().addAll(this.getPathStatuses()); } if (this.getProjects() != null) { copy.getProjects().addAll(this.getProjects()); } copy.setProjectGroupCode(this.getProjectGroupCode()); if (this.getResidentialmoveindates() != null) { copy.getResidentialmoveindates().addAll(this.getResidentialmoveindates()); } if (this.getRhybcpStatuses() != null) { copy.getRhybcpStatuses().addAll(this.getRhybcpStatuses()); } if (this.getServiceFaReferrals() != null) { copy.getServiceFaReferrals().addAll(this.getServiceFaReferrals()); } if (this.getSites() != null) { copy.getSites().addAll(this.getSites()); } copy.setSource(this.getSource()); copy.setStartDate(this.getStartDate()); copy.setSync(this.isSync()); copy.setUserId(this.getUserId()); copy.setVersion(this.getVersion()); return copy; } /** Provides toString implementation. * @see java.lang.Object#toString() * @return String representation of this class. */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("dateCreated: " + this.getDateCreated() + ", "); sb.append("dateCreatedFromSource: " + this.getDateCreatedFromSource() + ", "); sb.append("dateUpdated: " + this.getDateUpdated() + ", "); sb.append("dateUpdatedFromSource: " + this.getDateUpdatedFromSource() + ", "); sb.append("deleted: " + this.isDeleted() + ", "); sb.append("endDate: " + this.getEndDate() + ", "); sb.append("exportdirective: " + this.getExportdirective() + ", "); sb.append("exportperiodtype: " + this.getExportperiodtype() + ", "); sb.append("exportDate: " + this.getExportDate() + ", "); sb.append("exportId: " + this.getExportId() + ", "); sb.append("id: " + this.getId() + ", "); sb.append("parentId: " + this.getParentId() + ", "); sb.append("projectGroupCode: " + this.getProjectGroupCode() + ", "); sb.append("startDate: " + this.getStartDate() + ", "); sb.append("sync: " + this.isSync() + ", "); sb.append("userId: " + this.getUserId() + ", "); sb.append("version: " + this.getVersion() + ", "); return sb.toString(); } /** Equals implementation. * @see java.lang.Object#equals(java.lang.Object) * @param aThat Object to compare with * @return true/false */ @Override public boolean equals(final Object aThat) { Object proxyThat = aThat; if ( this == aThat ) { return true; } if (aThat instanceof HibernateProxy) { // narrow down the proxy to the class we are dealing with. try { proxyThat = ((HibernateProxy) aThat).getHibernateLazyInitializer().getImplementation(); } catch (org.hibernate.ObjectNotFoundException e) { return false; } } if (aThat == null) { return false; } final Export that; try { that = (Export) proxyThat; if ( !(that.getClassType().equals(this.getClassType()))){ return false; } } catch (org.hibernate.ObjectNotFoundException e) { return false; } catch (ClassCastException e) { return false; } boolean result = true; result = result && (((this.getId() == null) && ( that.getId() == null)) || (this.getId() != null && this.getId().equals(that.getId()))); result = result && (((getDateCreated() == null) && (that.getDateCreated() == null)) || (getDateCreated() != null && getDateCreated().equals(that.getDateCreated()))); result = result && (((getDateCreatedFromSource() == null) && (that.getDateCreatedFromSource() == null)) || (getDateCreatedFromSource() != null && getDateCreatedFromSource().equals(that.getDateCreatedFromSource()))); result = result && (((getDateUpdated() == null) && (that.getDateUpdated() == null)) || (getDateUpdated() != null && getDateUpdated().equals(that.getDateUpdated()))); result = result && (((getDateUpdatedFromSource() == null) && (that.getDateUpdatedFromSource() == null)) || (getDateUpdatedFromSource() != null && getDateUpdatedFromSource().equals(that.getDateUpdatedFromSource()))); result = result && (((getEndDate() == null) && (that.getEndDate() == null)) || (getEndDate() != null && getEndDate().equals(that.getEndDate()))); result = result && (((getExportdirective() == null) && (that.getExportdirective() == null)) || (getExportdirective() != null && getExportdirective().equals(that.getExportdirective()))); result = result && (((getExportperiodtype() == null) && (that.getExportperiodtype() == null)) || (getExportperiodtype() != null && getExportperiodtype().equals(that.getExportperiodtype()))); result = result && (((getExportDate() == null) && (that.getExportDate() == null)) || (getExportDate() != null && getExportDate().equals(that.getExportDate()))); result = result && (((getExportId() == null) && (that.getExportId() == null)) || (getExportId() != null && getExportId().equals(that.getExportId()))); result = result && (((getParentId() == null) && (that.getParentId() == null)) || (getParentId() != null && getParentId().equals(that.getParentId()))); result = result && (((getProjectGroupCode() == null) && (that.getProjectGroupCode() == null)) || (getProjectGroupCode() != null && getProjectGroupCode().equals(that.getProjectGroupCode()))); result = result && (((getSource() == null) && (that.getSource() == null)) || (getSource() != null && getSource().getId().equals(that.getSource().getId()))); result = result && (((getStartDate() == null) && (that.getStartDate() == null)) || (getStartDate() != null && getStartDate().equals(that.getStartDate()))); result = result && (((getUserId() == null) && (that.getUserId() == null)) || (getUserId() != null && getUserId().equals(that.getUserId()))); result = result && (((getVersion() == null) && (that.getVersion() == null)) || (getVersion() != null && getVersion().equals(that.getVersion()))); return result; } }
hmis-model-v2015/src/main/java/com/servinglynk/hmis/warehouse/model/v2015/Export.java
package com.servinglynk.hmis.warehouse.model.v2015; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.WeakHashMap; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Type; import org.hibernate.proxy.HibernateProxy; import com.servinglynk.hmis.warehouse.model.base.BulkUpload; /** * Object mapping for hibernate-handled table: export. * * * @author autogenerated */ @Entity(name = "export_v2015") @Table(name = "export", catalog = "hmis", schema = "v2015") public class Export implements Cloneable, Serializable { /** Serial Version UID. */ private static final long serialVersionUID = 42126664696688958L; /** Use a WeakHashMap so entries will be garbage collected once all entities referring to a saved hash are garbage collected themselves. */ private static final Map<Serializable, java.util.UUID> SAVED_HASHES = Collections.synchronizedMap(new WeakHashMap<Serializable, java.util.UUID>()); /** hashCode temporary storage. */ private volatile java.util.UUID hashCode; /** Field mapping. */ private Set<EnrollmentCoc> enrollmentCocs = new HashSet<EnrollmentCoc>(); /** Field mapping. */ private Set<Affiliation> affiliations = new HashSet<Affiliation>(); /** Field mapping. */ private Set<Bedinventory> bedinventories = new HashSet<Bedinventory>(); /** Field mapping. */ private Set<BulkUpload> bulkUploads = new HashSet<BulkUpload>(); /** Field mapping. */ private Set<Client> clients = new HashSet<Client>(); /** Field mapping. */ private Set<ClientVeteranInfo> clientVeteranInfoes = new HashSet<ClientVeteranInfo>(); /** Field mapping. */ private Set<Coc> cocs = new HashSet<Coc>(); /** Field mapping. */ private Set<Contact> contacts = new HashSet<Contact>(); /** Field mapping. */ private Set<Dateofengagement> dateofengagements = new HashSet<Dateofengagement>(); /** Field mapping. */ private Set<Disabilities> disabilitieses = new HashSet<Disabilities>(); /** Field mapping. */ private Set<Domesticviolence> domesticviolences = new HashSet<Domesticviolence>(); /** Field mapping. */ private Set<Employment> employments = new HashSet<Employment>(); /** Field mapping. */ private LocalDateTime endDate; /** Field mapping. */ private Set<Enrollment> enrollments = new HashSet<Enrollment>(); /** Field mapping. */ private Set<Entryrhsp> entryrhsps = new HashSet<Entryrhsp>(); /** Field mapping. */ private Set<Entryrhy> entryrhies = new HashSet<Entryrhy>(); /** Field mapping. */ private Set<Entryssvf> entryssvfs = new HashSet<Entryssvf>(); /** Field mapping. */ private Set<Exit> exits = new HashSet<Exit>(); /** Field mapping. */ private Set<Exithousingassessment> exithousingassessments = new HashSet<Exithousingassessment>(); /** Field mapping. */ private Set<Exitpath> exitpaths = new HashSet<Exitpath>(); /** Field mapping. */ private Set<Exitrhy> exitrhies = new HashSet<Exitrhy>(); /** Field mapping. */ private Set<Education> educations = new HashSet<Education>(); /** Field mapping. */ private String exportdirective; /** Field mapping. */ private String exportperiodtype; /** Field mapping. */ private LocalDateTime exportDate; /** Field mapping. */ private java.util.UUID exportId; /** Field mapping. */ private Set<Funder> funders = new HashSet<Funder>(); /** Field mapping. */ private Set<Healthinsurance> healthinsurances = new HashSet<Healthinsurance>(); /** Field mapping. */ private Set<HealthStatus> healthStatuses = new HashSet<HealthStatus>(); /** Field mapping. */ private Set<Housingassessmentdisposition> housingassessmentdispositions = new HashSet<Housingassessmentdisposition>(); /** Field mapping. */ private java.util.UUID id; /** Field mapping. */ private Set<Incomeandsources> incomeandsourceses = new HashSet<Incomeandsources>(); /** Field mapping. */ private Set<Inventory> inventories = new HashSet<Inventory>(); /** Field mapping. */ private Set<Medicalassistance> medicalassistances = new HashSet<Medicalassistance>(); /** Field mapping. */ private Set<Noncashbenefits> noncashbenefitss = new HashSet<Noncashbenefits>(); /** Field mapping. */ private Set<Organization> organizations = new HashSet<Organization>(); /** Field mapping. */ private java.util.UUID parentId; /** Field mapping. */ private Set<Pathstatus> pathStatuses = new HashSet<Pathstatus>(); /** Field mapping. */ private Set<Project> projects = new HashSet<Project>(); /** Field mapping. */ private Set<Residentialmoveindate> residentialmoveindates = new HashSet<Residentialmoveindate>(); /** Field mapping. */ private Set<RhybcpStatus> rhybcpStatuses = new HashSet<RhybcpStatus>(); /** Field mapping. */ private Set<ServiceFaReferral> serviceFaReferrals = new HashSet<ServiceFaReferral>(); /** Field mapping. */ private Set<Site> sites = new HashSet<Site>(); /** Field mapping. */ private Source source; /** Field mapping. */ private LocalDateTime startDate; /** Field mapping. */ /** * Default constructor, mainly for hibernate use. */ public Export() { // Default constructor } /** Constructor taking a given ID. * @param id to set */ public Export(java.util.UUID id) { this.id = id; } /** Return the type of this class. Useful for when dealing with proxies. * @return Defining class. */ @Transient public Class<?> getClassType() { return Export.class; } /** * Return the value associated with the column: affiliation. * @return A Set&lt;Affiliation&gt; object (this.affiliation) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Affiliation> getAffiliations() { return this.affiliations; } /** * Adds a bi-directional link of type Affiliation to the affiliations set. * @param affiliation item to add */ public void addAffiliation(Affiliation affiliation) { affiliation.setExport(this); this.affiliations.add(affiliation); } /** * Set the value related to the column: affiliation. * @param affiliation the affiliation value you wish to set */ public void setAffiliations(final Set<Affiliation> affiliation) { this.affiliations = affiliation; } /** * Return the value associated with the column: bedinventory. * @return A Set&lt;Bedinventory&gt; object (this.bedinventory) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Bedinventory> getBedinventories() { return this.bedinventories; } /** * Adds a bi-directional link of type Bedinventory to the bedinventories set. * @param bedinventory item to add */ public void addBedinventory(Bedinventory bedinventory) { bedinventory.setExport(this); this.bedinventories.add(bedinventory); } /** * Set the value related to the column: bedinventory. * @param bedinventory the bedinventory value you wish to set */ public void setBedinventories(final Set<Bedinventory> bedinventory) { this.bedinventories = bedinventory; } /** * Return the value associated with the column: bulkUpload. * @return A Set&lt;BulkUpload&gt; object (this.bulkUpload) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<BulkUpload> getBulkUploads() { return this.bulkUploads; } /** * Adds a bi-directional link of type BulkUpload to the bulkUploads set. * @param bulkUpload item to add */ public void addBulkUpload(BulkUpload bulkUpload) { this.bulkUploads.add(bulkUpload); } /** * Set the value related to the column: bulkUpload. * @param bulkUpload the bulkUpload value you wish to set */ public void setBulkUploads(final Set<BulkUpload> bulkUpload) { this.bulkUploads = bulkUpload; } /** * Return the value associated with the column: client. * @return A Set&lt;Client&gt; object (this.client) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column(nullable = true ) public Set<Client> getClients() { return this.clients; } /** * Adds a bi-directional link of type Client to the clients set. * @param client item to add */ public void addClient(Client client) { client.setExport(this); this.clients.add(client); } /** * Set the value related to the column: client. * @param client the client value you wish to set */ public void setClients(final Set<Client> client) { this.clients = client; } /** * Return the value associated with the column: clientVeteranInfo. * @return A Set&lt;ClientVeteranInfo&gt; object (this.clientVeteranInfo) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<ClientVeteranInfo> getClientVeteranInfoes() { return this.clientVeteranInfoes; } /** * Adds a bi-directional link of type ClientVeteranInfo to the clientVeteranInfoes set. * @param clientVeteranInfo item to add */ public void addClientVeteranInfo(ClientVeteranInfo clientVeteranInfo) { clientVeteranInfo.setExport(this); this.clientVeteranInfoes.add(clientVeteranInfo); } /** * Set the value related to the column: clientVeteranInfo. * @param clientVeteranInfo the clientVeteranInfo value you wish to set */ public void setClientVeteranInfoes(final Set<ClientVeteranInfo> clientVeteranInfo) { this.clientVeteranInfoes = clientVeteranInfo; } /** * Return the value associated with the column: coc. * @return A Set&lt;Coc&gt; object (this.coc) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Coc> getCocs() { return this.cocs; } /** * Adds a bi-directional link of type Coc to the cocs set. * @param coc item to add */ public void addCoc(Coc coc) { coc.setExport(this); this.cocs.add(coc); } /** * Set the value related to the column: coc. * @param coc the coc value you wish to set */ public void setCocs(final Set<Coc> coc) { this.cocs = coc; } /** * Return the value associated with the column: contact. * @return A Set&lt;Contact&gt; object (this.contact) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Contact> getContacts() { return this.contacts; } /** * Adds a bi-directional link of type Contact to the contacts set. * @param contact item to add */ public void addContact(Contact contact) { contact.setExport(this); this.contacts.add(contact); } /** * Set the value related to the column: contact. * @param contact the contact value you wish to set */ public void setContacts(final Set<Contact> contact) { this.contacts = contact; } /** * Return the value associated with the column: dateofengagement. * @return A Set&lt;Dateofengagement&gt; object (this.dateofengagement) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Dateofengagement> getDateofengagements() { return this.dateofengagements; } /** * Adds a bi-directional link of type Dateofengagement to the dateofengagements set. * @param dateofengagement item to add */ public void addDateofengagement(Dateofengagement dateofengagement) { dateofengagement.setExport(this); this.dateofengagements.add(dateofengagement); } /** * Set the value related to the column: dateofengagement. * @param dateofengagement the dateofengagement value you wish to set */ public void setDateofengagements(final Set<Dateofengagement> dateofengagement) { this.dateofengagements = dateofengagement; } /** * Return the value associated with the column: disabilities. * @return A Set&lt;Disabilities&gt; object (this.disabilities) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Disabilities> getDisabilitieses() { return this.disabilitieses; } /** * Adds a bi-directional link of type Disabilities to the disabilitieses set. * @param disabilities item to add */ public void addDisabilities(Disabilities disabilities) { disabilities.setExport(this); this.disabilitieses.add(disabilities); } /** * Set the value related to the column: disabilities. * @param disabilities the disabilities value you wish to set */ public void setDisabilitieses(final Set<Disabilities> disabilities) { this.disabilitieses = disabilities; } /** * Return the value associated with the column: domesticviolence. * @return A Set&lt;Domesticviolence&gt; object (this.domesticviolence) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Domesticviolence> getDomesticviolences() { return this.domesticviolences; } /** * Adds a bi-directional link of type Domesticviolence to the domesticviolences set. * @param domesticviolence item to add */ public void addDomesticviolence(Domesticviolence domesticviolence) { domesticviolence.setExport(this); this.domesticviolences.add(domesticviolence); } /** * Set the value related to the column: domesticviolence. * @param domesticviolence the domesticviolence value you wish to set */ public void setDomesticviolences(final Set<Domesticviolence> domesticviolence) { this.domesticviolences = domesticviolence; } /** * Return the value associated with the column: employment. * @return A Set&lt;Employment&gt; object (this.employment) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Employment> getEmployments() { return this.employments; } /** * Adds a bi-directional link of type Employment to the employments set. * @param employment item to add */ public void addEmployment(Employment employment) { employment.setExport(this); this.employments.add(employment); } /** * Set the value related to the column: employment. * @param employment the employment value you wish to set */ public void setEmployments(final Set<Employment> employment) { this.employments = employment; } /** * Return the value associated with the column: endDate. * @return A LocalDateTime object (this.endDate) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "end_date" ) public LocalDateTime getEndDate() { return this.endDate; } /** * Set the value related to the column: endDate. * @param endDate the endDate value you wish to set */ public void setEndDate(final LocalDateTime endDate) { this.endDate = endDate; } /** * Return the value associated with the column: enrollment. * @return A Set&lt;Enrollment&gt; object (this.enrollment) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Enrollment> getEnrollments() { return this.enrollments; } /** * Adds a bi-directional link of type Enrollment to the enrollments set. * @param enrollment item to add */ public void addEnrollment(Enrollment enrollment) { enrollment.setExport(this); this.enrollments.add(enrollment); } /** * Set the value related to the column: enrollment. * @param enrollment the enrollment value you wish to set */ public void setEnrollments(final Set<Enrollment> enrollment) { this.enrollments = enrollment; } /** * Return the value associated with the column: entryrhsp. * @return A Set&lt;Entryrhsp&gt; object (this.entryrhsp) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Entryrhsp> getEntryrhsps() { return this.entryrhsps; } /** * Adds a bi-directional link of type Entryrhsp to the entryrhsps set. * @param entryrhsp item to add */ public void addEntryrhsp(Entryrhsp entryrhsp) { entryrhsp.setExport(this); this.entryrhsps.add(entryrhsp); } /** * Set the value related to the column: entryrhsp. * @param entryrhsp the entryrhsp value you wish to set */ public void setEntryrhsps(final Set<Entryrhsp> entryrhsp) { this.entryrhsps = entryrhsp; } /** * Return the value associated with the column: entryrhy. * @return A Set&lt;Entryrhy&gt; object (this.entryrhy) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Entryrhy> getEntryrhies() { return this.entryrhies; } /** * Adds a bi-directional link of type Entryrhy to the entryrhies set. * @param entryrhy item to add */ public void addEntryrhy(Entryrhy entryrhy) { entryrhy.setExport(this); this.entryrhies.add(entryrhy); } /** * Set the value related to the column: entryrhy. * @param entryrhy the entryrhy value you wish to set */ public void setEntryrhies(final Set<Entryrhy> entryrhy) { this.entryrhies = entryrhy; } /** * Return the value associated with the column: entryssvf. * @return A Set&lt;Entryssvf&gt; object (this.entryssvf) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Entryssvf> getEntryssvfs() { return this.entryssvfs; } /** * Adds a bi-directional link of type Entryssvf to the entryssvfs set. * @param entryssvf item to add */ public void addEntryssvf(Entryssvf entryssvf) { entryssvf.setExport(this); this.entryssvfs.add(entryssvf); } /** * Set the value related to the column: entryssvf. * @param entryssvf the entryssvf value you wish to set */ public void setEntryssvfs(final Set<Entryssvf> entryssvf) { this.entryssvfs = entryssvf; } /** * Return the value associated with the column: exit. * @return A Set&lt;Exit&gt; object (this.exit) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exit> getExits() { return this.exits; } /** * Adds a bi-directional link of type Exit to the exits set. * @param exit item to add */ public void addExit(Exit exit) { exit.setExport(this); this.exits.add(exit); } /** * Set the value related to the column: exit. * @param exit the exit value you wish to set */ public void setExits(final Set<Exit> exit) { this.exits = exit; } /** * Return the value associated with the column: exithousingassessment. * @return A Set&lt;Exithousingassessment&gt; object (this.exithousingassessment) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exithousingassessment> getExithousingassessments() { return this.exithousingassessments; } /** * Adds a bi-directional link of type Exithousingassessment to the exithousingassessments set. * @param exithousingassessment item to add */ public void addExithousingassessment(Exithousingassessment exithousingassessment) { exithousingassessment.setExport(this); this.exithousingassessments.add(exithousingassessment); } /** * Set the value related to the column: exithousingassessment. * @param exithousingassessment the exithousingassessment value you wish to set */ public void setExithousingassessments(final Set<Exithousingassessment> exithousingassessment) { this.exithousingassessments = exithousingassessment; } /** * Return the value associated with the column: exitpath. * @return A Set&lt;Exitpath&gt; object (this.exitpath) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exitpath> getExitpaths() { return this.exitpaths; } /** * Adds a bi-directional link of type Exitpath to the exitpaths set. * @param exitpath item to add */ public void addExitpath(Exitpath exitpath) { exitpath.setExport(this); this.exitpaths.add(exitpath); } /** * Set the value related to the column: exitpath. * @param exitpath the exitpath value you wish to set */ public void setExitpaths(final Set<Exitpath> exitpath) { this.exitpaths = exitpath; } /** * Return the value associated with the column: exitrhy. * @return A Set&lt;Exitrhy&gt; object (this.exitrhy) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Exitrhy> getExitrhies() { return this.exitrhies; } /** * Adds a bi-directional link of type Exitrhy to the exitrhies set. * @param exitrhy item to add */ public void addExitrhy(Exitrhy exitrhy) { exitrhy.setExport(this); this.exitrhies.add(exitrhy); } /** * Set the value related to the column: exitrhy. * @param exitrhy the exitrhy value you wish to set */ public void setExitrhies(final Set<Exitrhy> exitrhy) { this.exitrhies = exitrhy; } /** * Return the value associated with the column: exportdirective. * @return A String object (this.exportdirective) */ @Basic( optional = true ) @Column( length = 2147483647 ) public String getExportdirective() { return this.exportdirective; } /** * Set the value related to the column: exportdirective. * @param exportdirective the exportdirective value you wish to set */ public void setExportdirective(final String exportdirective) { this.exportdirective = exportdirective; } /** * Return the value associated with the column: exportperiodtype. * @return A String object (this.exportperiodtype) */ @Basic( optional = true ) @Column( length = 2147483647 ) public String getExportperiodtype() { return this.exportperiodtype; } /** * Set the value related to the column: exportperiodtype. * @param exportperiodtype the exportperiodtype value you wish to set */ public void setExportperiodtype(final String exportperiodtype) { this.exportperiodtype = exportperiodtype; } /** * Return the value associated with the column: exportDate. * @return A LocalDateTime object (this.exportDate) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "export_date" ) public LocalDateTime getExportDate() { return this.exportDate; } /** * Set the value related to the column: exportDate. * @param exportDate the exportDate value you wish to set */ public void setExportDate(final LocalDateTime exportDate) { this.exportDate = exportDate; } /** * Return the value associated with the column: exportId. * @return A java.util.UUID object (this.exportId) */ @Basic( optional = true ) @Column( name = "export_id" ) @org.hibernate.annotations.Type(type="pg-uuid") public java.util.UUID getExportId() { return this.exportId; } /** * Set the value related to the column: exportId. * @param exportId the exportId value you wish to set */ public void setExportId(final java.util.UUID exportId) { this.exportId = exportId; } /** * Return the value associated with the column: funder. * @return A Set&lt;Funder&gt; object (this.funder) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Funder> getFunders() { return this.funders; } /** * Adds a bi-directional link of type Funder to the funders set. * @param funder item to add */ public void addFunder(Funder funder) { funder.setExport(this); this.funders.add(funder); } /** * Set the value related to the column: funder. * @param funder the funder value you wish to set */ public void setFunders(final Set<Funder> funder) { this.funders = funder; } /** * Return the value associated with the column: healthinsurance. * @return A Set&lt;Healthinsurance&gt; object (this.healthinsurance) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Healthinsurance> getHealthinsurances() { return this.healthinsurances; } /** * Adds a bi-directional link of type Healthinsurance to the healthinsurances set. * @param healthinsurance item to add */ public void addHealthinsurance(Healthinsurance healthinsurance) { healthinsurance.setExport(this); this.healthinsurances.add(healthinsurance); } /** * Set the value related to the column: healthinsurance. * @param healthinsurance the healthinsurance value you wish to set */ public void setHealthinsurances(final Set<Healthinsurance> healthinsurance) { this.healthinsurances = healthinsurance; } /** * Return the value associated with the column: healthStatus. * @return A Set&lt;HealthStatus&gt; object (this.healthStatus) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<HealthStatus> getHealthStatuses() { return this.healthStatuses; } /** * Adds a bi-directional link of type HealthStatus to the healthStatuses set. * @param healthStatus item to add */ public void addHealthStatus(HealthStatus healthStatus) { healthStatus.setExport(this); this.healthStatuses.add(healthStatus); } /** * Set the value related to the column: healthStatus. * @param healthStatus the healthStatus value you wish to set */ public void setHealthStatuses(final Set<HealthStatus> healthStatus) { this.healthStatuses = healthStatus; } /** * Return the value associated with the column: housingassessmentdisposition. * @return A Set&lt;Housingassessmentdisposition&gt; object (this.housingassessmentdisposition) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Housingassessmentdisposition> getHousingassessmentdispositions() { return this.housingassessmentdispositions; } /** * Adds a bi-directional link of type Housingassessmentdisposition to the housingassessmentdispositions set. * @param housingassessmentdisposition item to add */ public void addHousingassessmentdisposition(Housingassessmentdisposition housingassessmentdisposition) { housingassessmentdisposition.setExport(this); this.housingassessmentdispositions.add(housingassessmentdisposition); } /** * Set the value related to the column: housingassessmentdisposition. * @param housingassessmentdisposition the housingassessmentdisposition value you wish to set */ public void setHousingassessmentdispositions(final Set<Housingassessmentdisposition> housingassessmentdisposition) { this.housingassessmentdispositions = housingassessmentdisposition; } /** * Return the value associated with the column: id. * @return A java.util.UUID object (this.id) */ @Id @Basic( optional = false ) @Column( name = "id", nullable = false ) @org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType") public java.util.UUID getId() { return this.id; } /** * Set the value related to the column: id. * @param id the id value you wish to set */ public void setId(final java.util.UUID id) { // If we've just been persisted and hashCode has been // returned then make sure other entities with this // ID return the already returned hash code if ( (this.id == null ) && (id != null) && (this.hashCode != null) ) { SAVED_HASHES.put( id, this.hashCode ); } this.id = id; } /** * Return the value associated with the column: incomeandsources. * @return A Set&lt;Incomeandsources&gt; object (this.incomeandsources) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Incomeandsources> getIncomeandsourceses() { return this.incomeandsourceses; } /** * Adds a bi-directional link of type Incomeandsources to the incomeandsourceses set. * @param incomeandsources item to add */ public void addIncomeandsources(Incomeandsources incomeandsources) { incomeandsources.setExport(this); this.incomeandsourceses.add(incomeandsources); } /** * Set the value related to the column: incomeandsources. * @param incomeandsources the incomeandsources value you wish to set */ public void setIncomeandsourceses(final Set<Incomeandsources> incomeandsources) { this.incomeandsourceses = incomeandsources; } /** * Return the value associated with the column: inventory. * @return A Set&lt;Inventory&gt; object (this.inventory) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Inventory> getInventories() { return this.inventories; } /** * Adds a bi-directional link of type Inventory to the inventories set. * @param inventory item to add */ public void addInventory(Inventory inventory) { inventory.setExport(this); this.inventories.add(inventory); } /** * Set the value related to the column: inventory. * @param inventory the inventory value you wish to set */ public void setInventories(final Set<Inventory> inventory) { this.inventories = inventory; } /** * Return the value associated with the column: medicalassistance. * @return A Set&lt;Medicalassistance&gt; object (this.medicalassistance) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Medicalassistance> getMedicalassistances() { return this.medicalassistances; } /** * Adds a bi-directional link of type Medicalassistance to the medicalassistances set. * @param medicalassistance item to add */ public void addMedicalassistance(Medicalassistance medicalassistance) { medicalassistance.setExport(this); this.medicalassistances.add(medicalassistance); } /** * Set the value related to the column: medicalassistance. * @param medicalassistance the medicalassistance value you wish to set */ public void setMedicalassistances(final Set<Medicalassistance> medicalassistance) { this.medicalassistances = medicalassistance; } /** * Return the value associated with the column: noncashbenefits. * @return A Set&lt;Noncashbenefits&gt; object (this.noncashbenefits) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Noncashbenefits> getNoncashbenefitss() { return this.noncashbenefitss; } /** * Adds a bi-directional link of type Noncashbenefits to the noncashbenefitss set. * @param noncashbenefits item to add */ public void addNoncashbenefits(Noncashbenefits noncashbenefits) { noncashbenefits.setExport(this); this.noncashbenefitss.add(noncashbenefits); } /** * Set the value related to the column: noncashbenefits. * @param noncashbenefits the noncashbenefits value you wish to set */ public void setNoncashbenefitss(final Set<Noncashbenefits> noncashbenefits) { this.noncashbenefitss = noncashbenefits; } /* *//** * Return the value associated with the column: organization. * @return A Set&lt;Organization&gt; object (this.organization) *//* @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Organization> getOrganizations() { return this.organizations; } *//** * Adds a bi-directional link of type Organization to the organizations set. * @param organization item to add *//* public void addOrganization(Organization organization) { // organization.setExport(this); this.organizations.add(organization); } *//** * Set the value related to the column: organization. * @param organization the organization value you wish to set *//* public void setOrganizations(final Set<Organization> organization) { this.organizations = organization; }*/ /** * Return the value associated with the column: parentId. * @return A java.util.UUID object (this.parentId) */ @Basic( optional = true ) @Column( name = "parent_id" ) @org.hibernate.annotations.Type(type="pg-uuid") public java.util.UUID getParentId() { return this.parentId; } /** * Set the value related to the column: parentId. * @param parentId the parentId value you wish to set */ public void setParentId(final java.util.UUID parentId) { this.parentId = parentId; } /** * Return the value associated with the column: pathStatus. * @return A Set&lt;PathStatus&gt; object (this.pathStatus) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Pathstatus> getPathStatuses() { return this.pathStatuses; } /** * Adds a bi-directional link of type PathStatus to the pathStatuses set. * @param pathStatus item to add */ public void addPathStatus(Pathstatus pathStatus) { pathStatus.setExport(this); this.pathStatuses.add(pathStatus); } /** * Set the value related to the column: pathStatus. * @param pathStatus the pathStatus value you wish to set */ public void setPathStatuses(final Set<Pathstatus> pathStatus) { this.pathStatuses = pathStatus; } /** * Return the value associated with the column: project. * @return A Set&lt;Project&gt; object (this.project) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Project> getProjects() { return this.projects; } /** * Adds a bi-directional link of type Project to the projects set. * @param project item to add */ public void addProject(Project project) { project.setExport(this); this.projects.add(project); } /** * Set the value related to the column: project. * @param project the project value you wish to set */ public void setProjects(final Set<Project> project) { this.projects = project; } /** * Return the value associated with the column: residentialmoveindate. * @return A Set&lt;Residentialmoveindate&gt; object (this.residentialmoveindate) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Residentialmoveindate> getResidentialmoveindates() { return this.residentialmoveindates; } /** * Adds a bi-directional link of type Residentialmoveindate to the residentialmoveindates set. * @param residentialmoveindate item to add */ public void addResidentialmoveindate(Residentialmoveindate residentialmoveindate) { residentialmoveindate.setExport(this); this.residentialmoveindates.add(residentialmoveindate); } /** * Set the value related to the column: residentialmoveindate. * @param residentialmoveindate the residentialmoveindate value you wish to set */ public void setResidentialmoveindates(final Set<Residentialmoveindate> residentialmoveindate) { this.residentialmoveindates = residentialmoveindate; } /** * Return the value associated with the column: rhybcpStatus. * @return A Set&lt;RhybcpStatus&gt; object (this.rhybcpStatus) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<RhybcpStatus> getRhybcpStatuses() { return this.rhybcpStatuses; } /** * Adds a bi-directional link of type RhybcpStatus to the rhybcpStatuses set. * @param rhybcpStatus item to add */ public void addRhybcpStatus(RhybcpStatus rhybcpStatus) { rhybcpStatus.setExport(this); this.rhybcpStatuses.add(rhybcpStatus); } /** * Set the value related to the column: rhybcpStatus. * @param rhybcpStatus the rhybcpStatus value you wish to set */ public void setRhybcpStatuses(final Set<RhybcpStatus> rhybcpStatus) { this.rhybcpStatuses = rhybcpStatus; } /** * Return the value associated with the column: serviceFaReferral. * @return A Set&lt;ServiceFaReferral&gt; object (this.serviceFaReferral) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<ServiceFaReferral> getServiceFaReferrals() { return this.serviceFaReferrals; } /** * Adds a bi-directional link of type ServiceFaReferral to the serviceFaReferrals set. * @param serviceFaReferral item to add */ public void addServiceFaReferral(ServiceFaReferral serviceFaReferral) { serviceFaReferral.setExport(this); this.serviceFaReferrals.add(serviceFaReferral); } /** * Set the value related to the column: serviceFaReferral. * @param serviceFaReferral the serviceFaReferral value you wish to set */ public void setServiceFaReferrals(final Set<ServiceFaReferral> serviceFaReferral) { this.serviceFaReferrals = serviceFaReferral; } /** * Return the value associated with the column: site. * @return A Set&lt;Site&gt; object (this.site) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<Site> getSites() { return this.sites; } /** * Adds a bi-directional link of type Site to the sites set. * @param site item to add */ public void addSite(Site site) { site.setExport(this); this.sites.add(site); } /** * Set the value related to the column: site. * @param site the site value you wish to set */ public void setSites(final Set<Site> site) { this.sites = site; } /** * Return the value associated with the column: source. * @return A Source object (this.source) */ @ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = true ) @JoinColumn(name = "source_id", nullable = true ) public Source getSource() { return this.source; } /** * Set the value related to the column: source. * @param source the source value you wish to set */ public void setSource(final Source source) { this.source = source; } /** * Return the value associated with the column: startDate. * @return A LocalDateTime object (this.startDate) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "start_date" ) public LocalDateTime getStartDate() { return this.startDate; } /** * Set the value related to the column: startDate. * @param startDate the startDate value you wish to set */ public void setStartDate(final LocalDateTime startDate) { this.startDate = startDate; } /** * Return the value associated with the column: enrollmentCoc. * @return A Set&lt;EnrollmentCoc&gt; object (this.enrollmentCoc) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.ALL}) @Basic( optional = false ) @Column( nullable = false ) public Set<EnrollmentCoc> getEnrollmentCocs() { return this.enrollmentCocs; } /** * Adds a bi-directional link of type EnrollmentCoc to the enrollmentCocs set. * @param enrollmentCoc item to add */ public void addEnrollmentCoc(EnrollmentCoc enrollmentCoc) { enrollmentCoc.setExport(this); this.enrollmentCocs.add(enrollmentCoc); } /** * Set the value related to the column: enrollmentCoc. * @param enrollmentCoc the enrollmentCoc value you wish to set */ public void setEnrollmentCocs(final Set<EnrollmentCoc> enrollmentCoc) { this.enrollmentCocs = enrollmentCoc; } /** * Return the value associated with the column: affiliation. * @return A Set&lt;Affiliation&gt; object (this.affiliation) */ @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = false ) @Column( nullable = false ) public Set<com.servinglynk.hmis.warehouse.model.v2015.Education> getEducations() { return this.educations; } /** * Adds a bi-directional link of type Affiliation to the affiliations set. * @param affiliation item to add */ public void addEducation(Education education) { education.setExport(this); this.educations.add(education); } /** * Set the value related to the column: affiliation. * @param affiliation the affiliation value you wish to set */ public void setEducations(final Set<Education> education) { this.educations = education; } /** Field mapping. */ private LocalDateTime dateCreated; /** Field mapping. */ private LocalDateTime dateUpdated; /** Field mapping. */ private LocalDateTime dateCreatedFromSource; /** Field mapping. */ private LocalDateTime dateUpdatedFromSource; /** Field mapping. */ private String projectGroupCode; private UUID userId; /** * Return the value associated with the column: dateCreated. * @return A LocalDateTime object (this.dateCreated) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_created" ) public LocalDateTime getDateCreated() { return this.dateCreated; } /** * Set the value related to the column: dateCreated. * @param dateCreated the dateCreated value you wish to set */ public void setDateCreated(final LocalDateTime dateCreated) { this.dateCreated = dateCreated; } /** * Return the value associated with the column: dateUpdated. * @return A LocalDateTime object (this.dateUpdated) */ @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_updated" ) public LocalDateTime getDateUpdated() { return this.dateUpdated; } /** * Set the value related to the column: dateUpdated. * @param dateUpdated the dateUpdated value you wish to set */ public void setDateUpdated(final LocalDateTime dateUpdated) { this.dateUpdated = dateUpdated; } @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_created_from_source" ) public LocalDateTime getDateCreatedFromSource() { return dateCreatedFromSource; } public void setDateCreatedFromSource(LocalDateTime dateCreatedFromSource) { this.dateCreatedFromSource = dateCreatedFromSource; } @Type(type="org.jadira.usertype.dateandtime.threeten.PersistentLocalDateTime") @Basic( optional = true ) @Column( name = "date_updated_from_source" ) public LocalDateTime getDateUpdatedFromSource() { return dateUpdatedFromSource; } public void setDateUpdatedFromSource(LocalDateTime dateUpdatedFromSource) { this.dateUpdatedFromSource = dateUpdatedFromSource; } @Column(name="project_group_code") public String getProjectGroupCode() { return projectGroupCode; } public void setProjectGroupCode(String projectGroupCode) { this.projectGroupCode = projectGroupCode; } private boolean deleted; private boolean sync; @Column(name="sync") public boolean isSync() { return sync; } public void setSync(boolean sync) { this.sync = sync; } @Column(name="deleted") public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } private Long version; @Basic( optional = true ) @Column( name = "version", nullable = true ) public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @Basic( optional = true ) @Column( name = "user_id", nullable = true ) @org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType") public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } /** Field mapping. */ /** * Deep copy. * @return cloned object * @throws CloneNotSupportedException on error */ @Override public Export clone() throws CloneNotSupportedException { final Export copy = (Export)super.clone(); if (this.getAffiliations() != null) { copy.getAffiliations().addAll(this.getAffiliations()); } if (this.getBedinventories() != null) { copy.getBedinventories().addAll(this.getBedinventories()); } if (this.getBulkUploads() != null) { copy.getBulkUploads().addAll(this.getBulkUploads()); } /* if (this.getClients() != null) { copy.getClients().addAll(this.getClients()); }*/ if (this.getClientVeteranInfoes() != null) { copy.getClientVeteranInfoes().addAll(this.getClientVeteranInfoes()); } if (this.getCocs() != null) { copy.getCocs().addAll(this.getCocs()); } if (this.getContacts() != null) { copy.getContacts().addAll(this.getContacts()); } if (this.getDateofengagements() != null) { copy.getDateofengagements().addAll(this.getDateofengagements()); } copy.setDateCreated(this.getDateCreated()); copy.setDateCreatedFromSource(this.getDateCreatedFromSource()); copy.setDateUpdated(this.getDateUpdated()); copy.setDateUpdatedFromSource(this.getDateUpdatedFromSource()); copy.setDeleted(this.isDeleted()); if (this.getDisabilitieses() != null) { copy.getDisabilitieses().addAll(this.getDisabilitieses()); } if (this.getDomesticviolences() != null) { copy.getDomesticviolences().addAll(this.getDomesticviolences()); } if (this.getEmployments() != null) { copy.getEmployments().addAll(this.getEmployments()); } copy.setEndDate(this.getEndDate()); if (this.getEnrollments() != null) { copy.getEnrollments().addAll(this.getEnrollments()); } if (this.getEntryrhsps() != null) { copy.getEntryrhsps().addAll(this.getEntryrhsps()); } if (this.getEntryrhies() != null) { copy.getEntryrhies().addAll(this.getEntryrhies()); } if (this.getEntryssvfs() != null) { copy.getEntryssvfs().addAll(this.getEntryssvfs()); } if (this.getExits() != null) { copy.getExits().addAll(this.getExits()); } if (this.getExithousingassessments() != null) { copy.getExithousingassessments().addAll(this.getExithousingassessments()); } if (this.getExitpaths() != null) { copy.getExitpaths().addAll(this.getExitpaths()); } if (this.getExitrhies() != null) { copy.getExitrhies().addAll(this.getExitrhies()); } copy.setExportdirective(this.getExportdirective()); copy.setExportperiodtype(this.getExportperiodtype()); copy.setExportDate(this.getExportDate()); copy.setExportId(this.getExportId()); if (this.getFunders() != null) { copy.getFunders().addAll(this.getFunders()); } if (this.getHealthinsurances() != null) { copy.getHealthinsurances().addAll(this.getHealthinsurances()); } if (this.getHealthStatuses() != null) { copy.getHealthStatuses().addAll(this.getHealthStatuses()); } if (this.getHousingassessmentdispositions() != null) { copy.getHousingassessmentdispositions().addAll(this.getHousingassessmentdispositions()); } copy.setId(this.getId()); if (this.getIncomeandsourceses() != null) { copy.getIncomeandsourceses().addAll(this.getIncomeandsourceses()); } if (this.getInventories() != null) { copy.getInventories().addAll(this.getInventories()); } if (this.getMedicalassistances() != null) { copy.getMedicalassistances().addAll(this.getMedicalassistances()); } if (this.getNoncashbenefitss() != null) { copy.getNoncashbenefitss().addAll(this.getNoncashbenefitss()); } /* if (this.getOrganizations() != null) { copy.getOrganizations().addAll(this.getOrganizations()); }*/ copy.setParentId(this.getParentId()); if (this.getPathStatuses() != null) { copy.getPathStatuses().addAll(this.getPathStatuses()); } if (this.getProjects() != null) { copy.getProjects().addAll(this.getProjects()); } copy.setProjectGroupCode(this.getProjectGroupCode()); if (this.getResidentialmoveindates() != null) { copy.getResidentialmoveindates().addAll(this.getResidentialmoveindates()); } if (this.getRhybcpStatuses() != null) { copy.getRhybcpStatuses().addAll(this.getRhybcpStatuses()); } if (this.getServiceFaReferrals() != null) { copy.getServiceFaReferrals().addAll(this.getServiceFaReferrals()); } if (this.getSites() != null) { copy.getSites().addAll(this.getSites()); } copy.setSource(this.getSource()); copy.setStartDate(this.getStartDate()); copy.setSync(this.isSync()); copy.setUserId(this.getUserId()); copy.setVersion(this.getVersion()); return copy; } /** Provides toString implementation. * @see java.lang.Object#toString() * @return String representation of this class. */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("dateCreated: " + this.getDateCreated() + ", "); sb.append("dateCreatedFromSource: " + this.getDateCreatedFromSource() + ", "); sb.append("dateUpdated: " + this.getDateUpdated() + ", "); sb.append("dateUpdatedFromSource: " + this.getDateUpdatedFromSource() + ", "); sb.append("deleted: " + this.isDeleted() + ", "); sb.append("endDate: " + this.getEndDate() + ", "); sb.append("exportdirective: " + this.getExportdirective() + ", "); sb.append("exportperiodtype: " + this.getExportperiodtype() + ", "); sb.append("exportDate: " + this.getExportDate() + ", "); sb.append("exportId: " + this.getExportId() + ", "); sb.append("id: " + this.getId() + ", "); sb.append("parentId: " + this.getParentId() + ", "); sb.append("projectGroupCode: " + this.getProjectGroupCode() + ", "); sb.append("startDate: " + this.getStartDate() + ", "); sb.append("sync: " + this.isSync() + ", "); sb.append("userId: " + this.getUserId() + ", "); sb.append("version: " + this.getVersion() + ", "); return sb.toString(); } /** Equals implementation. * @see java.lang.Object#equals(java.lang.Object) * @param aThat Object to compare with * @return true/false */ @Override public boolean equals(final Object aThat) { Object proxyThat = aThat; if ( this == aThat ) { return true; } if (aThat instanceof HibernateProxy) { // narrow down the proxy to the class we are dealing with. try { proxyThat = ((HibernateProxy) aThat).getHibernateLazyInitializer().getImplementation(); } catch (org.hibernate.ObjectNotFoundException e) { return false; } } if (aThat == null) { return false; } final Export that; try { that = (Export) proxyThat; if ( !(that.getClassType().equals(this.getClassType()))){ return false; } } catch (org.hibernate.ObjectNotFoundException e) { return false; } catch (ClassCastException e) { return false; } boolean result = true; result = result && (((this.getId() == null) && ( that.getId() == null)) || (this.getId() != null && this.getId().equals(that.getId()))); result = result && (((getDateCreated() == null) && (that.getDateCreated() == null)) || (getDateCreated() != null && getDateCreated().equals(that.getDateCreated()))); result = result && (((getDateCreatedFromSource() == null) && (that.getDateCreatedFromSource() == null)) || (getDateCreatedFromSource() != null && getDateCreatedFromSource().equals(that.getDateCreatedFromSource()))); result = result && (((getDateUpdated() == null) && (that.getDateUpdated() == null)) || (getDateUpdated() != null && getDateUpdated().equals(that.getDateUpdated()))); result = result && (((getDateUpdatedFromSource() == null) && (that.getDateUpdatedFromSource() == null)) || (getDateUpdatedFromSource() != null && getDateUpdatedFromSource().equals(that.getDateUpdatedFromSource()))); result = result && (((getEndDate() == null) && (that.getEndDate() == null)) || (getEndDate() != null && getEndDate().equals(that.getEndDate()))); result = result && (((getExportdirective() == null) && (that.getExportdirective() == null)) || (getExportdirective() != null && getExportdirective().equals(that.getExportdirective()))); result = result && (((getExportperiodtype() == null) && (that.getExportperiodtype() == null)) || (getExportperiodtype() != null && getExportperiodtype().equals(that.getExportperiodtype()))); result = result && (((getExportDate() == null) && (that.getExportDate() == null)) || (getExportDate() != null && getExportDate().equals(that.getExportDate()))); result = result && (((getExportId() == null) && (that.getExportId() == null)) || (getExportId() != null && getExportId().equals(that.getExportId()))); result = result && (((getParentId() == null) && (that.getParentId() == null)) || (getParentId() != null && getParentId().equals(that.getParentId()))); result = result && (((getProjectGroupCode() == null) && (that.getProjectGroupCode() == null)) || (getProjectGroupCode() != null && getProjectGroupCode().equals(that.getProjectGroupCode()))); result = result && (((getSource() == null) && (that.getSource() == null)) || (getSource() != null && getSource().getId().equals(that.getSource().getId()))); result = result && (((getStartDate() == null) && (that.getStartDate() == null)) || (getStartDate() != null && getStartDate().equals(that.getStartDate()))); result = result && (((getUserId() == null) && (that.getUserId() == null)) || (getUserId() != null && getUserId().equals(that.getUserId()))); result = result && (((getVersion() == null) && (that.getVersion() == null)) || (getVersion() != null && getVersion().equals(that.getVersion()))); return result; } }
Export and bulkuploads mapping configuration issue fixed
hmis-model-v2015/src/main/java/com/servinglynk/hmis/warehouse/model/v2015/Export.java
Export and bulkuploads mapping configuration issue fixed
<ide><path>mis-model-v2015/src/main/java/com/servinglynk/hmis/warehouse/model/v2015/Export.java <ide> * Return the value associated with the column: bulkUpload. <ide> * @return A Set&lt;BulkUpload&gt; object (this.bulkUpload) <ide> */ <del> @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "export" ) <add> @OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "exportId" ) <ide> @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) <ide> @Basic( optional = false ) <ide> @Column( nullable = false )
Java
mit
error: pathspec 'src/ctci/_7LinkedList_4.java' did not match any file(s) known to git
c1f178421c8da1136e0dd2762dcddbce85ea19e0
1
darshanhs90/Java-InterviewPrep,darshanhs90/Java-Coding
package ctci; import java.io.InputStreamReader; import java.util.Scanner; import ctci._2linkedList.Node; /*Implementation of CTCI 2.5*/ public class _7LinkedList_4 { public static void main(String[] args) { Scanner scanner =new Scanner(new InputStreamReader(System.in)); System.out.println("Enter First Number"); String firstNumberArray[]=scanner.nextLine().split(""); _2linkedList firstNumberList=new _2linkedList(); for (int i = firstNumberArray.length-1; i >0 ; i--) { firstNumberList.add(Integer.parseInt(firstNumberArray[i])); } System.out.println("Enter Second Number"); String secondNumberArray[]=scanner.nextLine().split(""); scanner.close(); _2linkedList secondNumberList=new _2linkedList(); for (int i = secondNumberArray.length-1; i >0 ; i--) { secondNumberList.add(Integer.parseInt(secondNumberArray[i])); } _2linkedList addedList=addNumbers(firstNumberList,secondNumberList); Node addedListNode=addedList.getHeadNode(); StringBuffer outputStringBuffer=new StringBuffer(); while(addedListNode!=null){ outputStringBuffer.append(addedListNode.data); addedListNode=addedListNode.next; } System.out.println(outputStringBuffer.reverse().toString()); } private static _2linkedList addNumbers(_2linkedList firstNumberList, _2linkedList secondNumberList) { int carry=0; Node firstNumberNode=firstNumberList.getHeadNode(); Node secondNumberNode=secondNumberList.getHeadNode(); _2linkedList finalList=new _2linkedList(); while(firstNumberNode!=null && secondNumberNode!=null) { String outputStringArray[]=String.valueOf((firstNumberNode.data+secondNumberNode.data+carry)).split(""); if(outputStringArray.length>2){ carry=Integer.parseInt(outputStringArray[1]); finalList.add(Integer.parseInt(outputStringArray[2])); } else{ carry=0; finalList.add(Integer.parseInt(outputStringArray[1])); } firstNumberNode=firstNumberNode.next; secondNumberNode=secondNumberNode.next; } Node mainNode; if(firstNumberNode==null) { mainNode=firstNumberNode; } else{ mainNode=secondNumberNode; } while(mainNode!=null){ String outputStringArray[]=String.valueOf((mainNode.data+carry)).split(""); if(outputStringArray.length>1){ carry=Integer.parseInt(outputStringArray[0]); finalList.add(Integer.parseInt(outputStringArray[1])); } else{ carry=0; finalList.add(Integer.parseInt(outputStringArray[0])); } mainNode=mainNode.next; } return finalList; } }
src/ctci/_7LinkedList_4.java
LinkedList 2.5 completed
src/ctci/_7LinkedList_4.java
LinkedList 2.5 completed
<ide><path>rc/ctci/_7LinkedList_4.java <add>package ctci; <add> <add>import java.io.InputStreamReader; <add>import java.util.Scanner; <add> <add>import ctci._2linkedList.Node; <add> <add> <add> <add> <add>/*Implementation of CTCI 2.5*/ <add>public class _7LinkedList_4 { <add> public static void main(String[] args) { <add> Scanner scanner =new Scanner(new InputStreamReader(System.in)); <add> System.out.println("Enter First Number"); <add> String firstNumberArray[]=scanner.nextLine().split(""); <add> _2linkedList firstNumberList=new _2linkedList(); <add> for (int i = firstNumberArray.length-1; i >0 ; i--) { <add> <add> firstNumberList.add(Integer.parseInt(firstNumberArray[i])); <add> } <add> System.out.println("Enter Second Number"); <add> String secondNumberArray[]=scanner.nextLine().split(""); <add> scanner.close(); <add> _2linkedList secondNumberList=new _2linkedList(); <add> for (int i = secondNumberArray.length-1; i >0 ; i--) { <add> secondNumberList.add(Integer.parseInt(secondNumberArray[i])); <add> } <add> _2linkedList addedList=addNumbers(firstNumberList,secondNumberList); <add> Node addedListNode=addedList.getHeadNode(); <add> StringBuffer outputStringBuffer=new StringBuffer(); <add> while(addedListNode!=null){ <add> outputStringBuffer.append(addedListNode.data); <add> addedListNode=addedListNode.next; <add> } <add> System.out.println(outputStringBuffer.reverse().toString()); <add> } <add> <add> private static _2linkedList addNumbers(_2linkedList firstNumberList, <add> _2linkedList secondNumberList) { <add> int carry=0; <add> Node firstNumberNode=firstNumberList.getHeadNode(); <add> Node secondNumberNode=secondNumberList.getHeadNode(); <add> _2linkedList finalList=new _2linkedList(); <add> while(firstNumberNode!=null && secondNumberNode!=null) <add> { <add> String outputStringArray[]=String.valueOf((firstNumberNode.data+secondNumberNode.data+carry)).split(""); <add> if(outputStringArray.length>2){ <add> carry=Integer.parseInt(outputStringArray[1]); <add> finalList.add(Integer.parseInt(outputStringArray[2])); <add> } <add> else{ <add> carry=0; <add> finalList.add(Integer.parseInt(outputStringArray[1])); <add> } <add> firstNumberNode=firstNumberNode.next; <add> secondNumberNode=secondNumberNode.next; <add> } <add> Node mainNode; <add> if(firstNumberNode==null) <add> { <add> mainNode=firstNumberNode; <add> } <add> else{ <add> mainNode=secondNumberNode; <add> } <add> while(mainNode!=null){ <add> String outputStringArray[]=String.valueOf((mainNode.data+carry)).split(""); <add> if(outputStringArray.length>1){ <add> carry=Integer.parseInt(outputStringArray[0]); <add> finalList.add(Integer.parseInt(outputStringArray[1])); <add> } <add> else{ <add> carry=0; <add> finalList.add(Integer.parseInt(outputStringArray[0])); <add> } <add> mainNode=mainNode.next; <add> } <add> return finalList; <add> } <add> <add> <add>}
Java
apache-2.0
error: pathspec 'main/src/com/pathtomani/screens/game/RightPaneLayout.java' did not match any file(s) known to git
8de3d1395f5f4a7d8d58c63d0e91c20d7b7002ab
1
BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani
/* * Copyright 2016 BurntGameProductions * * 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.pathtomani.screens.game; import com.badlogic.gdx.math.Rectangle; public class RightPaneLayout { public final float btnH; public final float btnW; public final float row0; public final float rowH; public final float col0; public RightPaneLayout(float r) { btnH = .07f; rowH = 1.1f * btnH; row0 = .1f; btnW = 3 * btnH; col0 = r - btnW; } public Rectangle buttonRect(int row) { float x = col0; float y = row0 + rowH * row; return new Rectangle(x, y, btnW, btnH); } }
main/src/com/pathtomani/screens/game/RightPaneLayout.java
Moving files to Managers.
main/src/com/pathtomani/screens/game/RightPaneLayout.java
Moving files to Managers.
<ide><path>ain/src/com/pathtomani/screens/game/RightPaneLayout.java <add>/* <add> * Copyright 2016 BurntGameProductions <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package com.pathtomani.screens.game; <add> <add>import com.badlogic.gdx.math.Rectangle; <add> <add>public class RightPaneLayout { <add> public final float btnH; <add> public final float btnW; <add> public final float row0; <add> public final float rowH; <add> public final float col0; <add> <add> public RightPaneLayout(float r) { <add> btnH = .07f; <add> rowH = 1.1f * btnH; <add> row0 = .1f; <add> btnW = 3 * btnH; <add> col0 = r - btnW; <add> } <add> <add> public Rectangle buttonRect(int row) { <add> float x = col0; <add> float y = row0 + rowH * row; <add> return new Rectangle(x, y, btnW, btnH); <add> } <add>}
Java
mit
c279f136ae44b0f15c15fb778ae6def9f4182c28
0
yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods
/* * FilterTaxaPropertiesPlugin.java * * Created on May 9, 2013 * */ package net.maizegenetics.baseplugins; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.plugindef.PluginEvent; import javax.swing.*; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.maizegenetics.pal.alignment.FilterAlignment; import net.maizegenetics.pal.ids.IdGroup; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.prefs.TasselPrefs; import org.apache.log4j.Logger; /** * * @author Terry */ public class FilterTaxaPropertiesPlugin extends AbstractPlugin { private static final Logger myLogger = Logger.getLogger(FilterTaxaPropertiesPlugin.class); private double myMinNotMissing = TasselPrefs.FILTER_TAXA_PROPS_PLUGIN_MIN_NOT_MISSING_DEFAULT; private double myMinHeterozygous = TasselPrefs.FILTER_TAXA_PROPS_PLUGIN_MIN_HET_DEFAULT; private double myMaxHeterozygous = TasselPrefs.FILTER_TAXA_PROPS_PLUGIN_MAX_HET_DEFAULT; /** * Creates a new instance of FilterTaxaPropertiesPlugin */ public FilterTaxaPropertiesPlugin(Frame parentFrame, boolean isInteractive) { super(parentFrame, isInteractive); } @Override public DataSet performFunction(DataSet input) { try { List<Datum> alignInList = input.getDataOfType(Alignment.class); if (alignInList.size() != 1) { String gpMessage = "Invalid selection. Please Select One Genotype Alignment."; if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), gpMessage); } else { myLogger.error(gpMessage); } return null; } Datum current = alignInList.get(0); Datum result = processDatum(current, isInteractive()); if (result != null) { DataSet output = new DataSet(result, this); fireDataSetReturned(new PluginEvent(output, FilterTaxaPropertiesPlugin.class)); return output; } else { return null; } } finally { fireProgress(100); } } private Datum processDatum(Datum inDatum, boolean isInteractive) { Alignment aa = (Alignment) inDatum.getData(); if (isInteractive) { FilterTaxaPropertiesDialog theDialog = new FilterTaxaPropertiesDialog(); theDialog.setLocationRelativeTo(getParentFrame()); theDialog.setVisible(true); if (theDialog.isCancel()) { return null; } myMinNotMissing = theDialog.getMinNotMissingProportion(); myMinHeterozygous = theDialog.getMinHeterozygousProportion(); myMaxHeterozygous = theDialog.getMaxHeterozygousProportion(); theDialog.dispose(); } Alignment result = getFilteredAlignment(aa); StringBuilder builder = new StringBuilder(); builder.append("Filter Alignment by Taxa Properties...\n"); builder.append(" Min. Proportion of Sites Present: "); builder.append(myMinNotMissing); builder.append("\n"); builder.append(" Heterozygous Proportion: "); builder.append(myMinHeterozygous); builder.append(" - "); builder.append(myMaxHeterozygous); builder.append("\n"); String theComment = builder.toString(); if (result == aa) { if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), "The Alignment is Unchanged."); } else { myLogger.warn("The Alignment is Unchanged: " + inDatum.getName()); } } if (result.getSequenceCount() != 0) { String theName = inDatum.getName() + "_" + result.getSequenceCount() + "Taxa"; myLogger.info("Resulting Number Sequences: " + result.getSequenceCount()); return new Datum(theName, result, theComment); } else { if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), "No remaining Taxa given filter parameters."); } else { myLogger.warn("No remaining Taxa given filter parameters."); } return null; } } private Alignment getFilteredAlignment(Alignment alignment) { int numSites = alignment.getSiteCount(); int numTaxa = alignment.getSequenceCount(); IdGroup ids = alignment.getIdGroup(); List<Identifier> keepTaxaList = new ArrayList<Identifier>(); for (int t = 0; t < numTaxa; t++) { progress((int) ((double) t / (double) numTaxa * 100.0), null); if (myMinNotMissing != 0.0) { int totalNotMissing = alignment.getTotalNotMissingForTaxon(t); double percentNotMissing = (double) totalNotMissing / (double) numSites; if (percentNotMissing < myMinNotMissing) { continue; } } if ((myMinHeterozygous != 0.0) || (myMaxHeterozygous != 1.0)) { int numHeterozygous = alignment.getHeterozygousCountForTaxon(t); int totalSitesNotMissing = alignment.getTotalNotMissingForTaxon(t); double percentHets = (double) numHeterozygous / (double) totalSitesNotMissing; if ((percentHets < myMinHeterozygous) || (percentHets > myMaxHeterozygous)) { continue; } } keepTaxaList.add(ids.getIdentifier(t)); } IdGroup taxa = new SimpleIdGroup(keepTaxaList); return FilterAlignment.getInstance(alignment, taxa, false); } public double getMinNotMissing() { return myMinNotMissing; } public void setMinNotMissing(int minNotMissing) { if ((minNotMissing < 0.0) || (minNotMissing > 1.0)) { throw new IllegalArgumentException("FilterTaxaPropertiesPlugin: setMinNotMissing: Value must be between 0.0 and 1.0: " + minNotMissing); } myMinNotMissing = minNotMissing; } public double getMinHeterozygous() { return myMinHeterozygous; } public void setMinHeterozygous(double minHeterozygous) { if ((minHeterozygous < 0.0) || (minHeterozygous > 1.0)) { throw new IllegalArgumentException("FilterTaxaPropertiesPlugin: setMinHeterozygous: Value must be between 0.0 and 1.0: " + minHeterozygous); } myMinHeterozygous = minHeterozygous; } public double getMaxHeterozygous() { return myMaxHeterozygous; } public void setMaxHeterozygous(double maxHeterozygous) { if ((maxHeterozygous < 0.0) || (maxHeterozygous > 1.0)) { throw new IllegalArgumentException("FilterTaxaPropertiesPlugin: setMaxHeterozygous: Value must be between 0.0 and 1.0: " + maxHeterozygous); } myMaxHeterozygous = maxHeterozygous; } /** * Icon for this plugin to be used in buttons, etc. * * @return ImageIcon */ public ImageIcon getIcon() { URL imageURL = FilterTaxaPropertiesPlugin.class.getResource("images/Filter_horizontal.gif"); if (imageURL == null) { return null; } else { return new ImageIcon(imageURL); } } /** * Button name for this plugin to be used in buttons, etc. * * @return String */ public String getButtonName() { return "Taxa"; } /** * Tool Tip Text for this plugin * * @return String */ public String getToolTipText() { return "Filter Alignment Based Taxa Properties"; } } class FilterTaxaPropertiesDialog extends JDialog { private static final int TEXT_FIELD_WIDTH = 10; private JTabbedPane myTabbedPane = new JTabbedPane(); private JTextField myMinNotMissingField = new JTextField(TEXT_FIELD_WIDTH); private JTextField myMinHeterozygousField = new JTextField(TEXT_FIELD_WIDTH); private JTextField myMaxHeterozygousField = new JTextField(TEXT_FIELD_WIDTH); private double myMinNotMissing = TasselPrefs.getFilterTaxaPropsMinNotMissingFreq(); private double myMinHeterozygous = TasselPrefs.getFilterTaxaPropsMinHetFreq(); private double myMaxHeterozygous = TasselPrefs.getFilterTaxaPropsMaxHetFreq(); private boolean myIsCancel = true; private boolean myIsOkToContinue = true; public FilterTaxaPropertiesDialog() { super((Frame) null, null, true); JButton okButton = new JButton(); okButton.setActionCommand("Ok"); okButton.setText("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myIsOkToContinue) { myIsCancel = false; setVisible(false); } else { myIsOkToContinue = true; } } }); JButton closeButton = new JButton(); closeButton.setText("Close"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myIsCancel = true; setVisible(false); } }); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(getLine("Min Proportion of Sites Present", myMinNotMissingField)); panel.add(getLine("Min Heterozygous Proportion", myMinHeterozygousField)); panel.add(getLine("Max Heterozygous Proportion", myMaxHeterozygousField)); myMinNotMissingField.setText(String.valueOf(myMinNotMissing)); myMinNotMissingField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { myMinNotMissing = focusLostParseFreq(myMinNotMissingField, myMinNotMissing); TasselPrefs.putFilterTaxaPropsMinNotMissingFreq(myMinNotMissing); } }); myMinHeterozygousField.setText(String.valueOf(myMinHeterozygous)); myMinHeterozygousField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { myMinHeterozygous = focusLostParseFreq(myMinHeterozygousField, myMinHeterozygous); TasselPrefs.putFilterTaxaPropsMinHetFreq(myMinHeterozygous); } }); myMaxHeterozygousField.setText(String.valueOf(myMaxHeterozygous)); myMaxHeterozygousField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { myMaxHeterozygous = focusLostParseFreq(myMaxHeterozygousField, myMaxHeterozygous); TasselPrefs.putFilterTaxaPropsMaxHetFreq(myMaxHeterozygous); } }); myTabbedPane.add(panel, "Filter Taxa by Properties"); JPanel pnlButtons = new JPanel(); pnlButtons.setLayout(new FlowLayout()); pnlButtons.add(okButton); pnlButtons.add(closeButton); getContentPane().add(myTabbedPane, BorderLayout.CENTER); getContentPane().add(pnlButtons, BorderLayout.SOUTH); pack(); } public boolean isCancel() { return myIsCancel; } public double getMinNotMissingProportion() { return myMinNotMissing; } public double getMinHeterozygousProportion() { return myMinHeterozygous; } public double getMaxHeterozygousProportion() { return myMaxHeterozygous; } private double focusLostParseFreq(JTextField field, double lastValue) { myIsOkToContinue = true; double freq = -0.1; try { String input = field.getText().trim(); if (input != null) { freq = Double.parseDouble(input); } if ((freq > 1.0) || (freq < 0.0)) { myIsOkToContinue = false; JOptionPane.showMessageDialog(this, "Please enter a value between 0.0 and 1.0"); freq = lastValue; } } catch (NumberFormatException nfe) { myIsOkToContinue = false; JOptionPane.showMessageDialog(this, "Please enter a value between 0.0 and 1.0"); freq = lastValue; } field.setText(String.valueOf(freq)); return freq; } private JPanel getLine(String label, JTextField ref) { JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT)); result.add(new JLabel(label)); ref.setEditable(true); ref.setHorizontalAlignment(JTextField.LEFT); ref.setAlignmentX(JTextField.CENTER_ALIGNMENT); ref.setAlignmentY(JTextField.CENTER_ALIGNMENT); ref.setMaximumSize(ref.getPreferredSize()); result.add(ref); return result; } }
src/net/maizegenetics/baseplugins/FilterTaxaPropertiesPlugin.java
/* * FilterTaxaPropertiesPlugin.java * * Created on May 9, 2013 * */ package net.maizegenetics.baseplugins; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.plugindef.PluginEvent; import javax.swing.*; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.net.URL; import java.util.ArrayList; import java.util.List; import net.maizegenetics.pal.alignment.FilterAlignment; import net.maizegenetics.pal.ids.IdGroup; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.prefs.TasselPrefs; import org.apache.log4j.Logger; /** * * @author Terry */ public class FilterTaxaPropertiesPlugin extends AbstractPlugin { private static final Logger myLogger = Logger.getLogger(FilterTaxaPropertiesPlugin.class); private double myMinNotMissing = TasselPrefs.FILTER_TAXA_PROPS_PLUGIN_MIN_NOT_MISSING_DEFAULT; private double myMinHeterozygous = TasselPrefs.FILTER_TAXA_PROPS_PLUGIN_MIN_HET_DEFAULT; private double myMaxHeterozygous = TasselPrefs.FILTER_TAXA_PROPS_PLUGIN_MAX_HET_DEFAULT; /** * Creates a new instance of FilterTaxaPropertiesPlugin */ public FilterTaxaPropertiesPlugin(Frame parentFrame, boolean isInteractive) { super(parentFrame, isInteractive); } @Override public DataSet performFunction(DataSet input) { try { List<Datum> alignInList = input.getDataOfType(Alignment.class); if (alignInList.size() != 1) { String gpMessage = "Invalid selection. Please Select One Genotype Alignment."; if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), gpMessage); } else { myLogger.error(gpMessage); } return null; } Datum current = alignInList.get(0); Datum result = processDatum(current, isInteractive()); if (result != null) { DataSet output = new DataSet(result, this); fireDataSetReturned(new PluginEvent(output, FilterTaxaPropertiesPlugin.class)); return output; } else { return null; } } finally { fireProgress(100); } } private Datum processDatum(Datum inDatum, boolean isInteractive) { Alignment aa = (Alignment) inDatum.getData(); if (isInteractive) { FilterTaxaPropertiesDialog theDialog = new FilterTaxaPropertiesDialog(); theDialog.setLocationRelativeTo(getParentFrame()); theDialog.setVisible(true); if (theDialog.isCancel()) { return null; } myMinNotMissing = theDialog.getMinNotMissingProportion(); myMinHeterozygous = theDialog.getMinHeterozygousProportion(); myMaxHeterozygous = theDialog.getMaxHeterozygousProportion(); theDialog.dispose(); } Alignment result = getFilteredAlignment(aa); StringBuilder builder = new StringBuilder(); builder.append("Filter Alignment by Taxa Properties...\n"); builder.append(" Min. Not Missing Proportion: "); builder.append(myMinNotMissing); builder.append("\n"); builder.append(" Heterozygous Proportion: "); builder.append(myMinHeterozygous); builder.append(" - "); builder.append(myMaxHeterozygous); builder.append("\n"); String theComment = builder.toString(); if (result == aa) { if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), "The Alignment is Unchanged."); } else { myLogger.warn("The Alignment is Unchanged: " + inDatum.getName()); } } if (result.getSequenceCount() != 0) { String theName = inDatum.getName() + "_" + result.getSequenceCount() + "Taxa"; myLogger.info("Resulting Number Sequences: " + result.getSequenceCount()); return new Datum(theName, result, theComment); } else { if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), "No remaining Taxa given filter parameters."); } else { myLogger.warn("No remaining Taxa given filter parameters."); } return null; } } private Alignment getFilteredAlignment(Alignment alignment) { int numSites = alignment.getSiteCount(); int numTaxa = alignment.getSequenceCount(); int totalGametes = numSites * 2; IdGroup ids = alignment.getIdGroup(); List<Identifier> keepTaxaList = new ArrayList<Identifier>(); for (int t = 0; t < numTaxa; t++) { progress((int) ((double) t / (double) numTaxa * 100.0), null); if (myMinNotMissing != 0.0) { int totalGametesNotMissing = alignment.getTotalGametesNotMissingForTaxon(t); double percentGametesNotMissing = (double) totalGametesNotMissing / (double) totalGametes; if (percentGametesNotMissing < myMinNotMissing) { continue; } } if ((myMinHeterozygous != 0.0) || (myMaxHeterozygous != 1.0)) { int numHeterozygous = alignment.getHeterozygousCountForTaxon(t); int totalSitesNotMissing = alignment.getTotalNotMissingForTaxon(t); double percentHets = (double) numHeterozygous / (double) totalSitesNotMissing; if ((percentHets < myMinHeterozygous) || (percentHets > myMaxHeterozygous)) { continue; } } keepTaxaList.add(ids.getIdentifier(t)); } IdGroup taxa = new SimpleIdGroup(keepTaxaList); return FilterAlignment.getInstance(alignment, taxa, false); } public double getMinNotMissing() { return myMinNotMissing; } public void setMinNotMissing(int minNotMissing) { if ((minNotMissing < 0.0) || (minNotMissing > 1.0)) { throw new IllegalArgumentException("FilterTaxaPropertiesPlugin: setMinNotMissing: Value must be between 0.0 and 1.0: " + minNotMissing); } myMinNotMissing = minNotMissing; } public double getMinHeterozygous() { return myMinHeterozygous; } public void setMinHeterozygous(double minHeterozygous) { if ((minHeterozygous < 0.0) || (minHeterozygous > 1.0)) { throw new IllegalArgumentException("FilterTaxaPropertiesPlugin: setMinHeterozygous: Value must be between 0.0 and 1.0: " + minHeterozygous); } myMinHeterozygous = minHeterozygous; } public double getMaxHeterozygous() { return myMaxHeterozygous; } public void setMaxHeterozygous(double maxHeterozygous) { if ((maxHeterozygous < 0.0) || (maxHeterozygous > 1.0)) { throw new IllegalArgumentException("FilterTaxaPropertiesPlugin: setMaxHeterozygous: Value must be between 0.0 and 1.0: " + maxHeterozygous); } myMaxHeterozygous = maxHeterozygous; } /** * Icon for this plugin to be used in buttons, etc. * * @return ImageIcon */ public ImageIcon getIcon() { URL imageURL = FilterTaxaPropertiesPlugin.class.getResource("images/Filter_horizontal.gif"); if (imageURL == null) { return null; } else { return new ImageIcon(imageURL); } } /** * Button name for this plugin to be used in buttons, etc. * * @return String */ public String getButtonName() { return "Taxa"; } /** * Tool Tip Text for this plugin * * @return String */ public String getToolTipText() { return "Filter Alignment Based Taxa Properties"; } } class FilterTaxaPropertiesDialog extends JDialog { private static final int TEXT_FIELD_WIDTH = 10; private JTabbedPane myTabbedPane = new JTabbedPane(); private JTextField myMinNotMissingField = new JTextField(TEXT_FIELD_WIDTH); private JTextField myMinHeterozygousField = new JTextField(TEXT_FIELD_WIDTH); private JTextField myMaxHeterozygousField = new JTextField(TEXT_FIELD_WIDTH); private double myMinNotMissing = TasselPrefs.getFilterTaxaPropsMinNotMissingFreq(); private double myMinHeterozygous = TasselPrefs.getFilterTaxaPropsMinHetFreq(); private double myMaxHeterozygous = TasselPrefs.getFilterTaxaPropsMaxHetFreq(); private boolean myIsCancel = true; private boolean myIsOkToContinue = true; public FilterTaxaPropertiesDialog() { super((Frame) null, null, true); JButton okButton = new JButton(); okButton.setActionCommand("Ok"); okButton.setText("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (myIsOkToContinue) { myIsCancel = false; setVisible(false); } else { myIsOkToContinue = true; } } }); JButton closeButton = new JButton(); closeButton.setText("Close"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myIsCancel = true; setVisible(false); } }); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(getLine("Min Gametes Not Missing Proportion", myMinNotMissingField)); panel.add(getLine("Min Heterozygous Proportion", myMinHeterozygousField)); panel.add(getLine("Max Heterozygous Proportion", myMaxHeterozygousField)); myMinNotMissingField.setText(String.valueOf(myMinNotMissing)); myMinNotMissingField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { myMinNotMissing = focusLostParseFreq(myMinNotMissingField, myMinNotMissing); TasselPrefs.putFilterTaxaPropsMinNotMissingFreq(myMinNotMissing); } }); myMinHeterozygousField.setText(String.valueOf(myMinHeterozygous)); myMinHeterozygousField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { myMinHeterozygous = focusLostParseFreq(myMinHeterozygousField, myMinHeterozygous); TasselPrefs.putFilterTaxaPropsMinHetFreq(myMinHeterozygous); } }); myMaxHeterozygousField.setText(String.valueOf(myMaxHeterozygous)); myMaxHeterozygousField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { myMaxHeterozygous = focusLostParseFreq(myMaxHeterozygousField, myMaxHeterozygous); TasselPrefs.putFilterTaxaPropsMaxHetFreq(myMaxHeterozygous); } }); myTabbedPane.add(panel, "Filter Taxa by Properties"); JPanel pnlButtons = new JPanel(); pnlButtons.setLayout(new FlowLayout()); pnlButtons.add(okButton); pnlButtons.add(closeButton); getContentPane().add(myTabbedPane, BorderLayout.CENTER); getContentPane().add(pnlButtons, BorderLayout.SOUTH); pack(); } public boolean isCancel() { return myIsCancel; } public double getMinNotMissingProportion() { return myMinNotMissing; } public double getMinHeterozygousProportion() { return myMinHeterozygous; } public double getMaxHeterozygousProportion() { return myMaxHeterozygous; } private double focusLostParseFreq(JTextField field, double lastValue) { myIsOkToContinue = true; double freq = -0.1; try { String input = field.getText().trim(); if (input != null) { freq = Double.parseDouble(input); } if ((freq > 1.0) || (freq < 0.0)) { myIsOkToContinue = false; JOptionPane.showMessageDialog(this, "Please enter a value between 0.0 and 1.0"); freq = lastValue; } } catch (NumberFormatException nfe) { myIsOkToContinue = false; JOptionPane.showMessageDialog(this, "Please enter a value between 0.0 and 1.0"); freq = lastValue; } field.setText(String.valueOf(freq)); return freq; } private JPanel getLine(String label, JTextField ref) { JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT)); result.add(new JLabel(label)); ref.setEditable(true); ref.setHorizontalAlignment(JTextField.LEFT); ref.setAlignmentX(JTextField.CENTER_ALIGNMENT); ref.setAlignmentY(JTextField.CENTER_ALIGNMENT); ref.setMaximumSize(ref.getPreferredSize()); result.add(ref); return result; } }
Changed label to "Min Proportion of Sites Present" and made this calculate missing only if both alleles missing (no based on gametes).
src/net/maizegenetics/baseplugins/FilterTaxaPropertiesPlugin.java
Changed label to "Min Proportion of Sites Present" and made this calculate missing only if both alleles missing (no based on gametes).
<ide><path>rc/net/maizegenetics/baseplugins/FilterTaxaPropertiesPlugin.java <ide> <ide> StringBuilder builder = new StringBuilder(); <ide> builder.append("Filter Alignment by Taxa Properties...\n"); <del> builder.append(" Min. Not Missing Proportion: "); <add> builder.append(" Min. Proportion of Sites Present: "); <ide> builder.append(myMinNotMissing); <ide> builder.append("\n"); <ide> builder.append(" Heterozygous Proportion: "); <ide> private Alignment getFilteredAlignment(Alignment alignment) { <ide> int numSites = alignment.getSiteCount(); <ide> int numTaxa = alignment.getSequenceCount(); <del> int totalGametes = numSites * 2; <ide> IdGroup ids = alignment.getIdGroup(); <ide> <ide> List<Identifier> keepTaxaList = new ArrayList<Identifier>(); <ide> progress((int) ((double) t / (double) numTaxa * 100.0), null); <ide> <ide> if (myMinNotMissing != 0.0) { <del> int totalGametesNotMissing = alignment.getTotalGametesNotMissingForTaxon(t); <del> double percentGametesNotMissing = (double) totalGametesNotMissing / (double) totalGametes; <del> if (percentGametesNotMissing < myMinNotMissing) { <add> int totalNotMissing = alignment.getTotalNotMissingForTaxon(t); <add> double percentNotMissing = (double) totalNotMissing / (double) numSites; <add> if (percentNotMissing < myMinNotMissing) { <ide> continue; <ide> } <ide> } <ide> JPanel panel = new JPanel(); <ide> panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); <ide> <del> panel.add(getLine("Min Gametes Not Missing Proportion", myMinNotMissingField)); <add> panel.add(getLine("Min Proportion of Sites Present", myMinNotMissingField)); <ide> panel.add(getLine("Min Heterozygous Proportion", myMinHeterozygousField)); <ide> panel.add(getLine("Max Heterozygous Proportion", myMaxHeterozygousField)); <ide>
Java
apache-2.0
330b7cc48cac5fb7529cb30fc8e7521c2e41b434
0
atoulme/xmlrpc
package org.apache.xmlrpc; /* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "XML-RPC" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.*; import java.util.*; import java.text.*; import org.xml.sax.*; /** * This abstract base class provides basic capabilities for XML-RPC, * like parsing of parameters or encoding Java objects into XML-RPC format. * Any XML parser with a <a href=http://www.megginson.com/SAX/> SAX</a> interface can * be used.<p> * XmlRpcServer and XmlRpcClient are the classes that actually implement an * XML-RCP server and client. * * @see XmlRpcServer * @see XmlRpcClient * * @author <a href="mailto:[email protected]">Hannes Wallnoefer</a> */ public abstract class XmlRpc extends HandlerBase { public static final String version = "Apache XML-RPC 1.0"; String methodName; // class name of SAX parser to use private static Class parserClass; private static Hashtable saxDrivers = new Hashtable (); static { saxDrivers.put ("xerces", "org.apache.xerces.parsers.SAXParser"); saxDrivers.put ("xp", "com.jclark.xml.sax.Driver"); saxDrivers.put ("ibm1", "com.ibm.xml.parser.SAXDriver"); saxDrivers.put ("ibm2", "com.ibm.xml.parsers.SAXParser"); saxDrivers.put ("aelfred", "com.microstar.xml.SAXDriver"); saxDrivers.put ("oracle1", "oracle.xml.parser.XMLParser"); saxDrivers.put ("oracle2", "oracle.xml.parser.v2.SAXParser"); saxDrivers.put ("openxml", "org.openxml.parser.XMLSAXParser"); } // the stack we're parsing our values into. Stack values; Value currentValue; // formats for parsing and generating dateTime values // DateFormat datetime; // now comes wapped into a synchronized class because dateFormat is not threadsafe static Formatter dateformat = new Formatter (); // used to collect character data of parameter values StringBuffer cdata; boolean readCdata; // XML RPC parameter types used for dataMode static final int STRING = 0; static final int INTEGER = 1; static final int BOOLEAN = 2; static final int DOUBLE = 3; static final int DATE = 4; static final int BASE64 = 5; static final int STRUCT = 6; static final int ARRAY = 7; // Error level + message int errorLevel; String errorMsg; static final int NONE = 0; static final int RECOVERABLE = 1; static final int FATAL = 2; // use HTTP keepalive? static boolean keepalive = false; // for debugging output public static boolean debug = false; final static String types[] = {"String", "Integer", "Boolean", "Double", "Date", "Base64", "Struct", "Array"}; // mapping between java encoding names and "real" names used in XML prolog. static String encoding = "ISO8859_1"; static Properties encodings = new Properties (); static { encodings.put ("UTF8", "UTF-8"); encodings.put ("ISO8859_1", "ISO-8859-1"); } /** * Set the SAX Parser to be used. The argument can either be the * full class name or a user friendly shortcut if the parser is * known to this class. The parsers that can currently be set by * shortcut are listed in the main documentation page. If you are * using another parser please send me the name of the SAX driver * and I'll include it in a future release. If setDriver() is * never called then the System property "sax.driver" is * consulted. If that is not defined the driver defaults to * OpenXML. */ public static void setDriver (String driver) throws ClassNotFoundException { String parserClassName = null; try { parserClassName = (String) saxDrivers.get (driver); if (parserClassName == null) parserClassName = driver; parserClass = Class.forName (parserClassName); } catch (ClassNotFoundException x) { throw new ClassNotFoundException ("SAX driver not found: "+ parserClassName); } } /** * Set the SAX Parser to be used by directly passing the Class object. */ public static void setDriver (Class driver) { parserClass = driver; } /** * Set the encoding of the XML. This should be the name of a Java encoding * contained in the encodings Hashtable. */ public static void setEncoding (String enc) { encoding = enc; } /** * Return the encoding, transforming to the canonical name if possible. */ public String getEncoding () { return encodings.getProperty (encoding, encoding); } /** * Switch debugging output on/off. */ public static void setDebug (boolean val) { debug = val; } /** * Switch HTTP keepalive on/off. */ public static void setKeepAlive (boolean val) { keepalive = val; } /** * get current HTTP keepalive mode. */ public static boolean getKeepAlive () { return keepalive; } /** * Parse the input stream. For each root level object, method * <code>objectParsed</code> is called. */ synchronized void parse (InputStream is) throws Exception { // reset values (XmlRpc objects are reusable) errorLevel = NONE; errorMsg = null; values = new Stack (); if (cdata == null) cdata = new StringBuffer (128); else cdata.setLength (0); readCdata = false; currentValue = null; long now = System.currentTimeMillis (); if (parserClass == null) { // try to get the name of the SAX driver from the System properties // setDriver (System.getProperty ( // "sax.driver", "org.apache.xerces.parsers.SAXParser")); setDriver (System.getProperty ( "sax.driver", "uk.co.wilson.xml.MinML")); } Parser parser = null; try { parser = (Parser) parserClass.newInstance (); } catch (NoSuchMethodError nsm) { // This is thrown if no constructor exists for the parser class // and is transformed into a regular exception. throw new Exception ("Can't create Parser: " + parserClass); } parser.setDocumentHandler (this); parser.setErrorHandler (this); if (debug) System.err.println("Beginning parsing XML input stream"); parser.parse (new InputSource (is)); if (debug) System.err.println ("Spent "+ (System.currentTimeMillis () - now) + " millis parsing"); } /** * Writes the XML representation of a supported Java object to * the XML writer. */ void writeObject (Object what, XmlWriter writer) { writer.startElement ("value"); if (what == null) { throw new RuntimeException ("null value not supported by XML-RPC"); } else if (what instanceof String) { writer.chardata (what.toString ()); } else if (what instanceof Integer) { writer.startElement ("int"); writer.write (what.toString ()); writer.endElement ("int"); } else if (what instanceof Boolean) { writer.startElement ("boolean"); writer.write (((Boolean) what).booleanValue () ? "1" : "0"); writer.endElement ("boolean"); } else if (what instanceof Double || what instanceof Float) { writer.startElement ("double"); writer.write (what.toString ()); writer.endElement ("double"); } else if (what instanceof Date) { writer.startElement ("dateTime.iso8601"); Date d = (Date) what; writer.write (dateformat.format (d)); writer.endElement ("dateTime.iso8601"); } else if (what instanceof byte[]) { writer.startElement ("base64"); writer.write (Base64.encode ((byte[]) what)); writer.endElement ("base64"); } else if (what instanceof Vector) { writer.startElement ("array"); writer.startElement ("data"); Vector v = (Vector) what; int l2 = v.size (); for (int i2 = 0; i2 < l2; i2++) writeObject (v.elementAt (i2), writer); writer.endElement ("data"); writer.endElement ("array"); } else if (what instanceof Hashtable) { writer.startElement ("struct"); Hashtable h = (Hashtable) what; for (Enumeration e = h.keys (); e.hasMoreElements ();) { String nextkey = (String) e.nextElement (); Object nextval = h.get (nextkey); writer.startElement ("member"); writer.startElement ("name"); writer.write (nextkey); writer.endElement ("name"); writeObject (nextval, writer); writer.endElement ("member"); } writer.endElement ("struct"); } else throw new RuntimeException ("unsupported Java type: " + what.getClass ()); writer.endElement ("value"); } /** * This method is called when a root level object has been parsed. */ abstract void objectParsed (Object what); //////////////////////////////////////////////////////////////// // methods called by XML parser /** * Method called by SAX driver. */ public void characters (char ch[], int start, int length) throws SAXException { if (!readCdata) return; cdata.append (ch, start, length); } /** * Method called by SAX driver. */ public void endElement (String name) throws SAXException { if (debug) System.err.println ("endElement: "+name); // finalize character data, if appropriate if (currentValue != null && readCdata) { currentValue.characterData (cdata.toString ()); cdata.setLength (0); readCdata = false; } if ("value".equals (name)) { int depth = values.size (); // Only handle top level objects or objects contained in arrays here. // For objects contained in structs, wait for </member> (see code below). if (depth < 2 || values.elementAt (depth - 2).hashCode () != STRUCT) { Value v = currentValue; values.pop (); if (depth < 2) { // This is a top-level object objectParsed (v.value); currentValue = null; } else { // add object to sub-array; if current container is a struct, add later (at </member>) currentValue = (Value) values.peek (); currentValue.endElement (v); } } } // Handle objects contained in structs. if ("member".equals (name)) { Value v = currentValue; values.pop (); currentValue = (Value) values.peek (); currentValue.endElement (v); } else if ("methodName".equals (name)) { methodName = cdata.toString (); cdata.setLength (0); readCdata = false; } } /** * Method called by SAX driver. */ public void startElement (String name, AttributeList atts) throws SAXException { if (debug) System.err.println ("startElement: "+name); if ("value".equals (name)) { // System.err.println ("starting value"); Value v = new Value (); values.push (v); currentValue = v; // cdata object is reused cdata.setLength(0); readCdata = true; } else if ("methodName".equals (name)) { cdata.setLength(0); readCdata = true; } else if ("name".equals (name)) { cdata.setLength(0); readCdata = true; } else if ("string".equals (name)) { // currentValue.setType (STRING); cdata.setLength(0); readCdata = true; } else if ("i4".equals (name) || "int".equals (name)) { currentValue.setType (INTEGER); cdata.setLength(0); readCdata = true; } else if ("boolean".equals (name)) { currentValue.setType (BOOLEAN); cdata.setLength(0); readCdata = true; } else if ("double".equals (name)) { currentValue.setType (DOUBLE); cdata.setLength(0); readCdata = true; } else if ("dateTime.iso8601".equals (name)) { currentValue.setType (DATE); cdata.setLength(0); readCdata = true; } else if ("base64".equals (name)) { currentValue.setType (BASE64); cdata.setLength(0); readCdata = true; } else if ("struct".equals (name)) { currentValue.setType (STRUCT); } else if ("array".equals (name)) { currentValue.setType (ARRAY); } } public void error (SAXParseException e) throws SAXException { System.err.println ("Error parsing XML: "+e); errorLevel = RECOVERABLE; errorMsg = e.toString (); } public void fatalError(SAXParseException e) throws SAXException { System.err.println ("Fatal error parsing XML: "+e); errorLevel = FATAL; errorMsg = e.toString (); } /** * This represents a XML-RPC value parsed from the request. */ class Value { int type; Object value; // the name to use for the next member of struct values String nextMemberName; Hashtable struct; Vector array; /** * Constructor. */ public Value () { this.type = STRING; } /** * Notification that a new child element has been parsed. */ public void endElement (Value child) { switch (type) { case ARRAY: array.addElement (child.value); break; case STRUCT: struct.put (nextMemberName, child.value); } } /** * Set the type of this value. If it's a container, create the * corresponding java container. */ public void setType (int type) { // System.err.println ("setting type to "+types[type]); this.type = type; switch (type) { case ARRAY: value = array = new Vector (); break; case STRUCT: value = struct = new Hashtable (); break; } } /** * Set the character data for the element and interpret it * according to the element type. */ public void characterData (String cdata) { switch (type) { case INTEGER: value = new Integer (cdata.trim ()); break; case BOOLEAN: value = new Boolean ("1".equals (cdata.trim ())); break; case DOUBLE: value = new Double (cdata.trim ()); break; case DATE: try { value = dateformat.parse (cdata.trim ()); } catch (ParseException p) { // System.err.println ("Exception while parsing date: "+p); throw new RuntimeException (p.getMessage ()); } break; case BASE64: value = Base64.decode (cdata.toCharArray()); break; case STRING: value = cdata; break; case STRUCT: // this is the name to use for the next member of this struct nextMemberName = cdata; break; } } /** * This is a performance hack to get the type of a value * without casting the Object. It breaks the contract of * method hashCode, but it doesn't matter since Value objects * are never used as keys in Hashtables. */ public int hashCode () { return type; } public String toString () { return (types[type] + " element " + value); } } /** * A quick and dirty XML writer. */ class XmlWriter { StringBuffer buf; String enc; public XmlWriter (StringBuffer buf) { // The default encoding used for XML-RPC is ISO-8859-1 for pragmatical reasons. this (buf, encoding); } public XmlWriter (StringBuffer buf, String enc) { this.buf = buf; this.enc = enc; // get name of encoding for XML prolog String encName = encodings.getProperty (enc, enc); buf.append ("<?xml version=\"1.0\" encoding=\"" + encName + "\"?>"); } public void startElement (String elem) { buf.append ('<'); buf.append (elem); buf.append ('>'); } public void endElement (String elem) { buf.append ("</"); buf.append (elem); buf.append ('>'); } public void emptyElement (String elem) { buf.append ('<'); buf.append (elem); buf.append ("/>"); } public void chardata (String text) { int l = text.length (); for (int i = 0; i < l; i++) { char c = text.charAt (i); switch (c) { case '<' : buf.append ("&lt;"); break; case '>' : buf.append ("&gt;"); break; case '&' : buf.append ("&amp;"); break; default : buf.append (c); } } } public void write (char[] text) { buf.append (text); } public void write (String text) { buf.append (text); } public String toString () { return buf.toString (); } public byte[] getBytes () throws UnsupportedEncodingException { return buf.toString ().getBytes (enc); } } } /** * Wraps a <code>DateFormat</code> instance to provide thread safety. */ class Formatter { private DateFormat f; public Formatter () { f = new SimpleDateFormat ("yyyyMMdd'T'HH:mm:ss"); } public synchronized String format (Date d) { return f.format (d); } public synchronized Date parse (String s) throws ParseException { return f.parse (s); } }
src/java/org/apache/xmlrpc/XmlRpc.java
package org.apache.xmlrpc; /* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "XML-RPC" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.*; import java.util.*; import java.text.*; import org.xml.sax.*; /** * This abstract base class provides basic capabilities for XML-RPC, * like parsing of parameters or encoding Java objects into XML-RPC format. * Any XML parser with a <a href=http://www.megginson.com/SAX/> SAX</a> interface can * be used.<p> * XmlRpcServer and XmlRpcClient are the classes that actually implement an * XML-RCP server and client. * * @see XmlRpcServer * @see XmlRpcClient * * @author <a href="mailto:[email protected]">Hannes Wallnoefer</a> */ public abstract class XmlRpc extends HandlerBase { public static final String version = "Apache XML-RPC 1.0"; String methodName; // class name of SAX parser to use private static Class parserClass; private static Hashtable saxDrivers = new Hashtable (); static { saxDrivers.put ("xerces", "org.apache.xerces.parsers.SAXParser"); saxDrivers.put ("xp", "com.jclark.xml.sax.Driver"); saxDrivers.put ("ibm1", "com.ibm.xml.parser.SAXDriver"); saxDrivers.put ("ibm2", "com.ibm.xml.parsers.SAXParser"); saxDrivers.put ("aelfred", "com.microstar.xml.SAXDriver"); saxDrivers.put ("oracle1", "oracle.xml.parser.XMLParser"); saxDrivers.put ("oracle2", "oracle.xml.parser.v2.SAXParser"); saxDrivers.put ("openxml", "org.openxml.parser.XMLSAXParser"); } // the stack we're parsing our values into. Stack values; Value currentValue; // formats for parsing and generating dateTime values // DateFormat datetime; // now comes wapped into a synchronized class because dateFormat is not threadsafe static Formatter dateformat = new Formatter (); // used to collect character data of parameter values StringBuffer cdata; boolean readCdata; // XML RPC parameter types used for dataMode static final int STRING = 0; static final int INTEGER = 1; static final int BOOLEAN = 2; static final int DOUBLE = 3; static final int DATE = 4; static final int BASE64 = 5; static final int STRUCT = 6; static final int ARRAY = 7; // Error level + message int errorLevel; String errorMsg; static final int NONE = 0; static final int RECOVERABLE = 1; static final int FATAL = 2; // use HTTP keepalive? static boolean keepalive = false; // for debugging output public static boolean debug = false; final static String types[] = {"String", "Integer", "Boolean", "Double", "Date", "Base64", "Struct", "Array"}; // mapping between java encoding names and "real" names used in XML prolog. static String encoding = "ISO8859_1"; static Properties encodings = new Properties (); static { encodings.put ("UTF8", "UTF-8"); encodings.put ("ISO8859_1", "ISO-8859-1"); } /** * Set the SAX Parser to be used. The argument can either be the * full class name or a user friendly shortcut if the parser is * known to this class. The parsers that can currently be set by * shortcut are listed in the main documentation page. If you are * using another parser please send me the name of the SAX driver * and I'll include it in a future release. If setDriver() is * never called then the System property "sax.driver" is * consulted. If that is not defined the driver defaults to * OpenXML. */ public static void setDriver (String driver) throws ClassNotFoundException { String parserClassName = null; try { parserClassName = (String) saxDrivers.get (driver); if (parserClassName == null) parserClassName = driver; parserClass = Class.forName (parserClassName); } catch (ClassNotFoundException x) { throw new ClassNotFoundException ("SAX driver not found: "+ parserClassName); } } /** * Set the SAX Parser to be used by directly passing the Class object. */ public static void setDriver (Class driver) { parserClass = driver; } /** * Set the encoding of the XML. This should be the name of a Java encoding * contained in the encodings Hashtable. */ public static void setEncoding (String enc) { encoding = enc; } /** * Return the encoding, transforming to the canonical name if possible. */ public String getEncoding () { return encodings.getProperty (encoding, encoding); } /** * Switch debugging output on/off. */ public static void setDebug (boolean val) { debug = val; } /** * Switch HTTP keepalive on/off. */ public static void setKeepAlive (boolean val) { keepalive = val; } /** * get current HTTP keepalive mode. */ public static boolean getKeepAlive () { return keepalive; } /** * Parse the input stream. For each root level object, method * <code>objectParsed</code> is called. */ synchronized void parse (InputStream is) throws Exception { // reset values (XmlRpc objects are reusable) errorLevel = NONE; errorMsg = null; values = new Stack (); if (cdata == null) cdata = new StringBuffer (128); else cdata.setLength (0); readCdata = false; currentValue = null; long now = System.currentTimeMillis (); if (parserClass == null) { // try to get the name of the SAX driver from the System properties // setDriver (System.getProperty ( // "sax.driver", "org.apache.xerces.parsers.SAXParser")); setDriver (System.getProperty ( "sax.driver", "uk.co.wilson.xml.MinML")); } Parser parser = null; try { parser = (Parser) parserClass.newInstance (); } catch (NoSuchMethodError nsm) { // This is thrown if no constructor exists for the parser class // and is transformed into a regular exception. throw new Exception ("Can't create Parser: " + parserClass); } parser.setDocumentHandler (this); parser.setErrorHandler (this); if (debug) System.err.println("Beginning parsing XML input stream"); parser.parse (new InputSource (is)); if (debug) System.err.println ("Spent "+ (System.currentTimeMillis () - now) + " millis parsing"); } /** * Writes the XML representation of a supported Java object to * the XML writer. */ void writeObject (Object what, XmlWriter writer) { writer.startElement ("value"); if (what == null) { throw new RuntimeException ("null value not supported by XML-RPC"); } else if (what instanceof String) { writer.chardata (what.toString ()); } else if (what instanceof Integer) { writer.startElement ("int"); writer.write (what.toString ()); writer.endElement ("int"); } else if (what instanceof Boolean) { writer.startElement ("boolean"); writer.write (((Boolean) what).booleanValue () ? "1" : "0"); writer.endElement ("boolean"); } else if (what instanceof Double || what instanceof Float) { writer.startElement ("double"); writer.write (what.toString ()); writer.endElement ("double"); } else if (what instanceof Date) { writer.startElement ("dateTime.iso8601"); Date d = (Date) what; writer.write (dateformat.format (d)); writer.endElement ("dateTime.iso8601"); } else if (what instanceof byte[]) { writer.startElement ("base64"); writer.write (Base64.encode ((byte[]) what)); writer.endElement ("base64"); } else if (what instanceof Vector) { writer.startElement ("array"); writer.startElement ("data"); Vector v = (Vector) what; int l2 = v.size (); for (int i2 = 0; i2 < l2; i2++) writeObject (v.elementAt (i2), writer); writer.endElement ("data"); writer.endElement ("array"); } else if (what instanceof Hashtable) { writer.startElement ("struct"); Hashtable h = (Hashtable) what; for (Enumeration e = h.keys (); e.hasMoreElements ();) { String nextkey = (String) e.nextElement (); Object nextval = h.get (nextkey); writer.startElement ("member"); writer.startElement ("name"); writer.write (nextkey); writer.endElement ("name"); writeObject (nextval, writer); writer.endElement ("member"); } writer.endElement ("struct"); } else throw new RuntimeException ("unsupported Java type: " + what.getClass ()); writer.endElement ("value"); } /** * This method is called when a root level object has been parsed. */ abstract void objectParsed (Object what); //////////////////////////////////////////////////////////////// // methods called by XML parser /** * Method called by SAX driver. */ public void characters (char ch[], int start, int length) throws SAXException { if (!readCdata) return; cdata.append (ch, start, length); } /** * Method called by SAX driver. */ public void endElement (String name) throws SAXException { if (debug) System.err.println ("endElement: "+name); // finalize character data, if appropriate if (currentValue != null && readCdata) { currentValue.characterData (cdata.toString ()); cdata.setLength (0); readCdata = false; } if ("value".equals (name)) { int depth = values.size (); // Only handle top level objects or objects contained in arrays here. // For objects contained in structs, wait for </member> (see code below). if (depth < 2 || values.elementAt (depth - 2).hashCode () != STRUCT) { Value v = currentValue; values.pop (); if (depth < 2) { // This is a top-level object objectParsed (v.value); currentValue = null; } else { // add object to sub-array; if current container is a struct, add later (at </member>) currentValue = (Value) values.peek (); currentValue.endElement (v); } } } // Handle objects contained in structs. if ("member".equals (name)) { Value v = currentValue; values.pop (); currentValue = (Value) values.peek (); currentValue.endElement (v); } else if ("methodName".equals (name)) { methodName = cdata.toString (); cdata.setLength (0); readCdata = false; } } /** * Method called by SAX driver. */ public void startElement (String name, AttributeList atts) throws SAXException { if (debug) System.err.println ("startElement: "+name); if ("value".equals (name)) { // System.err.println ("starting value"); Value v = new Value (); values.push (v); currentValue = v; // cdata object is reused cdata.setLength(0); readCdata = true; } else if ("methodName".equals (name)) { cdata.setLength(0); readCdata = true; } else if ("name".equals (name)) { cdata.setLength(0); readCdata = true; } else if ("string".equals (name)) { // currentValue.setType (STRING); cdata.setLength(0); readCdata = true; } else if ("i4".equals (name) || "int".equals (name)) { currentValue.setType (INTEGER); cdata.setLength(0); readCdata = true; } else if ("boolean".equals (name)) { currentValue.setType (BOOLEAN); cdata.setLength(0); readCdata = true; } else if ("double".equals (name)) { currentValue.setType (DOUBLE); cdata.setLength(0); readCdata = true; } else if ("dateTime.iso8601".equals (name)) { currentValue.setType (DATE); cdata.setLength(0); readCdata = true; } else if ("base64".equals (name)) { currentValue.setType (BASE64); cdata.setLength(0); readCdata = true; } else if ("struct".equals (name)) { currentValue.setType (STRUCT); } else if ("array".equals (name)) { currentValue.setType (ARRAY); } } public void error (SAXParseException e) throws SAXException { System.err.println ("Error parsing XML: "+e); errorLevel = RECOVERABLE; errorMsg = e.toString (); } public void fatalError(SAXParseException e) throws SAXException { System.err.println ("Fatal error parsing XML: "+e); errorLevel = FATAL; errorMsg = e.toString (); } /** * This represents a XML-RPC value parsed from the request. */ class Value { int type; Object value; // the name to use for the next member of struct values String nextMemberName; Hashtable struct; Vector array; /** * Constructor. */ public Value () { this.type = STRING; } /** * Notification that a new child element has been parsed. */ public void endElement (Value child) { switch (type) { case ARRAY: array.addElement (child.value); break; case STRUCT: struct.put (nextMemberName, child.value); } } /** * Set the type of this value. If it's a container, create the * corresponding java container. */ public void setType (int type) { // System.err.println ("setting type to "+types[type]); this.type = type; switch (type) { case ARRAY: value = array = new Vector (); break; case STRUCT: value = struct = new Hashtable (); break; } } /** * Set the character data for the element and interpret it * according to the element type. */ public void characterData (String cdata) { switch (type) { case INTEGER: value = new Integer (cdata.trim ()); break; case BOOLEAN: value = new Boolean ("1".equals (cdata.trim ())); break; case DOUBLE: value = new Double (cdata.trim ()); break; case DATE: try { value = dateformat.parse (cdata.trim ()); } catch (ParseException p) { // System.err.println ("Exception while parsing date: "+p); throw new RuntimeException (p.getMessage ()); } break; case BASE64: value = Base64.decode (cdata.toCharArray()); break; case STRING: value = cdata; break; case STRUCT: // this is the name to use for the next member of this struct nextMemberName = cdata; break; } } /** * This is a performance hack to get the type of a value * without casting the Object. It breaks the contract of * method hashCode, but it doesn't matter since Value objects * are never used as keys in Hashtables. */ public int hashCode () { return type; } public String toString () { return (types[type] + " element " + value); } } /** * A quick and dirty XML writer. */ class XmlWriter { StringBuffer buf; String enc; public XmlWriter (StringBuffer buf) { // The default encoding used for XML-RPC is ISO-8859-1 for pragmatical reasons. this (buf, encoding); } public XmlWriter (StringBuffer buf, String enc) { this.buf = buf; this.enc = enc; // get name of encoding for XML prolog String encName = encodings.getProperty (enc, enc); buf.append ("<?xml version=\"1.0\" encoding=\"" + encName + "\"?>"); } public void startElement (String elem) { buf.append ("<"); buf.append (elem); buf.append (">"); } public void endElement (String elem) { buf.append ("</"); buf.append (elem); buf.append (">"); } public void emptyElement (String elem) { buf.append ("<"); buf.append (elem); buf.append ("/>"); } public void chardata (String text) { int l = text.length (); for (int i = 0; i < l; i++) { char c = text.charAt (i); switch (c) { case '<' : buf.append ("&lt;"); break; case '>' : buf.append ("&gt;"); break; case '&' : buf.append ("&amp;"); break; default : buf.append (c); } } } public void write (char[] text) { buf.append (text); } public void write (String text) { buf.append (text); } public String toString () { return buf.toString (); } public byte[] getBytes () throws UnsupportedEncodingException { return buf.toString ().getBytes (enc); } } } /** * Wraps a <code>DateFormat</code> instance to provide thread safety. */ class Formatter { private DateFormat f; public Formatter () { f = new SimpleDateFormat ("yyyyMMdd'T'HH:mm:ss"); } public synchronized String format (Date d) { return f.format (d); } public synchronized Date parse (String s) throws ParseException { return f.parse (s); } }
Use the char data type for single character text. Reviewed by: Leonard Richardson <[email protected]>
src/java/org/apache/xmlrpc/XmlRpc.java
Use the char data type for single character text.
<ide><path>rc/java/org/apache/xmlrpc/XmlRpc.java <ide> <ide> public void startElement (String elem) <ide> { <del> buf.append ("<"); <add> buf.append ('<'); <ide> buf.append (elem); <del> buf.append (">"); <add> buf.append ('>'); <ide> } <ide> <ide> public void endElement (String elem) <ide> { <ide> buf.append ("</"); <ide> buf.append (elem); <del> buf.append (">"); <add> buf.append ('>'); <ide> } <ide> <ide> public void emptyElement (String elem) <ide> { <del> buf.append ("<"); <add> buf.append ('<'); <ide> buf.append (elem); <ide> buf.append ("/>"); <ide> } <ide> { <ide> return buf.toString ().getBytes (enc); <ide> } <del> <del> } <del> <add> } <ide> } <ide> <ide>
Java
apache-2.0
035f9fc4cea0a2ef3fb1d3dda67129985308661a
0
hasinitg/airavata,glahiru/airavata,jjj117/airavata,glahiru/airavata,jjj117/airavata,anujbhan/airavata,apache/airavata,apache/airavata,machristie/airavata,apache/airavata,gouravshenoy/airavata,dogless/airavata,anujbhan/airavata,dogless/airavata,anujbhan/airavata,machristie/airavata,dogless/airavata,anujbhan/airavata,dogless/airavata,apache/airavata,machristie/airavata,gouravshenoy/airavata,machristie/airavata,machristie/airavata,anujbhan/airavata,gouravshenoy/airavata,anujbhan/airavata,gouravshenoy/airavata,jjj117/airavata,machristie/airavata,apache/airavata,hasinitg/airavata,glahiru/airavata,hasinitg/airavata,apache/airavata,dogless/airavata,anujbhan/airavata,apache/airavata,jjj117/airavata,jjj117/airavata,glahiru/airavata,gouravshenoy/airavata,hasinitg/airavata,gouravshenoy/airavata,machristie/airavata,hasinitg/airavata,glahiru/airavata,dogless/airavata,hasinitg/airavata,gouravshenoy/airavata,jjj117/airavata,apache/airavata
/* * * 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.airavata.services.gfac.axis2; import java.lang.reflect.Constructor; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.jcr.Credentials; import javax.jcr.Repository; import javax.jcr.RepositoryFactory; import javax.jcr.SimpleCredentials; import org.apache.airavata.registry.api.Registry; import org.apache.airavata.registry.api.impl.JCRRegistry; import org.apache.airavata.services.gfac.axis2.dispatchers.GFacURIBasedDispatcher; import org.apache.airavata.services.gfac.axis2.handlers.AmazonSecurityHandler; import org.apache.airavata.services.gfac.axis2.handlers.MyProxySecurityHandler; import org.apache.airavata.services.gfac.axis2.util.WSConstants; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.TransportInDescription; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.engine.Phase; import org.apache.axis2.engine.ServiceLifeCycle; import org.apache.axis2.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GFacService implements ServiceLifeCycle { private static final Logger log = LoggerFactory.getLogger(GFacService.class); public static final String CONFIGURATION_CONTEXT_REGISTRY = "registry"; public static final String GFAC_URL = "GFacURL"; public static final String SECURITY_CONTEXT = "security_context"; public static final String REPOSITORY_PROPERTIES = "repository.properties"; public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3; /* * Properties for JCR */ public static final String JCR_CLASS = "jcr.class"; public static final String JCR_USER = "jcr.user"; public static final String JCR_PASS = "jcr.pass"; /* * Heart beat thread */ private Thread thread; public void startUp(ConfigurationContext configctx, AxisService service) { AxisConfiguration config = null; List<Phase> phases = null; config = service.getAxisConfiguration(); phases = config.getInFlowPhases(); /* * Add dispatcher and security handler to inFlowPhases */ for (Iterator<Phase> iterator = phases.iterator(); iterator.hasNext();) { Phase phase = (Phase) iterator.next(); if ("Security".equals(phase.getPhaseName())) { phase.addHandler(new MyProxySecurityHandler()); phase.addHandler(new AmazonSecurityHandler()); } else if ("Dispatch".equals(phase.getPhaseName())) { phase.addHandler(new GFacURIBasedDispatcher(), 0); } } initializeRepository(configctx); } private void initializeRepository(ConfigurationContext context) { Properties properties = new Properties(); String port = null; try { URL url = this.getClass().getClassLoader().getResource(REPOSITORY_PROPERTIES); properties.load(url.openStream()); Map<String, String> map = new HashMap<String, String>((Map) properties); Class registryRepositoryFactory = Class.forName(map.get(JCR_CLASS)); Constructor c = registryRepositoryFactory.getConstructor(); RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance(); Repository repository = repositoryFactory.getRepository(map); Credentials credentials = new SimpleCredentials(map.get(JCR_USER), map.get(JCR_PASS).toCharArray()); Registry registry = new JCRRegistry(repository, credentials); String localAddress = Utils.getIpAddress(context.getAxisConfiguration()); TransportInDescription transportInDescription = context.getAxisConfiguration().getTransportsIn() .get("http"); if (transportInDescription != null && transportInDescription.getParameter("port") != null) { port = (String) transportInDescription.getParameter("port").getValue(); } else { port = map.get("port"); } localAddress = "http://" + localAddress + ":" + port; localAddress = localAddress + "/" + context.getContextRoot() + "/" + context.getServicePath() + "/" + WSConstants.GFAC_SERVICE_NAME; log.debug("GFAC_ADDRESS:" + localAddress); context.setProperty(CONFIGURATION_CONTEXT_REGISTRY, registry); context.setProperty(GFAC_URL, localAddress); /* * Heart beat message to registry */ thread = new GFacThread(context); thread.start(); } catch (Exception e) { log.error(e.getMessage(), e); } } public void shutDown(ConfigurationContext configctx, AxisService service) { Registry registry = (JCRRegistry) configctx.getProperty(CONFIGURATION_CONTEXT_REGISTRY); String gfacURL = (String) configctx.getProperty(GFAC_URL); registry.deleteGFacDescriptor(gfacURL); thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { log.info("GFacURL update thread is interrupted"); } } class GFacThread extends Thread { private ConfigurationContext context = null; GFacThread(ConfigurationContext context) { this.context = context; } public void run() { try { while (true) { Registry registry = (Registry) this.context.getProperty(CONFIGURATION_CONTEXT_REGISTRY); String localAddress = (String) this.context.getProperty(GFAC_URL); registry.saveGFacDescriptor(localAddress); log.info("Updated the GFac URL in to Repository"); Thread.sleep(GFAC_URL_UPDATE_INTERVAL); } } catch (InterruptedException e) { log.info("GFacURL update thread is interrupted"); } } } }
modules/gfac-axis2/src/main/java/org/apache/airavata/services/gfac/axis2/GFacService.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.airavata.services.gfac.axis2; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.URL; import java.util.*; import javax.jcr.Credentials; import javax.jcr.Repository; import javax.jcr.RepositoryFactory; import javax.jcr.SimpleCredentials; import javax.security.auth.login.Configuration; import javax.servlet.ServletContext; import org.apache.airavata.core.gfac.services.GenericService; import org.apache.airavata.registry.api.Registry; import org.apache.airavata.registry.api.impl.JCRRegistry; import org.apache.airavata.services.gfac.axis2.handlers.AmazonSecurityHandler; import org.apache.airavata.services.gfac.axis2.handlers.MyProxySecurityHandler; import org.apache.airavata.services.gfac.axis2.util.WSConstants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.deployment.WarBasedAxisConfigurator; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.TransportInDescription; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.engine.AxisConfigurator; import org.apache.axis2.engine.Phase; import org.apache.axis2.engine.ServiceLifeCycle; import org.apache.axis2.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GFacService implements ServiceLifeCycle { private static final Logger log = LoggerFactory.getLogger(GFacService.class); public static final String CONFIGURATION_CONTEXT_REGISTRY = "registry"; public static final String SECURITY_CONTEXT = "security_context"; public static final String REPOSITORY_PROPERTIES = "repository.properties"; /* * Properties for JCR */ public static final String JCR_CLASS = "jcr.class"; public static final String JCR_USER = "jcr.user"; public static final String JCR_PASS = "jcr.pass"; public static GenericService service; public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3; public ConfigurationContext context; public GFacThread thread; public static final String GFAC_URL = "GFacURL"; public void startUp(ConfigurationContext configctx, AxisService service){ this.context = configctx; AxisConfiguration config = null; configctx.getAxisConfiguration().getTransportsIn().get("http").getParameter("port"); List<Phase> phases = null; config = service.getAxisConfiguration(); phases = config.getInFlowPhases(); initializeRepository(configctx); for (Iterator<Phase> iterator = phases.iterator(); iterator.hasNext();) { Phase phase = (Phase) iterator.next(); if ("Security".equals(phase.getPhaseName())) { phase.addHandler(new MyProxySecurityHandler()); phase.addHandler(new AmazonSecurityHandler()); return; } } } private void initializeRepository(ConfigurationContext context) { Properties properties = new Properties(); String port = null; try { URL url = this.getClass().getClassLoader().getResource(REPOSITORY_PROPERTIES); properties.load(url.openStream()); Map<String, String> map = new HashMap<String, String>((Map) properties); Class registryRepositoryFactory = Class.forName(map.get(JCR_CLASS)); Constructor c = registryRepositoryFactory.getConstructor(); RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance(); Repository repository = repositoryFactory.getRepository(map); Credentials credentials = new SimpleCredentials(map.get(JCR_USER), map.get(JCR_PASS).toCharArray()); Registry registry = new JCRRegistry(repository, credentials); String localAddress = Utils.getIpAddress(context.getAxisConfiguration()); TransportInDescription transportInDescription = context.getAxisConfiguration().getTransportsIn().get("http"); if(transportInDescription != null && transportInDescription.getParameter("port") != null){ port = (String)transportInDescription.getParameter("port").getValue(); }else{ port = map.get("port"); } localAddress = "http://" + localAddress + ":" + port; localAddress = localAddress + "/" + context.getContextRoot() + "/" + context.getServicePath() + "/" + WSConstants.GFAC_SERVICE_NAME; System.out.println(localAddress); context.setProperty(CONFIGURATION_CONTEXT_REGISTRY, registry); context.setProperty(GFAC_URL, localAddress); thread = new GFacThread(context); thread.start(); } catch (Exception e) { log.error(e.getMessage(), e); } } public void shutDown(ConfigurationContext configctx, AxisService service) { Registry registry = (JCRRegistry) configctx.getProperty(CONFIGURATION_CONTEXT_REGISTRY); String gfacURL = (String) configctx.getProperty(GFAC_URL); registry.deleteGFacDescriptor(gfacURL); thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { log.info("GFacURL update thread is interrupted"); } } // // private String getTomcatPort(ConfigurationContext context) { // String port = null; // Object obj = context.getProperty("transport.http.servletContext"); // try { // Field field = context.getProperty("transport.http.servletContext").getClass().getDeclaredField("context"); // field.setAccessible(true); // obj = field.get(obj); // field = obj.getClass().getDeclaredField("context"); // field.setAccessible(true); // obj = field.get(obj); // field = obj.getClass().getSuperclass().getDeclaredField("listeners"); // field.setAccessible(true); // ArrayList list = (ArrayList) field.get(obj); // for(int i=0;i<list.size();i++){ // obj = list.get(i); // field = obj.getClass().getDeclaredField("connector"); // field.setAccessible(true); // obj = field.get(obj); // field = obj.getClass().getDeclaredField("scheme"); // field.setAccessible(true); // String scheme = (String)field.get(obj); // if("http".equals(scheme)){ // field = obj.getClass().getDeclaredField("port"); // field.setAccessible(true); // port = Integer.toString(field.getInt(obj)); // break; // } // } // } catch (NoSuchFieldException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } catch (IllegalAccessException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } // return port; // } // // private Object getNextObject(Object obj,String fieldName){ // try { // Field field = obj.getClass().getDeclaredField(fieldName); // fi // } catch (NoSuchFieldException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } // } class GFacThread extends Thread{ private ConfigurationContext context = null; GFacThread(ConfigurationContext context){ this.context = context; } public void run() { try { while (true) { Registry registry = (Registry) this.context.getProperty(CONFIGURATION_CONTEXT_REGISTRY); String localAddress = (String) this.context.getProperty(GFAC_URL); registry.saveGFacDescriptor(localAddress); log.info("Updated the GFac URL in to Repository"); Thread.sleep(GFAC_URL_UPDATE_INTERVAL); } } catch (InterruptedException e) { log.info("GFacURL update thread is interrupted"); } } } }
Enable Dynamic Phase adding in GFac instead of using axis2.xml git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1182073 13f79535-47bb-0310-9956-ffa450edef68
modules/gfac-axis2/src/main/java/org/apache/airavata/services/gfac/axis2/GFacService.java
Enable Dynamic Phase adding in GFac instead of using axis2.xml
<ide><path>odules/gfac-axis2/src/main/java/org/apache/airavata/services/gfac/axis2/GFacService.java <ide> package org.apache.airavata.services.gfac.axis2; <ide> <ide> import java.lang.reflect.Constructor; <del>import java.lang.reflect.Field; <ide> import java.net.URL; <del>import java.util.*; <add>import java.util.HashMap; <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.Properties; <ide> <ide> import javax.jcr.Credentials; <ide> import javax.jcr.Repository; <ide> import javax.jcr.RepositoryFactory; <ide> import javax.jcr.SimpleCredentials; <del>import javax.security.auth.login.Configuration; <del>import javax.servlet.ServletContext; <ide> <del>import org.apache.airavata.core.gfac.services.GenericService; <ide> import org.apache.airavata.registry.api.Registry; <ide> import org.apache.airavata.registry.api.impl.JCRRegistry; <add>import org.apache.airavata.services.gfac.axis2.dispatchers.GFacURIBasedDispatcher; <ide> import org.apache.airavata.services.gfac.axis2.handlers.AmazonSecurityHandler; <ide> import org.apache.airavata.services.gfac.axis2.handlers.MyProxySecurityHandler; <ide> import org.apache.airavata.services.gfac.axis2.util.WSConstants; <del>import org.apache.axis2.addressing.EndpointReference; <ide> import org.apache.axis2.context.ConfigurationContext; <del>import org.apache.axis2.deployment.WarBasedAxisConfigurator; <ide> import org.apache.axis2.description.AxisService; <ide> import org.apache.axis2.description.TransportInDescription; <ide> import org.apache.axis2.engine.AxisConfiguration; <del>import org.apache.axis2.engine.AxisConfigurator; <ide> import org.apache.axis2.engine.Phase; <ide> import org.apache.axis2.engine.ServiceLifeCycle; <ide> import org.apache.axis2.util.Utils; <ide> import org.slf4j.LoggerFactory; <ide> <ide> public class GFacService implements ServiceLifeCycle { <del> <add> <ide> private static final Logger log = LoggerFactory.getLogger(GFacService.class); <ide> <ide> public static final String CONFIGURATION_CONTEXT_REGISTRY = "registry"; <add> public static final String GFAC_URL = "GFacURL"; <ide> <ide> public static final String SECURITY_CONTEXT = "security_context"; <add> <ide> public static final String REPOSITORY_PROPERTIES = "repository.properties"; <add> <add> public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3; <ide> <ide> /* <ide> * Properties for JCR <ide> public static final String JCR_CLASS = "jcr.class"; <ide> public static final String JCR_USER = "jcr.user"; <ide> public static final String JCR_PASS = "jcr.pass"; <add> <add> /* <add> * Heart beat thread <add> */ <add> private Thread thread; <ide> <del> public static GenericService service; <del> public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3; <del> public ConfigurationContext context; <del> public GFacThread thread; <del> public static final String GFAC_URL = "GFacURL"; <del> <del> public void startUp(ConfigurationContext configctx, AxisService service){ <del> this.context = configctx; <add> public void startUp(ConfigurationContext configctx, AxisService service) { <ide> AxisConfiguration config = null; <del> configctx.getAxisConfiguration().getTransportsIn().get("http").getParameter("port"); <ide> List<Phase> phases = null; <ide> config = service.getAxisConfiguration(); <ide> phases = config.getInFlowPhases(); <ide> <del> initializeRepository(configctx); <del> <add> /* <add> * Add dispatcher and security handler to inFlowPhases <add> */ <ide> for (Iterator<Phase> iterator = phases.iterator(); iterator.hasNext();) { <ide> Phase phase = (Phase) iterator.next(); <ide> if ("Security".equals(phase.getPhaseName())) { <ide> phase.addHandler(new MyProxySecurityHandler()); <ide> phase.addHandler(new AmazonSecurityHandler()); <del> return; <add> } else if ("Dispatch".equals(phase.getPhaseName())) { <add> phase.addHandler(new GFacURIBasedDispatcher(), 0); <ide> } <ide> } <add> <add> initializeRepository(configctx); <ide> } <ide> <ide> private void initializeRepository(ConfigurationContext context) { <ide> <ide> Registry registry = new JCRRegistry(repository, credentials); <ide> String localAddress = Utils.getIpAddress(context.getAxisConfiguration()); <del> TransportInDescription transportInDescription = context.getAxisConfiguration().getTransportsIn().get("http"); <del> if(transportInDescription != null && transportInDescription.getParameter("port") != null){ <del> port = (String)transportInDescription.getParameter("port").getValue(); <del> }else{ <add> TransportInDescription transportInDescription = context.getAxisConfiguration().getTransportsIn() <add> .get("http"); <add> if (transportInDescription != null && transportInDescription.getParameter("port") != null) { <add> port = (String) transportInDescription.getParameter("port").getValue(); <add> } else { <ide> port = map.get("port"); <ide> } <ide> localAddress = "http://" + localAddress + ":" + port; <del> localAddress = localAddress + "/" + <del> context.getContextRoot() + "/" + context.getServicePath() + "/" + WSConstants.GFAC_SERVICE_NAME; <del> System.out.println(localAddress); <add> localAddress = localAddress + "/" + context.getContextRoot() + "/" + context.getServicePath() + "/" <add> + WSConstants.GFAC_SERVICE_NAME; <add> log.debug("GFAC_ADDRESS:" + localAddress); <ide> context.setProperty(CONFIGURATION_CONTEXT_REGISTRY, registry); <ide> context.setProperty(GFAC_URL, localAddress); <add> <add> /* <add> * Heart beat message to registry <add> */ <ide> thread = new GFacThread(context); <ide> thread.start(); <ide> } catch (Exception e) { <ide> Registry registry = (JCRRegistry) configctx.getProperty(CONFIGURATION_CONTEXT_REGISTRY); <ide> String gfacURL = (String) configctx.getProperty(GFAC_URL); <ide> registry.deleteGFacDescriptor(gfacURL); <del> thread.interrupt(); <add> thread.interrupt(); <ide> try { <ide> thread.join(); <ide> } catch (InterruptedException e) { <ide> } <ide> } <ide> <del> <del>// <del>// private String getTomcatPort(ConfigurationContext context) { <del>// String port = null; <del>// Object obj = context.getProperty("transport.http.servletContext"); <del>// try { <del>// Field field = context.getProperty("transport.http.servletContext").getClass().getDeclaredField("context"); <del>// field.setAccessible(true); <del>// obj = field.get(obj); <del>// field = obj.getClass().getDeclaredField("context"); <del>// field.setAccessible(true); <del>// obj = field.get(obj); <del>// field = obj.getClass().getSuperclass().getDeclaredField("listeners"); <del>// field.setAccessible(true); <del>// ArrayList list = (ArrayList) field.get(obj); <del>// for(int i=0;i<list.size();i++){ <del>// obj = list.get(i); <del>// field = obj.getClass().getDeclaredField("connector"); <del>// field.setAccessible(true); <del>// obj = field.get(obj); <del>// field = obj.getClass().getDeclaredField("scheme"); <del>// field.setAccessible(true); <del>// String scheme = (String)field.get(obj); <del>// if("http".equals(scheme)){ <del>// field = obj.getClass().getDeclaredField("port"); <del>// field.setAccessible(true); <del>// port = Integer.toString(field.getInt(obj)); <del>// break; <del>// } <del>// } <del>// } catch (NoSuchFieldException e) { <del>// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. <del>// } catch (IllegalAccessException e) { <del>// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. <del>// } <del>// return port; <del>// } <del>// <del>// private Object getNextObject(Object obj,String fieldName){ <del>// try { <del>// Field field = obj.getClass().getDeclaredField(fieldName); <del>// fi <del>// } catch (NoSuchFieldException e) { <del>// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. <del>// } <del>// } <del> class GFacThread extends Thread{ <add> class GFacThread extends Thread { <ide> private ConfigurationContext context = null; <ide> <del> GFacThread(ConfigurationContext context){ <add> GFacThread(ConfigurationContext context) { <ide> this.context = context; <ide> } <add> <ide> public void run() { <del> try { <del> while (true) { <del> Registry registry = (Registry) this.context.getProperty(CONFIGURATION_CONTEXT_REGISTRY); <del> String localAddress = (String) this.context.getProperty(GFAC_URL); <del> registry.saveGFacDescriptor(localAddress); <del> log.info("Updated the GFac URL in to Repository"); <del> Thread.sleep(GFAC_URL_UPDATE_INTERVAL); <add> try { <add> while (true) { <add> Registry registry = (Registry) this.context.getProperty(CONFIGURATION_CONTEXT_REGISTRY); <add> String localAddress = (String) this.context.getProperty(GFAC_URL); <add> registry.saveGFacDescriptor(localAddress); <add> log.info("Updated the GFac URL in to Repository"); <add> Thread.sleep(GFAC_URL_UPDATE_INTERVAL); <add> } <add> } catch (InterruptedException e) { <add> log.info("GFacURL update thread is interrupted"); <ide> } <del> } catch (InterruptedException e) { <del> log.info("GFacURL update thread is interrupted"); <ide> } <ide> } <del> } <ide> }
Java
bsd-3-clause
3f259e40a6490582a500eab7a4d9dac9494bc31c
0
NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers
package gov.nih.nci.cabig.caaers.web.rule.notification; import gov.nih.nci.cabig.caaers.domain.ReportFormatType; import gov.nih.nci.cabig.caaers.domain.ConfigProperty; import gov.nih.nci.cabig.caaers.domain.ConfigPropertyType; import gov.nih.nci.cabig.caaers.domain.report.TimeScaleUnit; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.web.fields.DefaultInputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap; import gov.nih.nci.cabig.caaers.web.fields.TabWithFields; import gov.nih.nci.cabig.caaers.web.utils.WebUtils; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Errors; public class BasicsTab extends TabWithFields<ReportDefinitionCommand> { private InputFieldGroupMap map; public BasicsTab(String longTitle, String shortTitle, String viewName) { super(longTitle, shortTitle, viewName); } public BasicsTab() { this("Report Definition", "Details", "rule/notification/basicsTab"); } @Override public Map<String, Object> referenceData(HttpServletRequest request,ReportDefinitionCommand command) { // TODO Auto-generated method stub return super.referenceData(request, command); } @Override public Map<String, InputFieldGroup> createFieldGroups(ReportDefinitionCommand command) { map = new InputFieldGroupMap(); InputFieldGroup orgFieldGroup = new DefaultInputFieldGroup("reportDefinitionOrganization"); InputField orgField = InputFieldFactory.createAutocompleterField("reportDefinition.organization", "Organization", true); //InputFieldAttributes.setDetails(orgField,"Enter a portion of the organization name that you are looking for."); orgFieldGroup.getFields().add(orgField); map.addInputFieldGroup(orgFieldGroup); // setup the fileds InputFieldGroup fieldGroup = new DefaultInputFieldGroup("reportDefinitionFieldGroup"); List<InputField> fields = fieldGroup.getFields(); InputField nameField = InputFieldFactory.createTextField("reportDefinition.name", "Name", true); InputFieldAttributes.setSize(nameField, 50); fields.add(nameField); InputField labelField = InputFieldFactory.createTextField("reportDefinition.label", "Display Name", true); InputFieldAttributes.setSize(labelField, 50); fields.add(labelField); InputField descField = InputFieldFactory.createTextArea("reportDefinition.description", "Description", false); InputFieldAttributes.setColumns(descField, 50); fields.add(descField); if (command.getReportDefinition() == null || command.getReportDefinition().getReportFormatType() == ReportFormatType.CUSTOM_REPORT) { InputField headerField = InputFieldFactory.createTextArea("reportDefinition.header", "Header", false); InputFieldAttributes.setColumns(headerField, 50); fields.add(headerField); InputField footerField = InputFieldFactory.createTextArea("reportDefinition.footer", "Footer", false); InputFieldAttributes.setColumns(footerField, 50); fields.add(footerField); } InputField amendableField = InputFieldFactory.createBooleanSelectField("reportDefinition.amendable", "Amendable?", true); fields.add(amendableField); InputField reportGroupField = InputFieldFactory.createSelectField("reportDefinition.group", "Report Group", true, command.getGroupOptions()); fields.add(reportGroupField); InputField reportTypeField = InputFieldFactory.createSelectField("reportDefinition.reportType", "Report Type", true, command.collectReportTypeOptions()); fields.add(reportTypeField); Map<Object, Object> reportFormatTypesOptions = new LinkedHashMap<Object, Object>(); reportFormatTypesOptions.put("", "Please select"); reportFormatTypesOptions.putAll(WebUtils.collectOptions(Arrays.asList(ReportFormatType.values()), "name", "displayName")); InputField reportFormatField = InputFieldFactory.createSelectField("reportDefinition.reportFormatType", "Report Format", true, reportFormatTypesOptions); fields.add(reportFormatField); InputField attributionRequiredField = InputFieldFactory.createBooleanSelectField("reportDefinition.attributionRequired", "Attribution required?", true); fields.add(attributionRequiredField); fields.add(InputFieldFactory.createSelectField("reportDefinition.timeScaleUnitType","Time Scale UOM", true, createMapFromArray(TimeScaleUnit.values()))); InputField timeTillReportDueField = InputFieldFactory.createTextField("reportDefinition.duration", "Time until report due", true); InputFieldAttributes.setSize(timeTillReportDueField, 2); fields.add(timeTillReportDueField); fields.add(InputFieldFactory.createBooleanSelectField("reportDefinition.physicianSignOff", "Physician signoff required?", true)); Map<Object, Object> parentOptions = new LinkedHashMap<Object, Object>(); parentOptions.put("", "Please select"); InputField parentReportDefinition = InputFieldFactory.createSelectField("reportDefinition.parent", "Parent", false, command.getParentOptions()); fields.add(parentReportDefinition); fields.add(InputFieldFactory.createBooleanSelectField("reportDefinition.workflowEnabled", "Workflow enabled?", true)); map.addInputFieldGroup(fieldGroup); return map; } protected Map<Object, Object> createMapFromArray(Object[] arr) { Map<Object, Object> map = new LinkedHashMap<Object, Object>(); map.put("", "Select a Value"); for (Object o : arr) map.put(o, o); return map; } /* * (non-Javadoc) * * @see gov.nih.nci.cabig.caaers.web.fields.TabWithFields#validate(java.lang.Object, * org.springframework.beans.BeanWrapper, java.util.Map, * org.springframework.validation.Errors) */ @Override protected void validate(ReportDefinitionCommand command, BeanWrapper commandBean, Map<String, InputFieldGroup> fieldGroups, Errors errors) { super.validate(command, commandBean, fieldGroups, errors); if (command.getReportDefinition().getDuration() == null) { errors.rejectValue("reportDefinition.duration", "RPD_002", "Invalid Time Till Report Due"); } //check for duplicate report definitions. if(command.isSimilarReportDefinitionExist(command.getReportDefinition())){ errors.rejectValue("reportDefinition.name","RPD_001","Duplicate Report Definition!."); } } }
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/rule/notification/BasicsTab.java
package gov.nih.nci.cabig.caaers.web.rule.notification; import gov.nih.nci.cabig.caaers.domain.ReportFormatType; import gov.nih.nci.cabig.caaers.domain.ConfigProperty; import gov.nih.nci.cabig.caaers.domain.ConfigPropertyType; import gov.nih.nci.cabig.caaers.domain.report.TimeScaleUnit; import gov.nih.nci.cabig.caaers.domain.report.ReportDefinition; import gov.nih.nci.cabig.caaers.web.fields.DefaultInputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap; import gov.nih.nci.cabig.caaers.web.fields.TabWithFields; import gov.nih.nci.cabig.caaers.web.utils.WebUtils; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Errors; public class BasicsTab extends TabWithFields<ReportDefinitionCommand> { private InputFieldGroupMap map; public BasicsTab(String longTitle, String shortTitle, String viewName) { super(longTitle, shortTitle, viewName); } public BasicsTab() { this("Report Definition", "Details", "rule/notification/basicsTab"); } @Override public Map<String, Object> referenceData(HttpServletRequest request,ReportDefinitionCommand command) { // TODO Auto-generated method stub return super.referenceData(request, command); } @Override public Map<String, InputFieldGroup> createFieldGroups(ReportDefinitionCommand command) { map = new InputFieldGroupMap(); InputFieldGroup orgFieldGroup = new DefaultInputFieldGroup("reportDefinitionOrganization"); InputField orgField = InputFieldFactory.createAutocompleterField("reportDefinition.organization", "Organization", true); //InputFieldAttributes.setDetails(orgField,"Enter a portion of the organization name that you are looking for."); orgFieldGroup.getFields().add(orgField); map.addInputFieldGroup(orgFieldGroup); // setup the fileds InputFieldGroup fieldGroup = new DefaultInputFieldGroup("reportDefinitionFieldGroup"); List<InputField> fields = fieldGroup.getFields(); InputField nameField = InputFieldFactory.createTextField("reportDefinition.name", "Name", true); InputFieldAttributes.setSize(nameField, 50); fields.add(nameField); InputField labelField = InputFieldFactory.createTextField("reportDefinition.label", "Display Name", true); InputFieldAttributes.setSize(labelField, 50); fields.add(labelField); InputField descField = InputFieldFactory.createTextArea("reportDefinition.description", "Description", false); InputFieldAttributes.setColumns(descField, 50); fields.add(descField); InputField headerField = InputFieldFactory.createTextArea("reportDefinition.header", "Header", false); InputFieldAttributes.setColumns(headerField, 50); fields.add(headerField); InputField footerField = InputFieldFactory.createTextArea("reportDefinition.footer", "Footer", false); InputFieldAttributes.setColumns(footerField, 50); fields.add(footerField); InputField amendableField = InputFieldFactory.createBooleanSelectField("reportDefinition.amendable", "Amendable?", true); fields.add(amendableField); InputField reportGroupField = InputFieldFactory.createSelectField("reportDefinition.group", "Report Group", true, command.getGroupOptions()); fields.add(reportGroupField); InputField reportTypeField = InputFieldFactory.createSelectField("reportDefinition.reportType", "Report Type", true, command.collectReportTypeOptions()); fields.add(reportTypeField); Map<Object, Object> reportFormatTypesOptions = new LinkedHashMap<Object, Object>(); reportFormatTypesOptions.put("", "Please select"); reportFormatTypesOptions.putAll(WebUtils.collectOptions(Arrays.asList(ReportFormatType.values()), "name", "displayName")); InputField reportFormatField = InputFieldFactory.createSelectField("reportDefinition.reportFormatType", "Report Format", true, reportFormatTypesOptions); fields.add(reportFormatField); InputField attributionRequiredField = InputFieldFactory.createBooleanSelectField("reportDefinition.attributionRequired", "Attribution required?", true); fields.add(attributionRequiredField); fields.add(InputFieldFactory.createSelectField("reportDefinition.timeScaleUnitType","Time Scale UOM", true, createMapFromArray(TimeScaleUnit.values()))); InputField timeTillReportDueField = InputFieldFactory.createTextField("reportDefinition.duration", "Time until report due", true); InputFieldAttributes.setSize(timeTillReportDueField, 2); fields.add(timeTillReportDueField); fields.add(InputFieldFactory.createBooleanSelectField("reportDefinition.physicianSignOff", "Physician signoff required?", true)); Map<Object, Object> parentOptions = new LinkedHashMap<Object, Object>(); parentOptions.put("", "Please select"); InputField parentReportDefinition = InputFieldFactory.createSelectField("reportDefinition.parent", "Parent", false, command.getParentOptions()); fields.add(parentReportDefinition); fields.add(InputFieldFactory.createBooleanSelectField("reportDefinition.workflowEnabled", "Workflow enabled?", true)); map.addInputFieldGroup(fieldGroup); return map; } protected Map<Object, Object> createMapFromArray(Object[] arr) { Map<Object, Object> map = new LinkedHashMap<Object, Object>(); map.put("", "Select a Value"); for (Object o : arr) map.put(o, o); return map; } /* * (non-Javadoc) * * @see gov.nih.nci.cabig.caaers.web.fields.TabWithFields#validate(java.lang.Object, * org.springframework.beans.BeanWrapper, java.util.Map, * org.springframework.validation.Errors) */ @Override protected void validate(ReportDefinitionCommand command, BeanWrapper commandBean, Map<String, InputFieldGroup> fieldGroups, Errors errors) { super.validate(command, commandBean, fieldGroups, errors); if (command.getReportDefinition().getDuration() == null) { errors.rejectValue("reportDefinition.duration", "RPD_002", "Invalid Time Till Report Due"); } //check for duplicate report definitions. if(command.isSimilarReportDefinitionExist(command.getReportDefinition())){ errors.rejectValue("reportDefinition.name","RPD_001","Duplicate Report Definition!."); } } }
CAAERS-3676 - Make Report Definition Header and Footer fields only show if Custom PDF is select SVN-Revision: 12067
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/rule/notification/BasicsTab.java
CAAERS-3676 - Make Report Definition Header and Footer fields only show if Custom PDF is select
<ide><path>aAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/rule/notification/BasicsTab.java <ide> InputFieldAttributes.setColumns(descField, 50); <ide> fields.add(descField); <ide> <del> InputField headerField = InputFieldFactory.createTextArea("reportDefinition.header", "Header", false); <del> InputFieldAttributes.setColumns(headerField, 50); <del> fields.add(headerField); <add> if (command.getReportDefinition() == null || command.getReportDefinition().getReportFormatType() == ReportFormatType.CUSTOM_REPORT) { <add> InputField headerField = InputFieldFactory.createTextArea("reportDefinition.header", "Header", false); <add> InputFieldAttributes.setColumns(headerField, 50); <add> fields.add(headerField); <ide> <del> InputField footerField = InputFieldFactory.createTextArea("reportDefinition.footer", "Footer", false); <del> InputFieldAttributes.setColumns(footerField, 50); <del> fields.add(footerField); <del> <add> InputField footerField = InputFieldFactory.createTextArea("reportDefinition.footer", "Footer", false); <add> InputFieldAttributes.setColumns(footerField, 50); <add> fields.add(footerField); <add> } <add> <ide> InputField amendableField = InputFieldFactory.createBooleanSelectField("reportDefinition.amendable", "Amendable?", true); <ide> fields.add(amendableField); <ide>
Java
apache-2.0
0b92255ec5d3f4e57dab601b1cae3224e9e8a252
0
MatthewTamlin/Avatar
package com.matthewtamlin.java_compiler_utilities.element_supplier; import com.matthewtamlin.java_compiler_utilities.collectors.ElementCollector; import com.matthewtamlin.java_compiler_utilities.collectors.IdBasedElementCollector; import javax.lang.model.element.Element; import javax.tools.JavaFileObject; import java.util.Set; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; /** * Gets specific elements from a {@link JavaFileObject} via {@link ElementId} annotations in the source code. */ public class IdBasedElementSupplier { /** * The source to get elements from. */ private JavaFileObject source; /** * Constructs a new IdBasedElementSupplier. * * @param source * the JavaFileObject to get elements from, not null * * @throws IllegalArgumentException * if {@code source} is null */ public IdBasedElementSupplier(final JavaFileObject source) { this.source = checkNotNull(source, "Argument \'source\' cannot be null."); } /** * * @param id * @return * @throws CompilerMissingException */ public Set<Element> getElementsWithId(final String id) throws CompilerMissingException { checkNotNull(id, "Argument \'id\' cannot be null."); final ElementCollector<Set<Element>> collector = new IdBasedElementCollector(id); CompilerUtil.compileUsingCollector(source, collector); return collector.getCollectedElements(); } /** * * @param id * @return * @throws CompilerMissingException */ public Element getUniqueElementWithId(final String id) throws CompilerMissingException { checkNotNull(id, "Argument \'id\' cannot be null."); final Set<Element> elements = getElementsWithId(id); if (elements.isEmpty()) { throw new UniqueElementNotFoundException("No elements found for ID: " + id); } if (elements.size() > 1) { throw new UniqueElementNotFoundException("Multiple elements found for ID: " + id); } return elements.iterator().next(); } }
library/src/main/java/com/matthewtamlin/java_compiler_utilities/element_supplier/IdBasedElementSupplier.java
package com.matthewtamlin.java_compiler_utilities.element_supplier; import com.matthewtamlin.java_compiler_utilities.collectors.ElementCollector; import com.matthewtamlin.java_compiler_utilities.collectors.IdBasedElementCollector; import javax.lang.model.element.Element; import javax.tools.JavaFileObject; import java.util.Set; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; public class IdBasedElementSupplier { private JavaFileObject source; public IdBasedElementSupplier(final JavaFileObject source) { this.source = checkNotNull(source, "Argument \'source\' cannot be null."); } public Set<Element> getElementsWithId(final String id) throws CompilerMissingException { checkNotNull(id, "Argument \'id\' cannot be null."); final ElementCollector<Set<Element>> collector = new IdBasedElementCollector(id); CompilerUtil.compileUsingCollector(source, collector); return collector.getCollectedElements(); } public Element getUniqueElementWithId(final String id) throws CompilerMissingException { checkNotNull(id, "Argument \'id\' cannot be null."); final Set<Element> elements = getElementsWithId(id); if (elements.isEmpty()) { throw new UniqueElementNotFoundException("No elements found for ID: " + id); } if (elements.size() > 1) { throw new UniqueElementNotFoundException("Multiple elements found for ID: " + id); } return elements.iterator().next(); } }
Changed Javadoc
library/src/main/java/com/matthewtamlin/java_compiler_utilities/element_supplier/IdBasedElementSupplier.java
Changed Javadoc
<ide><path>ibrary/src/main/java/com/matthewtamlin/java_compiler_utilities/element_supplier/IdBasedElementSupplier.java <ide> <ide> import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; <ide> <add>/** <add> * Gets specific elements from a {@link JavaFileObject} via {@link ElementId} annotations in the source code. <add> */ <ide> public class IdBasedElementSupplier { <add> /** <add> * The source to get elements from. <add> */ <ide> private JavaFileObject source; <ide> <add> /** <add> * Constructs a new IdBasedElementSupplier. <add> * <add> * @param source <add> * the JavaFileObject to get elements from, not null <add> * <add> * @throws IllegalArgumentException <add> * if {@code source} is null <add> */ <ide> public IdBasedElementSupplier(final JavaFileObject source) { <ide> this.source = checkNotNull(source, "Argument \'source\' cannot be null."); <ide> } <ide> <add> /** <add> * <add> * @param id <add> * @return <add> * @throws CompilerMissingException <add> */ <ide> public Set<Element> getElementsWithId(final String id) throws CompilerMissingException { <ide> checkNotNull(id, "Argument \'id\' cannot be null."); <ide> <ide> return collector.getCollectedElements(); <ide> } <ide> <add> /** <add> * <add> * @param id <add> * @return <add> * @throws CompilerMissingException <add> */ <ide> public Element getUniqueElementWithId(final String id) throws CompilerMissingException { <ide> checkNotNull(id, "Argument \'id\' cannot be null."); <ide>
Java
apache-2.0
fb001febb77106269b9f12432024c136347d9d1d
0
lpandzic/querydsl,querydsl/querydsl,vveloso/querydsl,gordski/querydsl,querydsl/querydsl,pkcool/querydsl,dharaburda/querydsl,Log10Solutions/querydsl,mosoft521/querydsl,tomforster/querydsl,izeye/querydsl,mosoft521/querydsl,kevinleturc/querydsl,Log10Solutions/querydsl,lpandzic/querydsl,tomforster/querydsl,balazs-zsoldos/querydsl,gordski/querydsl,izeye/querydsl,robertandrewbain/querydsl,mosoft521/querydsl,kevinleturc/querydsl,johnktims/querydsl,gordski/querydsl,kevinleturc/querydsl,dharaburda/querydsl,izeye/querydsl,mdiazf/querydsl,johnktims/querydsl,vveloso/querydsl,Log10Solutions/querydsl,mdiazf/querydsl,pkcool/querydsl,tomforster/querydsl,attila-kiss-it/querydsl,johnktims/querydsl,mdiazf/querydsl,balazs-zsoldos/querydsl,attila-kiss-it/querydsl,balazs-zsoldos/querydsl,robertandrewbain/querydsl,attila-kiss-it/querydsl,querydsl/querydsl,lpandzic/querydsl,vveloso/querydsl,querydsl/querydsl,dharaburda/querydsl,lpandzic/querydsl,pkcool/querydsl,robertandrewbain/querydsl
/* * Copyright 2011, Mysema Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mysema.query.types; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; import com.mysema.query.types.path.StringPath; public class QMapTest { StringPath str1 = new StringPath("str1"); StringPath str2 = new StringPath("str2"); StringPath str3 = new StringPath("str3"); StringPath str4 = new StringPath("str4"); Expression<?>[] exprs1 = new Expression[]{str1, str2}; Expression<?>[] exprs2 = new Expression[]{str3, str4}; Concatenation concat = new Concatenation(str1, str2); @Test public void TwoExpressions_getArgs(){ assertEquals(Arrays.asList(str1, str2), new QMap(str1, str2).getArgs()); } @Test public void OneArray_getArgs(){ assertEquals(Arrays.asList(str1, str2), new QMap(exprs1).getArgs()); } @Test public void TwoExpressionArrays_getArgs(){ assertEquals(Arrays.asList(str1, str2, str3, str4), new QMap(exprs1, exprs2).getArgs()); } @Test public void NestedProjection_getArgs(){ assertEquals(Arrays.asList(str1, str2), FactoryExpressionUtils.wrap(new QMap(concat)).getArgs()); } @Test public void NestedProjection_getArgs2(){ assertEquals(Arrays.asList(str1, str2, str3), FactoryExpressionUtils.wrap(new QMap(concat, str3)).getArgs()); } @Test public void NestedProjection_newInstance(){ QMap expr = new QMap(concat); assertEquals("1234", FactoryExpressionUtils.wrap(expr).newInstance("12", "34").get(concat)); } @Test public void NestedProjection_newInstance2(){ QMap expr = new QMap(str1, str2, concat); assertEquals("1234", FactoryExpressionUtils.wrap(expr).newInstance("1", "2", "12", "34").get(concat)); } @Test public void Tuple_Equals() { QMap expr = new QMap(str1, str2); assertEquals(expr.newInstance("str1", "str2"), expr.newInstance("str1", "str2")); } @Test public void Tuple_hashCode() { QMap expr = new QMap(str1, str2); assertEquals(expr.newInstance("str1", "str2").hashCode(), expr.newInstance("str1", "str2").hashCode()); } }
querydsl-core/src/test/java/com/mysema/query/types/QMapTest.java
/* * Copyright 2011, Mysema Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mysema.query.types; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.ImmutableList; import com.mysema.query.types.path.StringPath; public class QMapTest { StringPath str1 = new StringPath("str1"); StringPath str2 = new StringPath("str2"); StringPath str3 = new StringPath("str3"); StringPath str4 = new StringPath("str4"); Expression<?>[] exprs1 = new Expression[]{str1, str2}; Expression<?>[] exprs2 = new Expression[]{str3, str4}; Concatenation concat = new Concatenation(str1, str2); @Test public void TwoExpressions_getArgs(){ assertEquals(Arrays.asList(str1, str2), new QMap(str1, str2).getArgs()); } @Test public void OneArray_getArgs(){ assertEquals(Arrays.asList(str1, str2), new QMap(exprs1).getArgs()); } @Test public void TwoExpressionArrays_getArgs(){ assertEquals(Arrays.asList(str1, str2, str3, str4), new QMap(exprs1, exprs2).getArgs()); } @Test public void NestedProjection_getArgs(){ assertEquals(Arrays.asList(str1, str2), FactoryExpressionUtils.wrap(new QMap(concat)).getArgs()); } @Test public void NestedProjection_getArgs2(){ assertEquals(Arrays.asList(str1, str2, str3), FactoryExpressionUtils.wrap(new QMap(concat, str3)).getArgs()); } @Test public void NestedProjection_newInstance(){ QMap expr = new QMap(concat); assertEquals("1234", FactoryExpressionUtils.wrap(expr).newInstance("12", "34").get(concat)); } @Test public void NestedProjection_newInstance2(){ QMap expr = new QMap(str1, str2, concat); assertEquals("1234", FactoryExpressionUtils.wrap(expr).newInstance("1", "2", "12", "34").get(concat)); } @Test public void Tuple_Equals() { QMap expr = new QMap(str1, str2); assertEquals(expr.newInstance("str1", "str2"), expr.newInstance("str1", "str2")); } @Test public void Tuple_hashCode() { QMap expr = new QMap(str1, str2); assertEquals(expr.newInstance("str1", "str2").hashCode(), expr.newInstance("str1", "str2").hashCode()); } }
Remove unused imports
querydsl-core/src/test/java/com/mysema/query/types/QMapTest.java
Remove unused imports
<ide><path>uerydsl-core/src/test/java/com/mysema/query/types/QMapTest.java <ide> <ide> import java.util.Arrays; <ide> <del>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <del>import com.google.common.collect.ImmutableList; <ide> import com.mysema.query.types.path.StringPath; <ide> <ide> public class QMapTest {
Java
apache-2.0
3eba74173252aad330f7c3379a93b05f240351b5
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.engine; import static java.lang.Math.round; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.jenetics.Population.toPopulation; import static org.jenetics.internal.util.require.probability; import java.time.Clock; import java.util.Iterator; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.jenetics.internal.util.Concurrency; import org.jenetics.internal.util.require; import org.jenetics.Alterer; import org.jenetics.Chromosome; import org.jenetics.Gene; import org.jenetics.Genotype; import org.jenetics.Mutator; import org.jenetics.Optimize; import org.jenetics.Phenotype; import org.jenetics.Population; import org.jenetics.Selector; import org.jenetics.SinglePointCrossover; import org.jenetics.TournamentSelector; import org.jenetics.util.Copyable; import org.jenetics.util.Factory; import org.jenetics.util.NanoClock; /** * Genetic algorithm <em>engine</em> which is the main class. The following * example shows the main steps in initializing and executing the GA. * * [code] * public class RealFunction { * // Definition of the fitness function. * private static Double evaluate(final Genotype&lt;DoubleGene&gt; gt) { * final double x = gt.getGene().doubleValue(); * return cos(0.5 + sin(x)) * cos(x); * } * * public static void main(String[] args) { * // Create/configuring the engine via its builder. * final Engine&lt;DoubleGene, Double&gt; engine = Engine * .builder( * RealFunction::evaluate, * DoubleChromosome.of(0.0, 2.0*PI)) * .populationSize(500) * .optimize(Optimize.MINIMUM) * .alterers( * new Mutator&lt;&gt;(0.03), * new MeanAlterer&lt;&gt;(0.6)) * .build(); * * // Execute the GA (engine). * final Phenotype&lt;DoubleGene, Double&gt; result = engine.stream() * // Truncate the evolution stream if no better individual could * // be found after 5 consecutive generations. * .limit(bySteadyFitness(5)) * // Terminate the evolution after maximal 100 generations. * .limit(100) * .collect(toBestPhenotype()); * } * } * [/code] * * The architecture allows to decouple the configuration of the engine from the * execution. The {@code Engine} is configured via the {@code Engine.Builder} * class and can't be changed after creation. The actual <i>evolution</i> is * performed by the {@link EvolutionStream}, which is created by the * {@code Engine}. * <p> * <em> * <b>This class is thread safe:</b> * No mutable state is maintained by the engine. Therefore it is save to * create multiple evolution streams with one engine, which may be actually * used in different threads. * </em> * * @see Engine.Builder * @see EvolutionStart * @see EvolutionResult * @see EvolutionStream * @see EvolutionStatistics * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since 3.0 * @version 3.1 */ public final class Engine< G extends Gene<?, G>, C extends Comparable<? super C> > implements Function<EvolutionStart<G, C>, EvolutionResult<G, C>> { // Needed context for population evolving. private final Function<? super Genotype<G>, ? extends C> _fitnessFunction; private final Function<? super C, ? extends C> _fitnessScaler; private final Factory<Genotype<G>> _genotypeFactory; private final Selector<G, C> _survivorsSelector; private final Selector<G, C> _offspringSelector; private final Alterer<G, C> _alterer; private final Predicate<? super Phenotype<G, C>> _validator; private final Optimize _optimize; private final int _offspringCount; private final int _survivorsCount; private final long _maximalPhenotypeAge; // Execution context for concurrent execution of evolving steps. private final TimedExecutor _executor; private final Clock _clock; /** * Create a new GA engine with the given parameters. * * @param genotypeFactory the genotype factory this GA is working with. * @param fitnessFunction the fitness function this GA is using. * @param fitnessScaler the fitness scaler this GA is using. * @param survivorsSelector the selector used for selecting the survivors * @param offspringSelector the selector used for selecting the offspring * @param alterer the alterer used for altering the offspring * @param validator phenotype validator which can override the default * implementation the {@link Phenotype#isValid()} method. * @param optimize the kind of optimization (minimize or maximize) * @param offspringCount the number of the offspring individuals * @param survivorsCount the number of the survivor individuals * @param maximalPhenotypeAge the maximal age of an individual * @param executor the executor used for executing the single evolve steps * @param clock the clock used for calculating the timing results * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the given integer values are smaller * than one. */ Engine( final Function<? super Genotype<G>, ? extends C> fitnessFunction, final Function<? super C, ? extends C> fitnessScaler, final Factory<Genotype<G>> genotypeFactory, final Selector<G, C> survivorsSelector, final Selector<G, C> offspringSelector, final Alterer<G, C> alterer, final Predicate<? super Phenotype<G, C>> validator, final Optimize optimize, final int offspringCount, final int survivorsCount, final long maximalPhenotypeAge, final Executor executor, final Clock clock ) { _fitnessFunction = requireNonNull(fitnessFunction); _fitnessScaler = requireNonNull(fitnessScaler); _genotypeFactory = requireNonNull(genotypeFactory); _survivorsSelector = requireNonNull(survivorsSelector); _offspringSelector = requireNonNull(offspringSelector); _alterer = requireNonNull(alterer); _validator = requireNonNull(validator); _optimize = requireNonNull(optimize); _offspringCount = require.positive(offspringCount); _survivorsCount = require.positive(survivorsCount); _maximalPhenotypeAge = require.positive(maximalPhenotypeAge); _executor = new TimedExecutor(requireNonNull(executor)); _clock = requireNonNull(clock); } /** * Perform one evolution step with the given {@code population} and * {@code generation}. New phenotypes are created with the fitness function * and fitness scaler defined by this <em>engine</em> * <p> * <em>This method is thread-safe.</em> * * @see #evolve(EvolutionStart) * * @param population the population to evolve * @param generation the current generation; used for calculating the * phenotype age. * @return the evolution result * @throws java.lang.NullPointerException if the given {@code population} is * {@code null} * @throws IllegalArgumentException if the given {@code generation} is * smaller then one */ public EvolutionResult<G, C> evolve( final Population<G, C> population, final long generation ) { return evolve(EvolutionStart.of(population, generation)); } /** * Perform one evolution step with the given evolution {@code start} object * New phenotypes are created with the fitness function and fitness scaler * defined by this <em>engine</em> * <p> * <em>This method is thread-safe.</em> * * @since 3.1 * @see #evolve(org.jenetics.Population, long) * * @param start the evolution start object * @return the evolution result * @throws java.lang.NullPointerException if the given evolution * {@code start} is {@code null} */ public EvolutionResult<G, C> evolve(final EvolutionStart<G, C> start) { final Timer timer = Timer.of().start(); // Select the offspring population. final CompletableFuture<TimedResult<Population<G, C>>> offspring = _executor.async(() -> selectOffspring(start.getPopulation()), _clock ); // Select the survivor population. final CompletableFuture<TimedResult<Population<G, C>>> survivors = _executor.async(() -> selectSurvivors(start.getPopulation()), _clock ); // Altering the offspring population. final CompletableFuture<TimedResult<AlterResult<G, C>>> alteredOffspring = _executor.thenApply(offspring, p -> alter(p.result, start.getGeneration()), _clock ); // Filter and replace invalid and to old survivor individuals. final CompletableFuture<TimedResult<FilterResult<G, C>>> filteredSurvivors = _executor.thenApply(survivors, pop -> filter(pop.result, start.getGeneration()), _clock ); // Filter and replace invalid and to old offspring individuals. final CompletableFuture<TimedResult<FilterResult<G, C>>> filteredOffspring = _executor.thenApply(alteredOffspring, pop -> filter(pop.result.population, start.getGeneration()), _clock ); // Combining survivors and offspring to the new population. final CompletableFuture<Population<G, C>> population = filteredSurvivors.thenCombineAsync(filteredOffspring, (s, o) -> { final Population<G, C> pop = s.result.population; pop.addAll(o.result.population); return pop; }, _executor.get() ); // Evaluate the fitness-function and wait for result. final TimedResult<Population<G, C>> result = population .thenApply(TimedResult.of(this::evaluate, _clock)) .join(); final EvolutionDurations durations = EvolutionDurations.of( offspring.join().duration, survivors.join().duration, alteredOffspring.join().duration, filteredOffspring.join().duration, filteredSurvivors.join().duration, result.duration, timer.stop().getTime() ); final int killCount = filteredOffspring.join().result.killCount + filteredSurvivors.join().result.killCount; final int invalidCount = filteredOffspring.join().result.invalidCount + filteredSurvivors.join().result.invalidCount; return EvolutionResult.of( _optimize, result.result, start.getGeneration(), durations, killCount, invalidCount, alteredOffspring.join().result.alterCount ); } /** * This method is an <i>alias</i> for the {@link #evolve(EvolutionStart)} * method. * * @since 3.1 */ @Override public EvolutionResult<G, C> apply(final EvolutionStart<G, C> start) { return evolve(start); } // Selects the survivors population. A new population object is returned. private Population<G, C> selectSurvivors(final Population<G, C> population) { return _survivorsSelector.select(population, _survivorsCount, _optimize); } // Selects the offspring population. A new population object is returned. private Population<G, C> selectOffspring(final Population<G, C> population) { return _offspringSelector.select(population, _offspringCount, _optimize); } // Filters out invalid and to old individuals. Filtering is done in place. private FilterResult<G, C> filter( final Population<G, C> population, final long generation ) { int killCount = 0; int invalidCount = 0; for (int i = 0, n = population.size(); i < n; ++i) { final Phenotype<G, C> individual = population.get(i); if (!_validator.test(individual)) { population.set(i, newPhenotype(generation)); ++invalidCount; } else if (individual.getAge(generation) > _maximalPhenotypeAge) { population.set(i, newPhenotype(generation)); ++killCount; } } return new FilterResult<>(population, killCount, invalidCount); } // Create a new phenotype private Phenotype<G, C> newPhenotype(final long generation) { return Phenotype.of( _genotypeFactory.newInstance(), generation, _fitnessFunction, _fitnessScaler ); } // Alters the given population. The altering is done in place. private AlterResult<G, C> alter( final Population<G,C> population, final long generation ) { return new AlterResult<>( population, _alterer.alter(population, generation) ); } // Evaluates the fitness function of the give population concurrently. private Population<G, C> evaluate(final Population<G, C> population) { try (Concurrency c = Concurrency.with(_executor.get())) { c.execute(population); } return population; } /** * Create a new <b>infinite</b> evolution iterator with a newly created * population. This is an alternative way for evolution. It lets the user * start, stop and resume the evolution process whenever desired. * * @return a new <b>infinite</b> evolution iterator */ public Iterator<EvolutionResult<G, C>> iterator() { return new EvolutionIterator<>( this::evolve, this::evolutionStart ); } /** * Create a new <b>infinite</b> evolution stream with a newly created * population. * * @return a new evolution stream. */ public EvolutionStream<G, C> stream() { return EvolutionStream.of(this::evolutionStart, this::evolve); } private EvolutionStart<G, C> evolutionStart() { final int generation = 1; final int size = _offspringCount + _survivorsCount; final Population<G, C> population = new Population<G, C>(size) .fill(() -> newPhenotype(generation), size); evaluate(population); return EvolutionStart.of(population, generation); } /** * Create a new <b>infinite</b> evolution stream with the given initial * individuals. If an empty {@code Iterable} is given, the engines genotype * factory is used for creating the population. * * @param genotypes the initial individuals used for the evolution stream. * Missing individuals are created and individuals not needed are * skipped. * @return a new evolution stream. * @throws java.lang.NullPointerException if the given {@code genotypes} is * {@code null}. */ public EvolutionStream<G, C> stream( final Iterable<Genotype<G>> genotypes ) { requireNonNull(genotypes); return EvolutionStream.of( () -> evolutionStart(genotypes, 1), this::evolve ); } /** * Create a new <b>infinite</b> evolution iterator with the given initial * individuals. If an empty {@code Iterable} is given, the engines genotype * factory is used for creating the population. * * @param genotypes the initial individuals used for the evolution iterator. * Missing individuals are created and individuals not needed are * skipped. * @return a new <b>infinite</b> evolution iterator * @throws java.lang.NullPointerException if the given {@code genotypes} is * {@code null}. */ public Iterator<EvolutionResult<G, C>> iterator( final Iterable<Genotype<G>> genotypes ) { requireNonNull(genotypes); return new EvolutionIterator<>( this::evolve, () -> evolutionStart(genotypes, 1) ); } private EvolutionStart<G, C> evolutionStart( final Iterable<Genotype<G>> genotypes, final long generation ) { final Stream<Phenotype<G, C>> stream = Stream.concat( StreamSupport.stream(genotypes.spliterator(), false) .map(gt -> Phenotype.of( gt, generation, _fitnessFunction, _fitnessScaler)), Stream.generate(() -> newPhenotype(generation)) ); final Population<G, C> population = stream .limit(getPopulationSize()) .collect(toPopulation()); evaluate(population); return EvolutionStart.of(population, generation); } /** * Create a new <b>infinite</b> evolution stream with the given initial * population. If an empty {@code Population} is given, the engines genotype * factory is used for creating the population. The given population might * be the result of an other engine and this method allows to start the * evolution with the outcome of an different engine. The fitness function * and the fitness scaler are replaced by the one defined for this engine. * * @param population the initial individuals used for the evolution stream. * Missing individuals are created and individuals not needed are * skipped. * @param generation the generation the stream starts from; must be greater * than zero. * @return a new evolution stream. * @throws java.lang.NullPointerException if the given {@code population} is * {@code null}. * @throws IllegalArgumentException if the given {@code generation} is smaller * then one */ public EvolutionStream<G, C> stream( final Population<G, C> population, final long generation ) { requireNonNull(population); require.positive(generation); return EvolutionStream.of( () -> evolutionStart(population, generation), this::evolve ); } /** * Create a new <b>infinite</b> evolution iterator with the given initial * population. If an empty {@code Population} is given, the engines genotype * factory is used for creating the population. The given population might * be the result of an other engine and this method allows to start the * evolution with the outcome of an different engine. The fitness function * and the fitness scaler are replaced by the one defined for this engine. * * @param population the initial individuals used for the evolution iterator. * Missing individuals are created and individuals not needed are * skipped. * @param generation the generation the iterator starts from; must be greater * than zero. * @return a new <b>infinite</b> evolution iterator * @throws java.lang.NullPointerException if the given {@code population} is * {@code null}. * @throws IllegalArgumentException if the given {@code generation} is smaller * then one */ public Iterator<EvolutionResult<G, C>> iterator( final Population<G, C> population, final long generation ) { requireNonNull(population); require.positive(generation); return new EvolutionIterator<>( this::evolve, () -> evolutionStart(population, generation) ); } private EvolutionStart<G, C> evolutionStart( final Population<G, C> population, final long generation ) { final Stream<Phenotype<G, C>> stream = Stream.concat( population.stream() .map(p -> p.newInstance( p.getGeneration(), _fitnessFunction, _fitnessScaler)), Stream.generate(() -> newPhenotype(generation)) ); final Population<G, C> pop = stream .limit(getPopulationSize()) .collect(toPopulation()); evaluate(pop); return EvolutionStart.of(pop, generation); } /* ************************************************************************* * Property access methods. **************************************************************************/ /** * Return the fitness function of the GA engine. * * @return the fitness function */ public Function<? super Genotype<G>, ? extends C> getFitnessFunction() { return _fitnessFunction; } /** * Return the fitness scaler of the GA engine. * * @return the fitness scaler */ public Function<? super C, ? extends C> getFitnessScaler() { return _fitnessScaler; } /** * Return the used genotype {@link Factory} of the GA. The genotype factory * is used for creating the initial population and new, random individuals * when needed (as replacement for invalid and/or died genotypes). * * @return the used genotype {@link Factory} of the GA. */ public Factory<Genotype<G>> getGenotypeFactory() { return _genotypeFactory; } /** * Return the used survivor {@link Selector} of the GA. * * @return the used survivor {@link Selector} of the GA. */ public Selector<G, C> getSurvivorsSelector() { return _survivorsSelector; } /** * Return the used offspring {@link Selector} of the GA. * * @return the used offspring {@link Selector} of the GA. */ public Selector<G, C> getOffspringSelector() { return _offspringSelector; } /** * Return the used {@link Alterer} of the GA. * * @return the used {@link Alterer} of the GA. */ public Alterer<G, C> getAlterer() { return _alterer; } /** * Return the number of selected offsprings. * * @return the number of selected offsprings */ public int getOffspringCount() { return _offspringCount; } /** * The number of selected survivors. * * @return the number of selected survivors */ public int getSurvivorsCount() { return _survivorsCount; } /** * Return the number of individuals of a population. * * @return the number of individuals of a population */ public int getPopulationSize() { return _offspringCount + _survivorsCount; } /** * Return the maximal allowed phenotype age. * * @return the maximal allowed phenotype age */ public long getMaximalPhenotypeAge() { return _maximalPhenotypeAge; } /** * Return the optimization strategy. * * @return the optimization strategy */ public Optimize getOptimize() { return _optimize; } /** * Return the {@link Clock} the engine is using for measuring the execution * time. * * @return the clock used for measuring the execution time */ public Clock getClock() { return _clock; } /** * Return the {@link Executor} the engine is using for executing the * evolution steps. * * @return the executor used for performing the evolution steps */ public Executor getExecutor() { return _executor.get(); } /* ************************************************************************* * Builder methods. **************************************************************************/ /** * Create a new evolution {@code Engine.Builder} initialized with the values * of the current evolution {@code Engine}. With this method, the evolution * engine can serve as a template for an new one. * * @return a new engine builder */ public Builder<G, C> builder() { return new Builder<>(_genotypeFactory, _fitnessFunction) .alterers(_alterer) .clock(_clock) .executor(_executor.get()) .fitnessScaler(_fitnessScaler) .maximalPhenotypeAge(_maximalPhenotypeAge) .offspringFraction((double)_offspringCount/(double)getPopulationSize()) .offspringSelector(_offspringSelector) .optimize(_optimize) .populationSize(getPopulationSize()) .survivorsSelector(_survivorsSelector); } /** * Create a new evolution {@code Engine.Builder} with the given fitness * function and genotype factory. * * @param fitnessFunction the fitness function * @param genotypeFactory the genotype factory * @param <G> the gene type * @param <C> the fitness function result type * @return a new engine builder * @throws java.lang.NullPointerException if one of the arguments is * {@code null}. */ public static <G extends Gene<?, G>, C extends Comparable<? super C>> Builder<G, C> builder( final Function<? super Genotype<G>, ? extends C> fitnessFunction, final Factory<Genotype<G>> genotypeFactory ) { return new Builder<>(genotypeFactory, fitnessFunction); } /** * Create a new evolution {@code Engine.Builder} with the given fitness * function and chromosome templates. * * @param fitnessFunction the fitness function * @param chromosome the first chromosome * @param chromosomes the chromosome templates * @param <G> the gene type * @param <C> the fitness function result type * @return a new engine builder * @throws java.lang.NullPointerException if one of the arguments is * {@code null}. */ @SafeVarargs public static <G extends Gene<?, G>, C extends Comparable<? super C>> Builder<G, C> builder( final Function<? super Genotype<G>, ? extends C> fitnessFunction, final Chromosome<G> chromosome, final Chromosome<G>... chromosomes ) { return new Builder<>( Genotype.of(chromosome, chromosomes), fitnessFunction ); } /* ************************************************************************* * Inner classes **************************************************************************/ /** * Builder class for building GA {@code Engine} instances. * * @see Engine * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since 3.0 * @version 3.0 */ public static final class Builder< G extends Gene<?, G>, C extends Comparable<? super C> > implements Copyable<Builder<G, C>> { // No default values for this properties. private Function<? super Genotype<G>, ? extends C> _fitnessFunction; private Factory<Genotype<G>> _genotypeFactory; // This are the properties which default values. private Function<? super C, ? extends C> _fitnessScaler = a -> a; private Selector<G, C> _survivorsSelector = new TournamentSelector<>(3); private Selector<G, C> _offspringSelector = new TournamentSelector<>(3); private Alterer<G, C> _alterer = Alterer.of( new SinglePointCrossover<G, C>(0.2), new Mutator<>(0.15) ); private Predicate<? super Phenotype<G, C>> _validator = Phenotype::isValid; private Optimize _optimize = Optimize.MAXIMUM; private double _offspringFraction = 0.6; private int _populationSize = 50; private long _maximalPhenotypeAge = 70; private Executor _executor = ForkJoinPool.commonPool(); private Clock _clock = NanoClock.systemUTC(); private Builder( final Factory<Genotype<G>> genotypeFactory, final Function<? super Genotype<G>, ? extends C> fitnessFunction ) { _genotypeFactory = requireNonNull(genotypeFactory); _fitnessFunction = requireNonNull(fitnessFunction); } /** * Set the fitness function of the evolution {@code Engine}. * * @param function the fitness function to use in the GA {@code Engine} * @return {@code this} builder, for command chaining */ public Builder<G, C> fitnessFunction( Function<? super Genotype<G>, ? extends C> function ) { _fitnessFunction = requireNonNull(function); return this; } /** * Set the fitness scaler of the evolution {@code Engine}. <i>Default * value is set to the identity function.</i> * * @param scaler the fitness scale to use in the GA {@code Engine} * @return {@code this} builder, for command chaining */ public Builder<G, C> fitnessScaler( final Function<? super C, ? extends C> scaler ) { _fitnessScaler = requireNonNull(scaler); return this; } /** * The genotype factory used for creating new individuals. * * @param genotypeFactory the genotype factory for creating new * individuals. * @return {@code this} builder, for command chaining */ public Builder<G, C> genotypeFactory( final Factory<Genotype<G>> genotypeFactory ) { _genotypeFactory = requireNonNull(genotypeFactory); return this; } /** * The selector used for selecting the offspring population. <i>Default * values is set to {@code TournamentSelector<>(3)}.</i> * * @param selector used for selecting the offspring population * @return {@code this} builder, for command chaining */ public Builder<G, C> offspringSelector( final Selector<G, C> selector ) { _offspringSelector = requireNonNull(selector); return this; } /** * The selector used for selecting the survivors population. <i>Default * values is set to {@code TournamentSelector<>(3)}.</i> * * @param selector used for selecting survivors population * @return {@code this} builder, for command chaining */ public Builder<G, C> survivorsSelector( final Selector<G, C> selector ) { _survivorsSelector = requireNonNull(selector); return this; } /** * The selector used for selecting the survivors and offspring * population. <i>Default values is set to * {@code TournamentSelector<>(3)}.</i> * * @param selector used for selecting survivors and offspring population * @return {@code this} builder, for command chaining */ public Builder<G, C> selector(final Selector<G, C> selector) { _offspringSelector = requireNonNull(selector); _survivorsSelector = requireNonNull(selector); return this; } /** * The alterers used for alter the offspring population. <i>Default * values is set to {@code new SinglePointCrossover<>(0.2)} followed by * {@code new Mutator<>(0.15)}.</i> * * @param first the first alterer used for alter the offspring * population * @param rest the rest of the alterers used for alter the offspring * population * @return {@code this} builder, for command chaining * @throws java.lang.NullPointerException if one of the alterers is * {@code null}. */ @SafeVarargs public final Builder<G, C> alterers( final Alterer<G, C> first, final Alterer<G, C>... rest ) { requireNonNull(first); Stream.of(rest).forEach(Objects::requireNonNull); _alterer = rest.length == 0 ? first : Alterer.of(rest).compose(first); return this; } /** * The phenotype validator used for detecting invalid individuals. * <i>Default value is set to {@code Phenotype::isValue}.</i> * * @since 3.1 * * @param validator the {@code validator} used for validating the * individuals (phenotypes). * @return {@code this} builder, for command chaining * @throws java.lang.NullPointerException if the {@code validator} is * {@code null}. */ public Builder<G, C> phenotypeValidator( final Predicate<? super Phenotype<G, C>> validator ) { _validator = requireNonNull(validator); return this; } /** * The phenotype validator used for detecting invalid individuals. * <i>Default value is set to {@code Genotype::isValue}.</i> * * @since 3.1 * * @param validator the {@code validator} used for validating the * individuals (genotypes). * @return {@code this} builder, for command chaining * @throws java.lang.NullPointerException if the {@code validator} is * {@code null}. */ public Builder<G, C> genotypeValidator( final Predicate<? super Genotype<G>> validator ) { requireNonNull(validator); _validator = pt -> validator.test(pt.getGenotype()); return this; } /** * The optimization strategy used by the engine. <i>Default values is * set to {@code Optimize.MAXIMUM}.</i> * * @param optimize the optimization strategy used by the engine * @return {@code this} builder, for command chaining */ public Builder<G, C> optimize(final Optimize optimize) { _optimize = requireNonNull(optimize); return this; } /** * The offspring fraction. <i>Default values is set to {@code 0.6}.</i> * * @param fraction the offspring fraction * @return {@code this} builder, for command chaining * @throws java.lang.IllegalArgumentException if the fraction is not * within the range [0, 1]. */ public Builder<G, C> offspringFraction(final double fraction) { _offspringFraction = probability(fraction); return this; } /** * The number of individuals which form the population. <i>Default * values is set to {@code 50}.</i> * * @param size the number of individuals of a population * @return {@code this} builder, for command chaining * @throws java.lang.IllegalArgumentException if {@code size < 1} */ public Builder<G, C> populationSize(final int size) { if (size < 1) { throw new IllegalArgumentException(format( "Population size must be greater than zero, but was %s.", size )); } _populationSize = size; return this; } /** * The maximal allowed age of a phenotype. <i>Default values is set to * {@code 70}.</i> * * @param age the maximal phenotype age * @return {@code this} builder, for command chaining * @throws java.lang.IllegalArgumentException if {@code age < 1} */ public Builder<G, C> maximalPhenotypeAge(final long age) { if (age < 1) { throw new IllegalArgumentException(format( "Phenotype age must be greater than one, but was %s.", age )); } _maximalPhenotypeAge = age; return this; } /** * The executor used by the engine. * * @param executor the executor used by the engine * @return {@code this} builder, for command chaining */ public Builder<G, C> executor(final Executor executor) { _executor = requireNonNull(executor); return this; } /** * The clock used for calculating the execution durations. * * @param clock the clock used for calculating the execution durations * @return {@code this} builder, for command chaining */ public Builder<G, C> clock(final Clock clock) { _clock = requireNonNull(clock); return this; } /** * Builds an new {@code Engine} instance from the set properties. * * @return an new {@code Engine} instance from the set properties */ public Engine<G, C> build() { return new Engine<>( _fitnessFunction, _fitnessScaler, _genotypeFactory, _survivorsSelector, _offspringSelector, _alterer, _validator, _optimize, getOffspringCount(), getSurvivorsCount(), _maximalPhenotypeAge, _executor, _clock ); } private int getSurvivorsCount() { return _populationSize - getOffspringCount(); } private int getOffspringCount() { return (int)round(_offspringFraction*_populationSize); } /** * Return the used {@link Alterer} of the GA. * * @return the used {@link Alterer} of the GA. */ public Alterer<G, C> getAlterers() { return _alterer; } /** * Return the {@link Clock} the engine is using for measuring the execution * time. * * @since 3.1 * * @return the clock used for measuring the execution time */ public Clock getClock() { return _clock; } /** * Return the {@link Executor} the engine is using for executing the * evolution steps. * * @since 3.1 * * @return the executor used for performing the evolution steps */ public Executor getExecutor() { return _executor; } /** * Return the fitness function of the GA engine. * * @since 3.1 * * @return the fitness function */ public Function<? super Genotype<G>, ? extends C> getFitnessFunction() { return _fitnessFunction; } /** * Return the fitness scaler of the GA engine. * * @since 3.1 * * @return the fitness scaler */ public Function<? super C, ? extends C> getFitnessScaler() { return _fitnessScaler; } /** * Return the used genotype {@link Factory} of the GA. The genotype factory * is used for creating the initial population and new, random individuals * when needed (as replacement for invalid and/or died genotypes). * * @since 3.1 * * @return the used genotype {@link Factory} of the GA. */ public Factory<Genotype<G>> getGenotypeFactory() { return _genotypeFactory; } /** * Return the maximal allowed phenotype age. * * @since 3.1 * * @return the maximal allowed phenotype age */ public long getMaximalPhenotypeAge() { return _maximalPhenotypeAge; } /** * Return the offspring fraction. * * @return the offspring fraction. */ public double getOffspringFraction() { return _offspringFraction; } /** * Return the used offspring {@link Selector} of the GA. * * @since 3.1 * * @return the used offspring {@link Selector} of the GA. */ public Selector<G, C> getOffspringSelector() { return _offspringSelector; } /** * Return the used survivor {@link Selector} of the GA. * * @since 3.1 * * @return the used survivor {@link Selector} of the GA. */ public Selector<G, C> getSurvivorsSelector() { return _survivorsSelector; } /** * Return the optimization strategy. * * @since 3.1 * * @return the optimization strategy */ public Optimize getOptimize() { return _optimize; } /** * Return the number of individuals of a population. * * @since 3.1 * * @return the number of individuals of a population */ public int getPopulationSize() { return _populationSize; } /** * Create a new builder, with the current configuration. * * @since 3.1 * * @return a new builder, with the current configuration */ @Override public Builder<G, C> copy() { return new Builder<>(_genotypeFactory, _fitnessFunction) .alterers(_alterer) .clock(_clock) .executor(_executor) .fitnessScaler(_fitnessScaler) .maximalPhenotypeAge(_maximalPhenotypeAge) .offspringFraction(_offspringFraction) .offspringSelector(_offspringSelector) .phenotypeValidator(_validator) .optimize(_optimize) .populationSize(_populationSize) .survivorsSelector(_survivorsSelector); } } }
org.jenetics/src/main/java/org/jenetics/engine/Engine.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.engine; import static java.lang.Math.round; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.jenetics.Population.toPopulation; import static org.jenetics.internal.util.require.probability; import java.time.Clock; import java.util.Iterator; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.jenetics.internal.util.Concurrency; import org.jenetics.internal.util.require; import org.jenetics.Alterer; import org.jenetics.Chromosome; import org.jenetics.Gene; import org.jenetics.Genotype; import org.jenetics.Mutator; import org.jenetics.Optimize; import org.jenetics.Phenotype; import org.jenetics.Population; import org.jenetics.Selector; import org.jenetics.SinglePointCrossover; import org.jenetics.TournamentSelector; import org.jenetics.util.Copyable; import org.jenetics.util.Factory; import org.jenetics.util.NanoClock; /** * Genetic algorithm <em>engine</em> which is the main class. The following * example shows the main steps in initializing and executing the GA. * * [code] * public class RealFunction { * // Definition of the fitness function. * private static Double evaluate(final Genotype&lt;DoubleGene&gt; gt) { * final double x = gt.getGene().doubleValue(); * return cos(0.5 + sin(x)) * cos(x); * } * * public static void main(String[] args) { * // Create/configuring the engine via its builder. * final Engine&lt;DoubleGene, Double&gt; engine = Engine * .builder( * RealFunction::evaluate, * DoubleChromosome.of(0.0, 2.0*PI)) * .populationSize(500) * .optimize(Optimize.MINIMUM) * .alterers( * new Mutator&lt;&gt;(0.03), * new MeanAlterer&lt;&gt;(0.6)) * .build(); * * // Execute the GA (engine). * final Phenotype&lt;DoubleGene, Double&gt; result = engine.stream() * // Truncate the evolution stream if no better individual could * // be found after 5 consecutive generations. * .limit(bySteadyFitness(5)) * // Terminate the evolution after maximal 100 generations. * .limit(100) * .collect(toBestPhenotype()); * } * } * [/code] * * The architecture allows to decouple the configuration of the engine from the * execution. The {@code Engine} is configured via the {@code Engine.Builder} * class and can't be changed after creation. The actual <i>evolution</i> is * performed by the {@link EvolutionStream}, which is created by the * {@code Engine}. * <p> * <em> * <b>This class is thread safe:</b> * No mutable state is maintained by the engine. Therefore it is save to * create multiple evolution streams with one engine, which may be actually * used in different threads. * </em> * * @see Engine.Builder * @see EvolutionStart * @see EvolutionResult * @see EvolutionStream * @see EvolutionStatistics * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since 3.0 * @version 3.1 */ public final class Engine< G extends Gene<?, G>, C extends Comparable<? super C> > implements Function<EvolutionStart<G, C>, EvolutionResult<G, C>> { // Needed context for population evolving. private final Function<? super Genotype<G>, ? extends C> _fitnessFunction; private final Function<? super C, ? extends C> _fitnessScaler; private final Factory<Genotype<G>> _genotypeFactory; private final Selector<G, C> _survivorsSelector; private final Selector<G, C> _offspringSelector; private final Alterer<G, C> _alterer; private final Predicate<? super Phenotype<G, C>> _validator; private final Optimize _optimize; private final int _offspringCount; private final int _survivorsCount; private final long _maximalPhenotypeAge; // Execution context for concurrent execution of evolving steps. private final TimedExecutor _executor; private final Clock _clock; /** * Create a new GA engine with the given parameters. * * @param genotypeFactory the genotype factory this GA is working with. * @param fitnessFunction the fitness function this GA is using. * @param fitnessScaler the fitness scaler this GA is using. * @param survivorsSelector the selector used for selecting the survivors * @param offspringSelector the selector used for selecting the offspring * @param alterer the alterer used for altering the offspring * @param validator phenotype validator which can override the default * implementation the {@link Phenotype#isValid()} method. * @param optimize the kind of optimization (minimize or maximize) * @param offspringCount the number of the offspring individuals * @param survivorsCount the number of the survivor individuals * @param maximalPhenotypeAge the maximal age of an individual * @param executor the executor used for executing the single evolve steps * @param clock the clock used for calculating the timing results * @throws NullPointerException if one of the arguments is {@code null} * @throws IllegalArgumentException if the given integer values are smaller * than one. */ Engine( final Function<? super Genotype<G>, ? extends C> fitnessFunction, final Function<? super C, ? extends C> fitnessScaler, final Factory<Genotype<G>> genotypeFactory, final Selector<G, C> survivorsSelector, final Selector<G, C> offspringSelector, final Alterer<G, C> alterer, final Predicate<? super Phenotype<G, C>> validator, final Optimize optimize, final int offspringCount, final int survivorsCount, final long maximalPhenotypeAge, final Executor executor, final Clock clock ) { _fitnessFunction = requireNonNull(fitnessFunction); _fitnessScaler = requireNonNull(fitnessScaler); _genotypeFactory = requireNonNull(genotypeFactory); _survivorsSelector = requireNonNull(survivorsSelector); _offspringSelector = requireNonNull(offspringSelector); _alterer = requireNonNull(alterer); _validator = requireNonNull(validator); _optimize = requireNonNull(optimize); _offspringCount = require.positive(offspringCount); _survivorsCount = require.positive(survivorsCount); _maximalPhenotypeAge = require.positive(maximalPhenotypeAge); _executor = new TimedExecutor(requireNonNull(executor)); _clock = requireNonNull(clock); } /** * Perform one evolution step with the given {@code population} and * {@code generation}. New phenotypes are created with the fitness function * and fitness scaler defined by this <em>engine</em> * <p> * <em>This method is thread-safe.</em> * * @see #evolve(EvolutionStart) * * @param population the population to evolve * @param generation the current generation; used for calculating the * phenotype age. * @return the evolution result * @throws java.lang.NullPointerException if the given {@code population} is * {@code null} * @throws IllegalArgumentException if the given {@code generation} is * smaller then one */ public EvolutionResult<G, C> evolve( final Population<G, C> population, final long generation ) { return evolve(EvolutionStart.of(population, generation)); } /** * Perform one evolution step with the given evolution {@code start} object * New phenotypes are created with the fitness function and fitness scaler * defined by this <em>engine</em> * <p> * <em>This method is thread-safe.</em> * * @since 3.1 * @see #evolve(org.jenetics.Population, long) * * @param start the evolution start object * @return the evolution result * @throws java.lang.NullPointerException if the given evolution * {@code start} is {@code null} */ public EvolutionResult<G, C> evolve(final EvolutionStart<G, C> start) { final Timer timer = Timer.of().start(); // Select the offspring population. final CompletableFuture<TimedResult<Population<G, C>>> offspring = _executor.async(() -> selectOffspring(start.getPopulation()), _clock ); // Select the survivor population. final CompletableFuture<TimedResult<Population<G, C>>> survivors = _executor.async(() -> selectSurvivors(start.getPopulation()), _clock ); // Altering the offspring population. final CompletableFuture<TimedResult<AlterResult<G, C>>> alteredOffspring = _executor.thenApply(offspring, p -> alter(p.result, start.getGeneration()), _clock ); // Filter and replace invalid and to old survivor individuals. final CompletableFuture<TimedResult<FilterResult<G, C>>> filteredSurvivors = _executor.thenApply(survivors, pop -> filter(pop.result, start.getGeneration()), _clock ); // Filter and replace invalid and to old offspring individuals. final CompletableFuture<TimedResult<FilterResult<G, C>>> filteredOffspring = _executor.thenApply(alteredOffspring, pop -> filter(pop.result.population, start.getGeneration()), _clock ); // Combining survivors and offspring to the new population. final CompletableFuture<Population<G, C>> population = filteredSurvivors.thenCombineAsync(filteredOffspring, (s, o) -> { final Population<G, C> pop = s.result.population; pop.addAll(o.result.population); return pop; }, _executor.get() ); // Evaluate the fitness-function and wait for result. final TimedResult<Population<G, C>> result = population .thenApply(TimedResult.of(this::evaluate, _clock)) .join(); final EvolutionDurations durations = EvolutionDurations.of( offspring.join().duration, survivors.join().duration, alteredOffspring.join().duration, filteredOffspring.join().duration, filteredSurvivors.join().duration, result.duration, timer.stop().getTime() ); final int killCount = filteredOffspring.join().result.killCount + filteredSurvivors.join().result.killCount; final int invalidCount = filteredOffspring.join().result.invalidCount + filteredSurvivors.join().result.invalidCount; return EvolutionResult.of( _optimize, result.result, start.getGeneration(), durations, killCount, invalidCount, alteredOffspring.join().result.alterCount ); } /** * This method is an <i>alias</i> for the {@link #evolve(EvolutionStart)} * method. * * @since 3.1 */ @Override public EvolutionResult<G, C> apply(final EvolutionStart<G, C> start) { return evolve(start); } // Selects the survivors population. A new population object is returned. private Population<G, C> selectSurvivors(final Population<G, C> population) { return _survivorsSelector.select(population, _survivorsCount, _optimize); } // Selects the offspring population. A new population object is returned. private Population<G, C> selectOffspring(final Population<G, C> population) { return _offspringSelector.select(population, _offspringCount, _optimize); } // Filters out invalid and to old individuals. Filtering is done in place. private FilterResult<G, C> filter( final Population<G, C> population, final long generation ) { int killCount = 0; int invalidCount = 0; for (int i = 0, n = population.size(); i < n; ++i) { final Phenotype<G, C> individual = population.get(i); if (!_validator.test(individual)) { population.set(i, newPhenotype(generation)); ++invalidCount; } else if (individual.getAge(generation) > _maximalPhenotypeAge) { population.set(i, newPhenotype(generation)); ++killCount; } } return new FilterResult<>(population, killCount, invalidCount); } // Create a new phenotype private Phenotype<G, C> newPhenotype(final long generation) { return Phenotype.of( _genotypeFactory.newInstance(), generation, _fitnessFunction, _fitnessScaler ); } // Alters the given population. The altering is done in place. private AlterResult<G, C> alter( final Population<G,C> population, final long generation ) { return new AlterResult<>( population, _alterer.alter(population, generation) ); } // Evaluates the fitness function of the give population concurrently. private Population<G, C> evaluate(final Population<G, C> population) { try (Concurrency c = Concurrency.with(_executor.get())) { c.execute(population); } return population; } /** * Create a new <b>infinite</b> evolution iterator with a newly created * population. This is an alternative way for evolution. It lets the user * start, stop and resume the evolution process whenever desired. * * @return a new <b>infinite</b> evolution iterator */ public Iterator<EvolutionResult<G, C>> iterator() { return new EvolutionIterator<>( this::evolve, this::evolutionStart ); } /** * Create a new <b>infinite</b> evolution stream with a newly created * population. * * @return a new evolution stream. */ public EvolutionStream<G, C> stream() { return EvolutionStream.of(this::evolutionStart, this::evolve); } private EvolutionStart<G, C> evolutionStart() { final int generation = 1; final int size = _offspringCount + _survivorsCount; final Population<G, C> population = new Population<G, C>(size) .fill(() -> newPhenotype(generation), size); evaluate(population); return EvolutionStart.of(population, generation); } /** * Create a new <b>infinite</b> evolution stream with the given initial * individuals. If an empty {@code Iterable} is given, the engines genotype * factory is used for creating the population. * * @param genotypes the initial individuals used for the evolution stream. * Missing individuals are created and individuals not needed are * skipped. * @return a new evolution stream. * @throws java.lang.NullPointerException if the given {@code genotypes} is * {@code null}. */ public EvolutionStream<G, C> stream( final Iterable<Genotype<G>> genotypes ) { requireNonNull(genotypes); return EvolutionStream.of( () -> evolutionStart(genotypes, 1), this::evolve ); } /** * Create a new <b>infinite</b> evolution iterator with the given initial * individuals. If an empty {@code Iterable} is given, the engines genotype * factory is used for creating the population. * * @param genotypes the initial individuals used for the evolution iterator. * Missing individuals are created and individuals not needed are * skipped. * @return a new <b>infinite</b> evolution iterator * @throws java.lang.NullPointerException if the given {@code genotypes} is * {@code null}. */ public Iterator<EvolutionResult<G, C>> iterator( final Iterable<Genotype<G>> genotypes ) { requireNonNull(genotypes); return new EvolutionIterator<>( this::evolve, () -> evolutionStart(genotypes, 1) ); } private EvolutionStart<G, C> evolutionStart( final Iterable<Genotype<G>> genotypes, final long generation ) { final Stream<Phenotype<G, C>> stream = Stream.concat( StreamSupport.stream(genotypes.spliterator(), false) .map(gt -> Phenotype.of( gt, generation, _fitnessFunction, _fitnessScaler)), Stream.generate(() -> newPhenotype(generation)) ); final Population<G, C> population = stream .limit(getPopulationSize()) .collect(toPopulation()); evaluate(population); return EvolutionStart.of(population, generation); } /** * Create a new <b>infinite</b> evolution stream with the given initial * population. If an empty {@code Population} is given, the engines genotype * factory is used for creating the population. The given population might * be the result of an other engine and this method allows to start the * evolution with the outcome of an different engine. The fitness function * and the fitness scaler are replaced by the one defined for this engine. * * @param population the initial individuals used for the evolution stream. * Missing individuals are created and individuals not needed are * skipped. * @param generation the generation the stream starts from; must be greater * than zero. * @return a new evolution stream. * @throws java.lang.NullPointerException if the given {@code population} is * {@code null}. * @throws IllegalArgumentException if the given {@code generation} is smaller * then one */ public EvolutionStream<G, C> stream( final Population<G, C> population, final long generation ) { requireNonNull(population); require.positive(generation); return EvolutionStream.of( () -> evolutionStart(population, generation), this::evolve ); } /** * Create a new <b>infinite</b> evolution iterator with the given initial * population. If an empty {@code Population} is given, the engines genotype * factory is used for creating the population. The given population might * be the result of an other engine and this method allows to start the * evolution with the outcome of an different engine. The fitness function * and the fitness scaler are replaced by the one defined for this engine. * * @param population the initial individuals used for the evolution iterator. * Missing individuals are created and individuals not needed are * skipped. * @param generation the generation the iterator starts from; must be greater * than zero. * @return a new <b>infinite</b> evolution iterator * @throws java.lang.NullPointerException if the given {@code population} is * {@code null}. * @throws IllegalArgumentException if the given {@code generation} is smaller * then one */ public Iterator<EvolutionResult<G, C>> iterator( final Population<G, C> population, final long generation ) { requireNonNull(population); require.positive(generation); return new EvolutionIterator<>( this::evolve, () -> evolutionStart(population, generation) ); } private EvolutionStart<G, C> evolutionStart( final Population<G, C> population, final long generation ) { final Stream<Phenotype<G, C>> stream = Stream.concat( population.stream() .map(p -> p.newInstance( p.getGeneration(), _fitnessFunction, _fitnessScaler)), Stream.generate(() -> newPhenotype(generation)) ); final Population<G, C> pop = stream .limit(getPopulationSize()) .collect(toPopulation()); evaluate(pop); return EvolutionStart.of(pop, generation); } /* ************************************************************************* * Property access methods. **************************************************************************/ /** * Return the fitness function of the GA engine. * * @return the fitness function */ public Function<? super Genotype<G>, ? extends C> getFitnessFunction() { return _fitnessFunction; } /** * Return the fitness scaler of the GA engine. * * @return the fitness scaler */ public Function<? super C, ? extends C> getFitnessScaler() { return _fitnessScaler; } /** * Return the used genotype {@link Factory} of the GA. The genotype factory * is used for creating the initial population and new, random individuals * when needed (as replacement for invalid and/or died genotypes). * * @return the used genotype {@link Factory} of the GA. */ public Factory<Genotype<G>> getGenotypeFactory() { return _genotypeFactory; } /** * Return the used survivor {@link Selector} of the GA. * * @return the used survivor {@link Selector} of the GA. */ public Selector<G, C> getSurvivorsSelector() { return _survivorsSelector; } /** * Return the used offspring {@link Selector} of the GA. * * @return the used offspring {@link Selector} of the GA. */ public Selector<G, C> getOffspringSelector() { return _offspringSelector; } /** * Return the used {@link Alterer} of the GA. * * @return the used {@link Alterer} of the GA. */ public Alterer<G, C> getAlterer() { return _alterer; } /** * Return the number of selected offsprings. * * @return the number of selected offsprings */ public int getOffspringCount() { return _offspringCount; } /** * The number of selected survivors. * * @return the number of selected survivors */ public int getSurvivorsCount() { return _survivorsCount; } /** * Return the number of individuals of a population. * * @return the number of individuals of a population */ public int getPopulationSize() { return _offspringCount + _survivorsCount; } /** * Return the maximal allowed phenotype age. * * @return the maximal allowed phenotype age */ public long getMaximalPhenotypeAge() { return _maximalPhenotypeAge; } /** * Return the optimization strategy. * * @return the optimization strategy */ public Optimize getOptimize() { return _optimize; } /** * Return the {@link Clock} the engine is using for measuring the execution * time. * * @return the clock used for measuring the execution time */ public Clock getClock() { return _clock; } /** * Return the {@link Executor} the engine is using for executing the * evolution steps. * * @return the executor used for performing the evolution steps */ public Executor getExecutor() { return _executor.get(); } /* ************************************************************************* * Builder methods. **************************************************************************/ /** * Create a new evolution {@code Engine.Builder} initialized with the values * of the current evolution {@code Engine}. With this method, the evolution * engine can serve as a template for an new one. * * @return a new engine builder */ public Builder<G, C> builder() { return new Builder<>(_genotypeFactory, _fitnessFunction) .alterers(_alterer) .clock(_clock) .executor(_executor.get()) .fitnessScaler(_fitnessScaler) .maximalPhenotypeAge(_maximalPhenotypeAge) .offspringFraction((double)_offspringCount/(double)getPopulationSize()) .offspringSelector(_offspringSelector) .optimize(_optimize) .populationSize(getPopulationSize()) .survivorsSelector(_survivorsSelector); } /** * Create a new evolution {@code Engine.Builder} with the given fitness * function and genotype factory. * * @param fitnessFunction the fitness function * @param genotypeFactory the genotype factory * @param <G> the gene type * @param <C> the fitness function result type * @return a new engine builder * @throws java.lang.NullPointerException if one of the arguments is * {@code null}. */ public static <G extends Gene<?, G>, C extends Comparable<? super C>> Builder<G, C> builder( final Function<? super Genotype<G>, ? extends C> fitnessFunction, final Factory<Genotype<G>> genotypeFactory ) { return new Builder<>(genotypeFactory, fitnessFunction); } /** * Create a new evolution {@code Engine.Builder} with the given fitness * function and chromosome templates. * * @param fitnessFunction the fitness function * @param chromosome the first chromosome * @param chromosomes the chromosome templates * @param <G> the gene type * @param <C> the fitness function result type * @return a new engine builder * @throws java.lang.NullPointerException if one of the arguments is * {@code null}. */ @SafeVarargs public static <G extends Gene<?, G>, C extends Comparable<? super C>> Builder<G, C> builder( final Function<? super Genotype<G>, ? extends C> fitnessFunction, final Chromosome<G> chromosome, final Chromosome<G>... chromosomes ) { return new Builder<>( Genotype.of(chromosome, chromosomes), fitnessFunction ); } /* ************************************************************************* * Inner classes **************************************************************************/ /** * Builder class for building GA {@code Engine} instances. * * @see Engine * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since 3.0 * @version 3.0 */ public static final class Builder< G extends Gene<?, G>, C extends Comparable<? super C> > implements Copyable<Builder<G, C>> { // No default values for this properties. private Function<? super Genotype<G>, ? extends C> _fitnessFunction; private Factory<Genotype<G>> _genotypeFactory; // This are the properties which default values. private Function<? super C, ? extends C> _fitnessScaler = a -> a; private Selector<G, C> _survivorsSelector = new TournamentSelector<>(3); private Selector<G, C> _offspringSelector = new TournamentSelector<>(3); private Alterer<G, C> _alterer = Alterer.of( new SinglePointCrossover<G, C>(0.2), new Mutator<>(0.15) ); private Predicate<? super Phenotype<G, C>> _validator = Phenotype::isValid; private Optimize _optimize = Optimize.MAXIMUM; private double _offspringFraction = 0.6; private int _populationSize = 50; private long _maximalPhenotypeAge = 70; private Executor _executor = ForkJoinPool.commonPool(); private Clock _clock = NanoClock.systemUTC(); private Builder( final Factory<Genotype<G>> genotypeFactory, final Function<? super Genotype<G>, ? extends C> fitnessFunction ) { _genotypeFactory = requireNonNull(genotypeFactory); _fitnessFunction = requireNonNull(fitnessFunction); } /** * Set the fitness function of the evolution {@code Engine}. * * @param function the fitness function to use in the GA {@code Engine} * @return {@code this} builder, for command chaining */ public Builder<G, C> fitnessFunction( Function<? super Genotype<G>, ? extends C> function ) { _fitnessFunction = requireNonNull(function); return this; } /** * Set the fitness scaler of the evolution {@code Engine}. <i>Default * value is set to the identity function.</i> * * @param scaler the fitness scale to use in the GA {@code Engine} * @return {@code this} builder, for command chaining */ public Builder<G, C> fitnessScaler( final Function<? super C, ? extends C> scaler ) { _fitnessScaler = requireNonNull(scaler); return this; } /** * The genotype factory used for creating new individuals. * * @param genotypeFactory the genotype factory for creating new * individuals. * @return {@code this} builder, for command chaining */ public Builder<G, C> genotypeFactory( final Factory<Genotype<G>> genotypeFactory ) { _genotypeFactory = requireNonNull(genotypeFactory); return this; } /** * The selector used for selecting the offspring population. <i>Default * values is set to {@code TournamentSelector<>(3)}.</i> * * @param selector used for selecting the offspring population * @return {@code this} builder, for command chaining */ public Builder<G, C> offspringSelector( final Selector<G, C> selector ) { _offspringSelector = requireNonNull(selector); return this; } /** * The selector used for selecting the survivors population. <i>Default * values is set to {@code TournamentSelector<>(3)}.</i> * * @param selector used for selecting survivors population * @return {@code this} builder, for command chaining */ public Builder<G, C> survivorsSelector( final Selector<G, C> selector ) { _survivorsSelector = requireNonNull(selector); return this; } /** * The selector used for selecting the survivors and offspring * population. <i>Default values is set to * {@code TournamentSelector<>(3)}.</i> * * @param selector used for selecting survivors and offspring population * @return {@code this} builder, for command chaining */ public Builder<G, C> selector(final Selector<G, C> selector) { _offspringSelector = requireNonNull(selector); _survivorsSelector = requireNonNull(selector); return this; } /** * The alterers used for alter the offspring population. <i>Default * values is set to {@code new SinglePointCrossover<>(0.2)} followed by * {@code new Mutator<>(0.15)}.</i> * * @param first the first alterer used for alter the offspring * population * @param rest the rest of the alterers used for alter the offspring * population * @return {@code this} builder, for command chaining * @throws java.lang.NullPointerException if one of the alterers is * {@code null}. */ @SafeVarargs public final Builder<G, C> alterers( final Alterer<G, C> first, final Alterer<G, C>... rest ) { requireNonNull(first); Stream.of(rest).forEach(Objects::requireNonNull); _alterer = rest.length == 0 ? first : Alterer.of(rest).compose(first); return this; } /** * The phenotype validator used for detecting invalid individuals. * <i>Default value is set to {@code Phenotype::isValue}.</i> * * @param validator the {@code validator} used for validating the * individuals (phenotypes). * @return {@code this} builder, for command chaining * @throws java.lang.NullPointerException if the {@code validator} is * {@code null}. */ public Builder<G, C> phenotypeValidator( final Predicate<? super Phenotype<G, C>> validator ) { _validator = requireNonNull(validator); return this; } /** * The phenotype validator used for detecting invalid individuals. * <i>Default value is set to {@code Genotype::isValue}.</i> * * @param validator the {@code validator} used for validating the * individuals (genotypes). * @return {@code this} builder, for command chaining * @throws java.lang.NullPointerException if the {@code validator} is * {@code null}. */ public Builder<G, C> genotypeValidator( final Predicate<? super Genotype<G>> validator ) { requireNonNull(validator); _validator = pt -> validator.test(pt.getGenotype()); return this; } /** * The optimization strategy used by the engine. <i>Default values is * set to {@code Optimize.MAXIMUM}.</i> * * @param optimize the optimization strategy used by the engine * @return {@code this} builder, for command chaining */ public Builder<G, C> optimize(final Optimize optimize) { _optimize = requireNonNull(optimize); return this; } /** * The offspring fraction. <i>Default values is set to {@code 0.6}.</i> * * @param fraction the offspring fraction * @return {@code this} builder, for command chaining * @throws java.lang.IllegalArgumentException if the fraction is not * within the range [0, 1]. */ public Builder<G, C> offspringFraction(final double fraction) { _offspringFraction = probability(fraction); return this; } /** * The number of individuals which form the population. <i>Default * values is set to {@code 50}.</i> * * @param size the number of individuals of a population * @return {@code this} builder, for command chaining * @throws java.lang.IllegalArgumentException if {@code size < 1} */ public Builder<G, C> populationSize(final int size) { if (size < 1) { throw new IllegalArgumentException(format( "Population size must be greater than zero, but was %s.", size )); } _populationSize = size; return this; } /** * The maximal allowed age of a phenotype. <i>Default values is set to * {@code 70}.</i> * * @param age the maximal phenotype age * @return {@code this} builder, for command chaining * @throws java.lang.IllegalArgumentException if {@code age < 1} */ public Builder<G, C> maximalPhenotypeAge(final long age) { if (age < 1) { throw new IllegalArgumentException(format( "Phenotype age must be greater than one, but was %s.", age )); } _maximalPhenotypeAge = age; return this; } /** * The executor used by the engine. * * @param executor the executor used by the engine * @return {@code this} builder, for command chaining */ public Builder<G, C> executor(final Executor executor) { _executor = requireNonNull(executor); return this; } /** * The clock used for calculating the execution durations. * * @param clock the clock used for calculating the execution durations * @return {@code this} builder, for command chaining */ public Builder<G, C> clock(final Clock clock) { _clock = requireNonNull(clock); return this; } /** * Builds an new {@code Engine} instance from the set properties. * * @return an new {@code Engine} instance from the set properties */ public Engine<G, C> build() { return new Engine<>( _fitnessFunction, _fitnessScaler, _genotypeFactory, _survivorsSelector, _offspringSelector, _alterer, _validator, _optimize, getOffspringCount(), getSurvivorsCount(), _maximalPhenotypeAge, _executor, _clock ); } private int getSurvivorsCount() { return _populationSize - getOffspringCount(); } private int getOffspringCount() { return (int)round(_offspringFraction*_populationSize); } /** * Return the used {@link Alterer} of the GA. * * @return the used {@link Alterer} of the GA. */ public Alterer<G, C> getAlterers() { return _alterer; } /** * Return the {@link Clock} the engine is using for measuring the execution * time. * * @since 3.1 * * @return the clock used for measuring the execution time */ public Clock getClock() { return _clock; } /** * Return the {@link Executor} the engine is using for executing the * evolution steps. * * @since 3.1 * * @return the executor used for performing the evolution steps */ public Executor getExecutor() { return _executor; } /** * Return the fitness function of the GA engine. * * @since 3.1 * * @return the fitness function */ public Function<? super Genotype<G>, ? extends C> getFitnessFunction() { return _fitnessFunction; } /** * Return the fitness scaler of the GA engine. * * @since 3.1 * * @return the fitness scaler */ public Function<? super C, ? extends C> getFitnessScaler() { return _fitnessScaler; } /** * Return the used genotype {@link Factory} of the GA. The genotype factory * is used for creating the initial population and new, random individuals * when needed (as replacement for invalid and/or died genotypes). * * @since 3.1 * * @return the used genotype {@link Factory} of the GA. */ public Factory<Genotype<G>> getGenotypeFactory() { return _genotypeFactory; } /** * Return the maximal allowed phenotype age. * * @since 3.1 * * @return the maximal allowed phenotype age */ public long getMaximalPhenotypeAge() { return _maximalPhenotypeAge; } /** * Return the offspring fraction. * * @return the offspring fraction. */ public double getOffspringFraction() { return _offspringFraction; } /** * Return the used offspring {@link Selector} of the GA. * * @since 3.1 * * @return the used offspring {@link Selector} of the GA. */ public Selector<G, C> getOffspringSelector() { return _offspringSelector; } /** * Return the used survivor {@link Selector} of the GA. * * @since 3.1 * * @return the used survivor {@link Selector} of the GA. */ public Selector<G, C> getSurvivorsSelector() { return _survivorsSelector; } /** * Return the optimization strategy. * * @since 3.1 * * @return the optimization strategy */ public Optimize getOptimize() { return _optimize; } /** * Return the number of individuals of a population. * * @since 3.1 * * @return the number of individuals of a population */ public int getPopulationSize() { return _populationSize; } /** * Create a new builder, with the current configuration. * * @since 3.1 * * @return a new builder, with the current configuration */ @Override public Builder<G, C> copy() { return new Builder<>(_genotypeFactory, _fitnessFunction) .alterers(_alterer) .clock(_clock) .executor(_executor) .fitnessScaler(_fitnessScaler) .maximalPhenotypeAge(_maximalPhenotypeAge) .offspringFraction(_offspringFraction) .offspringSelector(_offspringSelector) .phenotypeValidator(_validator) .optimize(_optimize) .populationSize(_populationSize) .survivorsSelector(_survivorsSelector); } } }
#20: Add version string to new methods.
org.jenetics/src/main/java/org/jenetics/engine/Engine.java
#20: Add version string to new methods.
<ide><path>rg.jenetics/src/main/java/org/jenetics/engine/Engine.java <ide> * The phenotype validator used for detecting invalid individuals. <ide> * <i>Default value is set to {@code Phenotype::isValue}.</i> <ide> * <add> * @since 3.1 <add> * <ide> * @param validator the {@code validator} used for validating the <ide> * individuals (phenotypes). <ide> * @return {@code this} builder, for command chaining <ide> /** <ide> * The phenotype validator used for detecting invalid individuals. <ide> * <i>Default value is set to {@code Genotype::isValue}.</i> <add> * <add> * @since 3.1 <ide> * <ide> * @param validator the {@code validator} used for validating the <ide> * individuals (genotypes).
Java
apache-2.0
c50748d7fe4d107e86560e3b763f5ddec9888e9f
0
eFaps/eFapsApp-ElectronicBilling
/* * Copyright 2003 - 2016 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.electronicbilling; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.efaps.admin.datamodel.Status; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Return; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.admin.program.esjp.Listener; import org.efaps.db.Insert; import org.efaps.db.Instance; import org.efaps.db.InstanceQuery; import org.efaps.db.PrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.esjp.ci.CIContacts; import org.efaps.esjp.ci.CIEBilling; import org.efaps.esjp.ci.CIERP; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.common.AbstractCommon; import org.efaps.esjp.db.InstanceUtils; import org.efaps.esjp.electronicbilling.listener.IOnDocument; import org.efaps.esjp.electronicbilling.util.ElectronicBilling; import org.efaps.util.EFapsException; /** * The Class AbstractEBillingDocument_Base. * * @author The eFaps Team */ @EFapsUUID("171bd803-81f1-445e-ad79-5b18e35878b6") @EFapsApplication("eFapsApp-ElectronicBilling") public abstract class EBillingDocument_Base extends AbstractCommon { /** * Scan for documents. * * @param _parameter Parameter as passed by the eFaps API * @return the return * @throws EFapsException on error */ public Return scan4Documents(final Parameter _parameter) throws EFapsException { final Properties props = ElectronicBilling.QUERYBLDR4DOCSCAN.get(); final QueryBuilder queryBldr = getQueryBldrFromProperties(_parameter, props); final QueryBuilder attrQueryBldr = new QueryBuilder(CIEBilling.DocumentAbstract); queryBldr.addWhereAttrNotInQuery(CIERP.DocumentAbstract.ID, attrQueryBldr.getAttributeQuery( CIEBilling.DocumentAbstract.DocumentLinkAbstract)); final InstanceQuery query = queryBldr.getQuery(); query.execute(); final List<Instance> instances = new ArrayList<>(); while (query.next()) { if (query.getCurrentValue().getType().isCIType(CISales.Invoice)) { final Insert insert = new Insert(CIEBilling.Invoice); insert.add(CIEBilling.Invoice.InvoiceLink, query.getCurrentValue()); insert.add(CIEBilling.Invoice.Status, Status.find(CIEBilling.InvoiceStatus.Pending)); insert.executeWithoutAccessCheck(); instances.add(insert.getInstance()); } } for (final IOnDocument listener : Listener.get().<IOnDocument>invoke(IOnDocument.class)) { listener.afterCreate(_parameter, instances.toArray(new Instance[instances.size()])); } return new Return(); } /** * Resend. * * @param _parameter Parameter as passed by the eFaps API * @return the return * @throws EFapsException on error */ public Return resend(final Parameter _parameter) throws EFapsException { final List<Instance> instances = new ArrayList<>(); instances.add(_parameter.getInstance()); for (final IOnDocument listener : Listener.get().<IOnDocument>invoke(IOnDocument.class)) { listener.afterCreate(_parameter, instances.toArray(new Instance[instances.size()])); } return new Return(); } /** * Gets the emails. * * @param _parameter Parameter as passed by the eFaps API * @param _contactInstance the contact instance * @return the emails * @throws EFapsException on error */ public Return getEmails(final Parameter _parameter) throws EFapsException { getEmails(_parameter, _parameter.getInstance()); return new Return(); } /** * Gets the emails. * * @param _parameter Parameter as passed by the eFaps API * @param _contactInstance the contact instance * @return the emails * @throws EFapsException on error */ @SuppressWarnings("unchecked") public List<String> getEmails(final Parameter _parameter, final Instance _contactInstance) throws EFapsException { final List<String> ret = new ArrayList<>(); if (InstanceUtils.isKindOf(_contactInstance, CIContacts.Contact)) { final PrintQuery print = new PrintQuery(_contactInstance); final SelectBuilder selEmails = SelectBuilder.get().clazz(CIContacts.Class) .attributeset(CIContacts.Class.EmailSet, "attribute[ElectronicBilling]==true") .attribute("Email"); print.addSelect(selEmails); if (print.execute()) { final Object obj = print.getSelect(selEmails); if (obj instanceof List) { ret.addAll((List<String>) obj); } else { ret.add((String) obj); } } } return ret; } }
src/main/efaps/ESJP/org/efaps/esjp/electronicbilling/EBillingDocument_Base.java
/* * Copyright 2003 - 2016 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.esjp.electronicbilling; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.efaps.admin.datamodel.Status; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Return; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.admin.program.esjp.Listener; import org.efaps.db.Insert; import org.efaps.db.Instance; import org.efaps.db.InstanceQuery; import org.efaps.db.QueryBuilder; import org.efaps.esjp.ci.CIEBilling; import org.efaps.esjp.ci.CIERP; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.common.AbstractCommon; import org.efaps.esjp.electronicbilling.listener.IOnDocument; import org.efaps.esjp.electronicbilling.util.ElectronicBilling; import org.efaps.util.EFapsException; /** * The Class AbstractEBillingDocument_Base. * * @author The eFaps Team */ @EFapsUUID("171bd803-81f1-445e-ad79-5b18e35878b6") @EFapsApplication("eFapsApp-ElectronicBilling") public abstract class EBillingDocument_Base extends AbstractCommon { /** * Scan for documents. * * @param _parameter Parameter as passed by the eFaps API * @return the return * @throws EFapsException on error */ public Return scan4Documents(final Parameter _parameter) throws EFapsException { final Properties props = ElectronicBilling.QUERYBLDR4DOCSCAN.get(); final QueryBuilder queryBldr = getQueryBldrFromProperties(_parameter, props); final QueryBuilder attrQueryBldr = new QueryBuilder(CIEBilling.DocumentAbstract); queryBldr.addWhereAttrNotInQuery(CIERP.DocumentAbstract.ID, attrQueryBldr.getAttributeQuery( CIEBilling.DocumentAbstract.DocumentLinkAbstract)); final InstanceQuery query = queryBldr.getQuery(); query.execute(); final List<Instance> instances = new ArrayList<>(); while (query.next()) { if (query.getCurrentValue().getType().isCIType(CISales.Invoice)) { final Insert insert = new Insert(CIEBilling.Invoice); insert.add(CIEBilling.Invoice.InvoiceLink, query.getCurrentValue()); insert.add(CIEBilling.Invoice.Status, Status.find(CIEBilling.InvoiceStatus.Pending)); insert.executeWithoutAccessCheck(); instances.add(insert.getInstance()); } } for (final IOnDocument listener : Listener.get().<IOnDocument>invoke(IOnDocument.class)) { listener.afterCreate(_parameter, instances.toArray(new Instance[instances.size()])); } return new Return(); } /** * Resend. * * @param _parameter Parameter as passed by the eFaps API * @return the return * @throws EFapsException on error */ public Return resend(final Parameter _parameter) throws EFapsException { final List<Instance> instances = new ArrayList<>(); instances.add(_parameter.getInstance()); for (final IOnDocument listener : Listener.get().<IOnDocument>invoke(IOnDocument.class)) { listener.afterCreate(_parameter, instances.toArray(new Instance[instances.size()])); } return new Return(); } }
- Issue #6: Add the evaluation for email closes #6
src/main/efaps/ESJP/org/efaps/esjp/electronicbilling/EBillingDocument_Base.java
- Issue #6: Add the evaluation for email
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/electronicbilling/EBillingDocument_Base.java <ide> import org.efaps.db.Insert; <ide> import org.efaps.db.Instance; <ide> import org.efaps.db.InstanceQuery; <add>import org.efaps.db.PrintQuery; <ide> import org.efaps.db.QueryBuilder; <add>import org.efaps.db.SelectBuilder; <add>import org.efaps.esjp.ci.CIContacts; <ide> import org.efaps.esjp.ci.CIEBilling; <ide> import org.efaps.esjp.ci.CIERP; <ide> import org.efaps.esjp.ci.CISales; <ide> import org.efaps.esjp.common.AbstractCommon; <add>import org.efaps.esjp.db.InstanceUtils; <ide> import org.efaps.esjp.electronicbilling.listener.IOnDocument; <ide> import org.efaps.esjp.electronicbilling.util.ElectronicBilling; <ide> import org.efaps.util.EFapsException; <ide> } <ide> return new Return(); <ide> } <add> <add> /** <add> * Gets the emails. <add> * <add> * @param _parameter Parameter as passed by the eFaps API <add> * @param _contactInstance the contact instance <add> * @return the emails <add> * @throws EFapsException on error <add> */ <add> public Return getEmails(final Parameter _parameter) <add> throws EFapsException <add> { <add> getEmails(_parameter, _parameter.getInstance()); <add> return new Return(); <add> } <add> <add> /** <add> * Gets the emails. <add> * <add> * @param _parameter Parameter as passed by the eFaps API <add> * @param _contactInstance the contact instance <add> * @return the emails <add> * @throws EFapsException on error <add> */ <add> @SuppressWarnings("unchecked") <add> public List<String> getEmails(final Parameter _parameter, <add> final Instance _contactInstance) <add> throws EFapsException <add> { <add> final List<String> ret = new ArrayList<>(); <add> if (InstanceUtils.isKindOf(_contactInstance, CIContacts.Contact)) { <add> final PrintQuery print = new PrintQuery(_contactInstance); <add> final SelectBuilder selEmails = SelectBuilder.get().clazz(CIContacts.Class) <add> .attributeset(CIContacts.Class.EmailSet, "attribute[ElectronicBilling]==true") <add> .attribute("Email"); <add> print.addSelect(selEmails); <add> if (print.execute()) { <add> final Object obj = print.getSelect(selEmails); <add> if (obj instanceof List) { <add> ret.addAll((List<String>) obj); <add> } else { <add> ret.add((String) obj); <add> } <add> } <add> } <add> return ret; <add> } <ide> }
Java
agpl-3.0
fe9020a74c340c60cb26232452acc314f01ed3ad
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
c1273a5e-2e5f-11e5-9284-b827eb9e62be
hello.java
c1218c6c-2e5f-11e5-9284-b827eb9e62be
c1273a5e-2e5f-11e5-9284-b827eb9e62be
hello.java
c1273a5e-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>c1218c6c-2e5f-11e5-9284-b827eb9e62be <add>c1273a5e-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
d7daed9dc3da6f4213541ecf0aab45039076fb13
0
skaldarnar/TerasologyLauncher,skaldarnar/TerasologyLauncher,skaldarnar/TerasologyLauncher,MovingBlocks/TerasologyLauncher,MovingBlocks/TerasologyLauncher
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.launcher.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public final class DownloadUtils { public static final String TERASOLOGY_LAUNCHER_NIGHTLY_JOB_NAME = "TerasologyLauncherNightly"; public static final String FILE_TERASOLOGY_GAME_ZIP = "distributions/Terasology.zip"; public static final String FILE_TERASOLOGY_LAUNCHER_ZIP = "distributions/TerasologyLauncher.zip"; public static final String FILE_TERASOLOGY_GAME_VERSION_INFO = "resources/main/org/terasology/version/versionInfo.properties"; public static final String FILE_TERASOLOGY_LAUNCHER_VERSION_INFO = "resources/main/org/terasology/launcher/version/versionInfo.properties"; private static final String FILE_TERASOLOGY_LAUNCHER_CHANGE_LOG = "distributions/CHANGELOG.txt"; private static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class); private static final String JENKINS_JOB_URL = "http://jenkins.terasology.org/job/"; private static final String LAST_STABLE_BUILD = "/lastStableBuild"; private static final String LAST_SUCCESSFUL_BUILD = "/lastSuccessfulBuild"; private static final String BUILD_NUMBER = "/buildNumber/"; private static final String ARTIFACT_BUILD = "/artifact/build/"; private static final String API_JSON_RESULT = "/api/json?tree=result"; private static final String API_XML_CHANGE_LOG = "/api/xml?xpath=//changeSet/item/msg[1]&wrapper=msgs"; private static final int CONNECT_TIMEOUT = 1000 * 30; private static final int READ_TIMEOUT = 1000 * 60 * 5; private DownloadUtils() { } public static void downloadToFile(URL downloadURL, File file, ProgressListener progressListener) throws DownloadException { progressListener.update(0); final HttpURLConnection connection = getConnectedDownloadConnection(downloadURL); final long contentLength = connection.getContentLengthLong(); if (contentLength <= 0) { throw new DownloadException("Wrong content length! URL=" + downloadURL + ", contentLength=" + contentLength); } if (logger.isDebugEnabled()) { logger.debug("Download file '{}' ({}; {}) from URL '{}'.", file, contentLength, connection.getContentType(), downloadURL); } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(connection.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(file)); downloadToFile(progressListener, contentLength, in, out); } catch (IOException e) { throw new DownloadException("Could not download file from URL! URL=" + downloadURL + ", file=" + file, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Closing InputStream for '{}' failed!", downloadURL, e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Closing OutputStream for '{}' failed!", file, e); } } connection.disconnect(); } if (!progressListener.isCancelled()) { if (file.length() != contentLength) { throw new DownloadException("Wrong file length after download! " + file.length() + " != " + contentLength); } progressListener.update(100); } } private static HttpURLConnection getConnectedDownloadConnection(URL downloadURL) throws DownloadException { final HttpURLConnection connection; try { connection = (HttpURLConnection) downloadURL.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); } catch (ClassCastException | IOException e) { throw new DownloadException("Could not open/connect HTTP-URL connection! URL=" + downloadURL, e); } return connection; } private static void downloadToFile(ProgressListener progressListener, long contentLength, BufferedInputStream in, BufferedOutputStream out) throws IOException { final byte[] buffer = new byte[2048]; final float sizeFactor = 100f / (float) contentLength; long writtenBytes = 0; int n; if (!progressListener.isCancelled()) { while ((n = in.read(buffer)) != -1) { if (progressListener.isCancelled()) { break; } out.write(buffer, 0, n); writtenBytes += n; int percentage = (int) (sizeFactor * (float) writtenBytes); if (percentage < 1) { percentage = 1; } else if (percentage >= 100) { percentage = 99; } progressListener.update(percentage); if (progressListener.isCancelled()) { break; } } } } public static URL createFileDownloadUrlJenkins(String jobName, int buildNumber, String fileName) throws MalformedURLException { final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(JENKINS_JOB_URL); urlBuilder.append(jobName); urlBuilder.append("/"); urlBuilder.append(buildNumber); urlBuilder.append(ARTIFACT_BUILD); urlBuilder.append(fileName); return new URL(urlBuilder.toString()); } public static URL createUrlJenkins(String jobName, int buildNumber, String subPath) throws MalformedURLException { final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(JENKINS_JOB_URL); urlBuilder.append(jobName); urlBuilder.append("/"); urlBuilder.append(buildNumber); urlBuilder.append(subPath); return new URL(urlBuilder.toString()); } /** * Loads the <code>buildNumber</code> of the last <b>stable</b> build. */ public static int loadLastStableBuildNumberJenkins(String jobName) throws DownloadException { return loadBuildNumberJenkins(jobName, LAST_STABLE_BUILD); } /** * Loads the <code>buildNumber</code> of the last <b>successful</b> build. */ public static int loadLastSuccessfulBuildNumberJenkins(String jobName) throws DownloadException { return loadBuildNumberJenkins(jobName, LAST_SUCCESSFUL_BUILD); } private static int loadBuildNumberJenkins(String jobName, String lastBuild) throws DownloadException { int buildNumber; URL urlVersion = null; BufferedReader reader = null; try { urlVersion = new URL(JENKINS_JOB_URL + jobName + lastBuild + BUILD_NUMBER); reader = new BufferedReader(new InputStreamReader(urlVersion.openStream(), StandardCharsets.US_ASCII)); buildNumber = Integer.parseInt(reader.readLine()); } catch (IOException | RuntimeException e) { throw new DownloadException("The build number could not be loaded! job=" + jobName + ", URL=" + urlVersion, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Closing BufferedReader for '{}' failed!", urlVersion, e); } } } return buildNumber; } public static JobResult loadJobResultJenkins(String jobName, int buildNumber) throws DownloadException { JobResult jobResult = null; URL urlResult = null; BufferedReader reader = null; try { urlResult = DownloadUtils.createUrlJenkins(jobName, buildNumber, API_JSON_RESULT); reader = new BufferedReader(new InputStreamReader(urlResult.openStream(), StandardCharsets.US_ASCII)); final String jsonResult = reader.readLine(); if (jsonResult != null) { for (JobResult result : JobResult.values()) { if (jsonResult.indexOf(result.name()) == 11) { jobResult = result; break; } } if (jobResult == null) { logger.error("Unknown job result '{}' for '{}'!", jsonResult, urlResult); } } } catch (IOException | RuntimeException e) { throw new DownloadException("The job result could not be loaded! job=" + jobName + ", URL=" + urlResult, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Closing BufferedReader for '{}' failed!", urlResult, e); } } } return jobResult; } public static List<String> loadChangeLogJenkins(String jobName, int buildNumber) throws DownloadException { List<String> changeLog = null; URL urlChangeLog = null; InputStream stream = null; try { urlChangeLog = DownloadUtils.createUrlJenkins(jobName, buildNumber, API_XML_CHANGE_LOG); final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); stream = urlChangeLog.openStream(); final Document document = builder.parse(stream); final NodeList nodeList = document.getElementsByTagName("msg"); if (nodeList != null) { changeLog = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { final Node item = nodeList.item(i); if (item != null) { final Node lastChild = item.getLastChild(); if (lastChild != null) { final String textContent = lastChild.getTextContent(); if ((textContent != null) && (textContent.trim().length() > 0)) { changeLog.add(textContent.trim()); } } } } } } catch (ParserConfigurationException | SAXException | IOException | RuntimeException e) { throw new DownloadException("The change log could not be loaded! job=" + jobName + ", URL=" + urlChangeLog, e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.warn("Closing InputStream for '{}' failed!", urlChangeLog, e); } } } return changeLog; } public static String loadLauncherChangeLogJenkins(String jobName, Integer buildNumber) throws DownloadException { URL urlChangeLog = null; BufferedReader reader = null; final StringBuilder changeLog = new StringBuilder(); try { urlChangeLog = DownloadUtils.createFileDownloadUrlJenkins(jobName, buildNumber, FILE_TERASOLOGY_LAUNCHER_CHANGE_LOG); reader = new BufferedReader(new InputStreamReader(urlChangeLog.openStream(), StandardCharsets.US_ASCII)); while (true) { String line = reader.readLine(); if (line == null) { break; } if (changeLog.length() > 0) { changeLog.append("\n"); } changeLog.append(line); } } catch (IOException | RuntimeException e) { throw new DownloadException("The launcher change log could not be loaded! job=" + jobName + ", URL=" + urlChangeLog, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Closing BufferedReader for '{}' failed!", urlChangeLog, e); } } } return changeLog.toString(); } }
src/main/java/org/terasology/launcher/util/DownloadUtils.java
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.launcher.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public final class DownloadUtils { public static final String TERASOLOGY_LAUNCHER_NIGHTLY_JOB_NAME = "TerasologyLauncherNightly"; public static final String FILE_TERASOLOGY_GAME_ZIP = "distributions/Terasology.zip"; public static final String FILE_TERASOLOGY_LAUNCHER_ZIP = "distributions/TerasologyLauncher.zip"; public static final String FILE_TERASOLOGY_GAME_VERSION_INFO = "resources/main/org/terasology/version/versionInfo.properties"; public static final String FILE_TERASOLOGY_LAUNCHER_VERSION_INFO = "resources/main/org/terasology/launcher/version/versionInfo.properties"; private static final String FILE_TERASOLOGY_LAUNCHER_CHANGE_LOG = "distributions/CHANGELOG.txt"; private static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class); private static final String JENKINS_JOB_URL = "http://jenkins.movingblocks.net/job/"; private static final String LAST_STABLE_BUILD = "/lastStableBuild"; private static final String LAST_SUCCESSFUL_BUILD = "/lastSuccessfulBuild"; private static final String BUILD_NUMBER = "/buildNumber/"; private static final String ARTIFACT_BUILD = "/artifact/build/"; private static final String API_JSON_RESULT = "/api/json?tree=result"; private static final String API_XML_CHANGE_LOG = "/api/xml?xpath=//changeSet/item/msg[1]&wrapper=msgs"; private static final int CONNECT_TIMEOUT = 1000 * 30; private static final int READ_TIMEOUT = 1000 * 60 * 5; private DownloadUtils() { } public static void downloadToFile(URL downloadURL, File file, ProgressListener progressListener) throws DownloadException { progressListener.update(0); final HttpURLConnection connection = getConnectedDownloadConnection(downloadURL); final long contentLength = connection.getContentLengthLong(); if (contentLength <= 0) { throw new DownloadException("Wrong content length! URL=" + downloadURL + ", contentLength=" + contentLength); } if (logger.isDebugEnabled()) { logger.debug("Download file '{}' ({}; {}) from URL '{}'.", file, contentLength, connection.getContentType(), downloadURL); } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(connection.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(file)); downloadToFile(progressListener, contentLength, in, out); } catch (IOException e) { throw new DownloadException("Could not download file from URL! URL=" + downloadURL + ", file=" + file, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Closing InputStream for '{}' failed!", downloadURL, e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Closing OutputStream for '{}' failed!", file, e); } } connection.disconnect(); } if (!progressListener.isCancelled()) { if (file.length() != contentLength) { throw new DownloadException("Wrong file length after download! " + file.length() + " != " + contentLength); } progressListener.update(100); } } private static HttpURLConnection getConnectedDownloadConnection(URL downloadURL) throws DownloadException { final HttpURLConnection connection; try { connection = (HttpURLConnection) downloadURL.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); } catch (ClassCastException | IOException e) { throw new DownloadException("Could not open/connect HTTP-URL connection! URL=" + downloadURL, e); } return connection; } private static void downloadToFile(ProgressListener progressListener, long contentLength, BufferedInputStream in, BufferedOutputStream out) throws IOException { final byte[] buffer = new byte[2048]; final float sizeFactor = 100f / (float) contentLength; long writtenBytes = 0; int n; if (!progressListener.isCancelled()) { while ((n = in.read(buffer)) != -1) { if (progressListener.isCancelled()) { break; } out.write(buffer, 0, n); writtenBytes += n; int percentage = (int) (sizeFactor * (float) writtenBytes); if (percentage < 1) { percentage = 1; } else if (percentage >= 100) { percentage = 99; } progressListener.update(percentage); if (progressListener.isCancelled()) { break; } } } } public static URL createFileDownloadUrlJenkins(String jobName, int buildNumber, String fileName) throws MalformedURLException { final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(JENKINS_JOB_URL); urlBuilder.append(jobName); urlBuilder.append("/"); urlBuilder.append(buildNumber); urlBuilder.append(ARTIFACT_BUILD); urlBuilder.append(fileName); return new URL(urlBuilder.toString()); } public static URL createUrlJenkins(String jobName, int buildNumber, String subPath) throws MalformedURLException { final StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(JENKINS_JOB_URL); urlBuilder.append(jobName); urlBuilder.append("/"); urlBuilder.append(buildNumber); urlBuilder.append(subPath); return new URL(urlBuilder.toString()); } /** * Loads the <code>buildNumber</code> of the last <b>stable</b> build. */ public static int loadLastStableBuildNumberJenkins(String jobName) throws DownloadException { return loadBuildNumberJenkins(jobName, LAST_STABLE_BUILD); } /** * Loads the <code>buildNumber</code> of the last <b>successful</b> build. */ public static int loadLastSuccessfulBuildNumberJenkins(String jobName) throws DownloadException { return loadBuildNumberJenkins(jobName, LAST_SUCCESSFUL_BUILD); } private static int loadBuildNumberJenkins(String jobName, String lastBuild) throws DownloadException { int buildNumber; URL urlVersion = null; BufferedReader reader = null; try { urlVersion = new URL(JENKINS_JOB_URL + jobName + lastBuild + BUILD_NUMBER); reader = new BufferedReader(new InputStreamReader(urlVersion.openStream(), StandardCharsets.US_ASCII)); buildNumber = Integer.parseInt(reader.readLine()); } catch (IOException | RuntimeException e) { throw new DownloadException("The build number could not be loaded! job=" + jobName + ", URL=" + urlVersion, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Closing BufferedReader for '{}' failed!", urlVersion, e); } } } return buildNumber; } public static JobResult loadJobResultJenkins(String jobName, int buildNumber) throws DownloadException { JobResult jobResult = null; URL urlResult = null; BufferedReader reader = null; try { urlResult = DownloadUtils.createUrlJenkins(jobName, buildNumber, API_JSON_RESULT); reader = new BufferedReader(new InputStreamReader(urlResult.openStream(), StandardCharsets.US_ASCII)); final String jsonResult = reader.readLine(); if (jsonResult != null) { for (JobResult result : JobResult.values()) { if (jsonResult.indexOf(result.name()) == 11) { jobResult = result; break; } } if (jobResult == null) { logger.error("Unknown job result '{}' for '{}'!", jsonResult, urlResult); } } } catch (IOException | RuntimeException e) { throw new DownloadException("The job result could not be loaded! job=" + jobName + ", URL=" + urlResult, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Closing BufferedReader for '{}' failed!", urlResult, e); } } } return jobResult; } public static List<String> loadChangeLogJenkins(String jobName, int buildNumber) throws DownloadException { List<String> changeLog = null; URL urlChangeLog = null; InputStream stream = null; try { urlChangeLog = DownloadUtils.createUrlJenkins(jobName, buildNumber, API_XML_CHANGE_LOG); final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); stream = urlChangeLog.openStream(); final Document document = builder.parse(stream); final NodeList nodeList = document.getElementsByTagName("msg"); if (nodeList != null) { changeLog = new ArrayList<>(); for (int i = 0; i < nodeList.getLength(); i++) { final Node item = nodeList.item(i); if (item != null) { final Node lastChild = item.getLastChild(); if (lastChild != null) { final String textContent = lastChild.getTextContent(); if ((textContent != null) && (textContent.trim().length() > 0)) { changeLog.add(textContent.trim()); } } } } } } catch (ParserConfigurationException | SAXException | IOException | RuntimeException e) { throw new DownloadException("The change log could not be loaded! job=" + jobName + ", URL=" + urlChangeLog, e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.warn("Closing InputStream for '{}' failed!", urlChangeLog, e); } } } return changeLog; } public static String loadLauncherChangeLogJenkins(String jobName, Integer buildNumber) throws DownloadException { URL urlChangeLog = null; BufferedReader reader = null; final StringBuilder changeLog = new StringBuilder(); try { urlChangeLog = DownloadUtils.createFileDownloadUrlJenkins(jobName, buildNumber, FILE_TERASOLOGY_LAUNCHER_CHANGE_LOG); reader = new BufferedReader(new InputStreamReader(urlChangeLog.openStream(), StandardCharsets.US_ASCII)); while (true) { String line = reader.readLine(); if (line == null) { break; } if (changeLog.length() > 0) { changeLog.append("\n"); } changeLog.append(line); } } catch (IOException | RuntimeException e) { throw new DownloadException("The launcher change log could not be loaded! job=" + jobName + ", URL=" + urlChangeLog, e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { logger.warn("Closing BufferedReader for '{}' failed!", urlChangeLog, e); } } } return changeLog.toString(); } }
Update DownloadUtils Jenkins link to http://jenkins.terasology.org
src/main/java/org/terasology/launcher/util/DownloadUtils.java
Update DownloadUtils Jenkins link to http://jenkins.terasology.org
<ide><path>rc/main/java/org/terasology/launcher/util/DownloadUtils.java <ide> <ide> private static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class); <ide> <del> private static final String JENKINS_JOB_URL = "http://jenkins.movingblocks.net/job/"; <add> private static final String JENKINS_JOB_URL = "http://jenkins.terasology.org/job/"; <ide> private static final String LAST_STABLE_BUILD = "/lastStableBuild"; <ide> private static final String LAST_SUCCESSFUL_BUILD = "/lastSuccessfulBuild"; <ide> private static final String BUILD_NUMBER = "/buildNumber/";
Java
agpl-3.0
d0c2eb3b42f039072c3099d830a4eb89d65195f5
0
jpmml/jpmml-xgboost,jpmml/jpmml-xgboost
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-XGBoost * * JPMML-XGBoost 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. * * JPMML-XGBoost 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 JPMML-XGBoost. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.xgboost.example; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteOrder; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.xgboost.ByteOrderUtil; import org.jpmml.xgboost.FeatureMap; import org.jpmml.xgboost.HasXGBoostOptions; import org.jpmml.xgboost.Learner; import org.jpmml.xgboost.XGBoostUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { @Parameter ( names = {"--help"}, description = "Show the list of configuration options and exit", help = true ) private boolean help = false; @Parameter ( names = {"--model-input"}, description = "XGBoost model input file", required = true ) private File modelInput = null; @Parameter ( names = {"--fmap-input"}, description = "XGBoost feature map input file" ) private File fmapInput = null; @Parameter ( names = {"--pmml-output"}, description = "PMML output file", required = true ) private File pmmlOutput = null; @Parameter ( names = {"--" + HasXGBoostOptions.OPTION_BYTE_ORDER}, description = "Endianness of XGBoost model input file. Possible values \"BIG_ENDIAN\" (\"BE\") or \"LITTLE_ENDIAN\" (\"LE\")" ) private String byteOrder = (ByteOrder.nativeOrder()).toString(); @Parameter ( names = {"--" + HasXGBoostOptions.OPTION_CHARSET}, description = "Charset of XGBoost model input file" ) private String charset = null; @Parameter ( names = {"--json-path"}, description = "JSONPath expression of the JSON model element" ) private String jsonPath = "$"; @Parameter ( names = {"--missing-value"}, description = "String representation of feature value(s) that should be regarded as missing" ) private String missingValue = null; @Parameter ( names = {"--target-name"}, description = "Target name. Defaults to \"_target\"" ) private String targetName = null; @Parameter ( names = {"--target-categories"}, description = "Target categories. Defaults to 0-based index [0, 1, .., num_class - 1]" ) private List<String> targetCategories = null; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_COMPACT}, description = "Transform XGBoost-style trees to PMML-style trees", arity = 1 ) private boolean compact = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NUMERIC}, description = "Simplify non-numeric split conditions to numeric split conditions", arity = 1 ) private boolean numeric = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_PRUNE}, description = "Remove unreachable nodes", arity = 1 ) private boolean prune = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NAN_AS_MISSING}, description = "Treat Not-a-Number (NaN) values as missing values" ) private boolean nanAsMissing = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NTREE_LIMIT}, description = "Limit the number of trees. Defaults to all trees" ) private Integer ntreeLimit = null; static public void main(String... args) throws Exception { Main main = new Main(); JCommander commander = new JCommander(main); commander.setProgramName(Main.class.getName()); try { commander.parse(args); } catch(ParameterException pe){ StringBuilder sb = new StringBuilder(); sb.append(pe.toString()); sb.append("\n"); commander.usage(sb); System.err.println(sb.toString()); System.exit(-1); } if(main.help){ StringBuilder sb = new StringBuilder(); commander.usage(sb); System.out.println(sb.toString()); System.exit(0); } main.run(); } private void run() throws Exception { Learner learner; ByteOrder byteOrder = ByteOrderUtil.forValue(this.byteOrder); try(InputStream is = new FileInputStream(this.modelInput)){ logger.info("Parsing learner.."); long begin = System.currentTimeMillis(); learner = XGBoostUtil.loadLearner(is, byteOrder, this.charset, this.jsonPath); long end = System.currentTimeMillis(); logger.info("Parsed learner in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to parse learner", e); throw e; } FeatureMap featureMap; if(this.fmapInput != null){ try(InputStream is = new FileInputStream(this.fmapInput)){ logger.info("Parsing feature map.."); long begin = System.currentTimeMillis(); featureMap = XGBoostUtil.loadFeatureMap(is); long end = System.currentTimeMillis(); logger.info("Parsed feature map in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to parse feature map", e); throw e; } } else { logger.info("Parsing embedded feature map"); featureMap = learner.encodeFeatureMap(); } // End if if(this.missingValue != null){ featureMap.addMissingValue(this.missingValue); } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasXGBoostOptions.OPTION_COMPACT, this.compact); options.put(HasXGBoostOptions.OPTION_NUMERIC, this.numeric); options.put(HasXGBoostOptions.OPTION_PRUNE, this.prune); options.put(HasXGBoostOptions.OPTION_NAN_AS_MISSING, this.nanAsMissing); options.put(HasXGBoostOptions.OPTION_NTREE_LIMIT, this.ntreeLimit); PMML pmml; try { logger.info("Converting learner to PMML.."); long begin = System.currentTimeMillis(); pmml = learner.encodePMML(options, this.targetName, this.targetCategories, featureMap); long end = System.currentTimeMillis(); logger.info("Converted learner to PMML in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to convert learner to PMML", e); throw e; } try(OutputStream os = new FileOutputStream(this.pmmlOutput)){ logger.info("Marshalling PMML.."); long begin = System.currentTimeMillis(); MetroJAXBUtil.marshalPMML(pmml, os); long end = System.currentTimeMillis(); logger.info("Marshalled PMML in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to marshal PMML", e); throw e; } } private static final Logger logger = LoggerFactory.getLogger(Main.class); }
pmml-xgboost-example/src/main/java/org/jpmml/xgboost/example/Main.java
/* * Copyright (c) 2016 Villu Ruusmann * * This file is part of JPMML-XGBoost * * JPMML-XGBoost 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. * * JPMML-XGBoost 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 JPMML-XGBoost. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.xgboost.example; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteOrder; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.dmg.pmml.PMML; import org.jpmml.model.metro.MetroJAXBUtil; import org.jpmml.xgboost.ByteOrderUtil; import org.jpmml.xgboost.FeatureMap; import org.jpmml.xgboost.HasXGBoostOptions; import org.jpmml.xgboost.Learner; import org.jpmml.xgboost.XGBoostUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { @Parameter ( names = {"--help"}, description = "Show the list of configuration options and exit", help = true ) private boolean help = false; @Parameter ( names = {"--model-input"}, description = "XGBoost model input file", required = true ) private File modelInput = null; @Parameter ( names = {"--fmap-input"}, description = "XGBoost feature map input file", required = true ) private File fmapInput = null; @Parameter ( names = {"--pmml-output"}, description = "PMML output file", required = true ) private File pmmlOutput = null; @Parameter ( names = {"--" + HasXGBoostOptions.OPTION_BYTE_ORDER}, description = "Endianness of XGBoost model input file. Possible values \"BIG_ENDIAN\" (\"BE\") or \"LITTLE_ENDIAN\" (\"LE\")" ) private String byteOrder = (ByteOrder.nativeOrder()).toString(); @Parameter ( names = {"--" + HasXGBoostOptions.OPTION_CHARSET}, description = "Charset of XGBoost model input file" ) private String charset = null; @Parameter ( names = {"--json-path"}, description = "JSONPath expression of the JSON model element" ) private String jsonPath = "$"; @Parameter ( names = {"--missing-value"}, description = "String representation of feature value(s) that should be regarded as missing" ) private String missingValue = null; @Parameter ( names = {"--target-name"}, description = "Target name. Defaults to \"_target\"" ) private String targetName = null; @Parameter ( names = {"--target-categories"}, description = "Target categories. Defaults to 0-based index [0, 1, .., num_class - 1]" ) private List<String> targetCategories = null; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_COMPACT}, description = "Transform XGBoost-style trees to PMML-style trees", arity = 1 ) private boolean compact = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NUMERIC}, description = "Simplify non-numeric split conditions to numeric split conditions", arity = 1 ) private boolean numeric = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_PRUNE}, description = "Remove unreachable nodes", arity = 1 ) private boolean prune = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NAN_AS_MISSING}, description = "Treat Not-a-Number (NaN) values as missing values" ) private boolean nanAsMissing = true; @Parameter ( names = {"--X-" + HasXGBoostOptions.OPTION_NTREE_LIMIT}, description = "Limit the number of trees. Defaults to all trees" ) private Integer ntreeLimit = null; static public void main(String... args) throws Exception { Main main = new Main(); JCommander commander = new JCommander(main); commander.setProgramName(Main.class.getName()); try { commander.parse(args); } catch(ParameterException pe){ StringBuilder sb = new StringBuilder(); sb.append(pe.toString()); sb.append("\n"); commander.usage(sb); System.err.println(sb.toString()); System.exit(-1); } if(main.help){ StringBuilder sb = new StringBuilder(); commander.usage(sb); System.out.println(sb.toString()); System.exit(0); } main.run(); } private void run() throws Exception { Learner learner; ByteOrder byteOrder = ByteOrderUtil.forValue(this.byteOrder); try(InputStream is = new FileInputStream(this.modelInput)){ logger.info("Parsing learner.."); long begin = System.currentTimeMillis(); learner = XGBoostUtil.loadLearner(is, byteOrder, this.charset, this.jsonPath); long end = System.currentTimeMillis(); logger.info("Parsed learner in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to parse learner", e); throw e; } FeatureMap featureMap; try(InputStream is = new FileInputStream(this.fmapInput)){ logger.info("Parsing feature map.."); long begin = System.currentTimeMillis(); featureMap = XGBoostUtil.loadFeatureMap(is); long end = System.currentTimeMillis(); logger.info("Parsed feature map in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to parse feature map", e); throw e; } if(this.missingValue != null){ featureMap.addMissingValue(this.missingValue); } Map<String, Object> options = new LinkedHashMap<>(); options.put(HasXGBoostOptions.OPTION_COMPACT, this.compact); options.put(HasXGBoostOptions.OPTION_NUMERIC, this.numeric); options.put(HasXGBoostOptions.OPTION_PRUNE, this.prune); options.put(HasXGBoostOptions.OPTION_NAN_AS_MISSING, this.nanAsMissing); options.put(HasXGBoostOptions.OPTION_NTREE_LIMIT, this.ntreeLimit); PMML pmml; try { logger.info("Converting learner to PMML.."); long begin = System.currentTimeMillis(); pmml = learner.encodePMML(options, this.targetName, this.targetCategories, featureMap); long end = System.currentTimeMillis(); logger.info("Converted learner to PMML in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to convert learner to PMML", e); throw e; } try(OutputStream os = new FileOutputStream(this.pmmlOutput)){ logger.info("Marshalling PMML.."); long begin = System.currentTimeMillis(); MetroJAXBUtil.marshalPMML(pmml, os); long end = System.currentTimeMillis(); logger.info("Marshalled PMML in {} ms.", (end - begin)); } catch(Exception e){ logger.error("Failed to marshal PMML", e); throw e; } } private static final Logger logger = LoggerFactory.getLogger(Main.class); }
Changed the '--fmap-input' command-line option from required to optional
pmml-xgboost-example/src/main/java/org/jpmml/xgboost/example/Main.java
Changed the '--fmap-input' command-line option from required to optional
<ide><path>mml-xgboost-example/src/main/java/org/jpmml/xgboost/example/Main.java <ide> <ide> @Parameter ( <ide> names = {"--fmap-input"}, <del> description = "XGBoost feature map input file", <del> required = true <add> description = "XGBoost feature map input file" <ide> ) <ide> private File fmapInput = null; <ide> <ide> <ide> FeatureMap featureMap; <ide> <del> try(InputStream is = new FileInputStream(this.fmapInput)){ <del> logger.info("Parsing feature map.."); <del> <del> long begin = System.currentTimeMillis(); <del> featureMap = XGBoostUtil.loadFeatureMap(is); <del> long end = System.currentTimeMillis(); <del> <del> logger.info("Parsed feature map in {} ms.", (end - begin)); <del> } catch(Exception e){ <del> logger.error("Failed to parse feature map", e); <del> <del> throw e; <del> } <add> if(this.fmapInput != null){ <add> <add> try(InputStream is = new FileInputStream(this.fmapInput)){ <add> logger.info("Parsing feature map.."); <add> <add> long begin = System.currentTimeMillis(); <add> featureMap = XGBoostUtil.loadFeatureMap(is); <add> long end = System.currentTimeMillis(); <add> <add> logger.info("Parsed feature map in {} ms.", (end - begin)); <add> } catch(Exception e){ <add> logger.error("Failed to parse feature map", e); <add> <add> throw e; <add> } <add> } else <add> <add> { <add> logger.info("Parsing embedded feature map"); <add> <add> featureMap = learner.encodeFeatureMap(); <add> } // End if <ide> <ide> if(this.missingValue != null){ <ide> featureMap.addMissingValue(this.missingValue);
Java
mit
7f01742c5e4ceb8025bc534ebb508203aad58f19
0
Innovimax-SARL/mix-them
package innovimax.mixthem.io; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; /** * <p>Reads lines from a character-input file.</p> * <p>This is the default implementation of IInputLine.</p> * @see IInputLine * @author Innovimax * @version 1.0 */ public class DefaultLineReader implements IInputLine { private final BufferedReader reader; /** * Creates a line reader from a file. * @param input The input file to be read * @throws IOException - If an I/O error occurs */ public DefaultLineReader(File input) throws IOException { this.reader = Files.newBufferedReader(input.toPath(), StandardCharsets.UTF_8); } /** * Creates a line reader from an input stream. * @param input The input stream to be read * @throws IOException - If an I/O error occurs */ public DefaultLineReader(InputStream input) throws IOException { this.reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); } @Override public boolean hasLine() throws IOException { return this.reader.ready(); } @Override public String nextLine() throws IOException { String line = null; if (hasLine()) { line = this.reader.readLine(); } return line; } @Override public void close() throws IOException { this.reader.close(); } }
src/main/java/innovimax/mixthem/io/DefaultLineReader.java
package innovimax.mixthem.io; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** * <p>Reads lines from a character-input file.</p> * <p>This is the default implementation of IInputLine.</p> * @see IInputLine * @author Innovimax * @version 1.0 */ public class DefaultLineReader implements IInputLine { private final BufferedReader reader; /** * Creates a line reader from a file. * @param input The input file to be read * @throws IOException - If an I/O error occurs */ public DefaultLineReader(File input) throws IOException { this.reader = Files.newBufferedReader(input.toPath(), StandardCharsets.UTF_8); } /** * Creates a line reader from an input stream. * @param input The input stream to be read * @throws IOException - If an I/O error occurs */ public DefaultLineReader(InputStream input) throws IOException { this.reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); } @Override public boolean hasLine() throws IOException { return this.reader.ready(); } @Override public String nextLine() throws IOException { String line = null; if (hasLine()) { line = this.reader.readLine(); } return line; } @Override public void close() throws IOException { this.reader.close(); } }
Update DefaultLineReader.java
src/main/java/innovimax/mixthem/io/DefaultLineReader.java
Update DefaultLineReader.java
<ide><path>rc/main/java/innovimax/mixthem/io/DefaultLineReader.java <ide> import java.io.IOException; <ide> import java.nio.charset.StandardCharsets; <ide> import java.nio.file.Files; <del>import java.nio.file.Path; <ide> <ide> /** <ide> * <p>Reads lines from a character-input file.</p>
Java
bsd-3-clause
2738d2fa30c80e96eae8d44488677885a14ab6ff
0
compgen-io/ngsutilsj,compgen-io/ngsutilsj
package io.compgen.ngsutils.cli.bam; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.exceptions.CommandArgumentException; import io.compgen.cmdline.impl.AbstractCommand; import io.compgen.common.RadixSet; import io.compgen.common.progress.FileChannelStats; import io.compgen.common.progress.ProgressMessage; import io.compgen.common.progress.ProgressUtils; import io.compgen.ngsutils.bam.support.ReadUtils; import io.compgen.ngsutils.support.CloseableFinalizer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.Iterator; @Command(name="bam-check", desc="Checks a BAM file to make sure it is valid", category="bam") public class BamCheck extends AbstractCommand { private String filename = null; private boolean lenient = false; private boolean silent = false; private boolean mates = false; @UnnamedArg(name = "FILE") public void setFilename(String filename) { this.filename = filename; } @Option(desc = "Check for missing read-mates (paired-end)", name="mates") public void setMates(boolean mates) { this.mates = mates; } @Option(desc = "Use lenient validation strategy", name="lenient") public void setLenient(boolean lenient) { this.lenient = lenient; } @Option(desc = "Use silent validation strategy", name="silent") public void setSilent(boolean silent) { this.silent = silent; } @Exec public void exec() throws IOException, CommandArgumentException { if (filename == null) { throw new CommandArgumentException("You must specify an input BAM filename!"); } SamReaderFactory readerFactory = SamReaderFactory.makeDefault(); if (lenient) { readerFactory.validationStringency(ValidationStringency.LENIENT); } else if (silent) { readerFactory.validationStringency(ValidationStringency.SILENT); } SamReader reader = null; String name; FileChannel channel = null; if (filename.equals("-")) { reader = readerFactory.open(SamInputResource.of(System.in)); name = "<stdin>"; } else { File f = new File(filename); FileInputStream fis = new FileInputStream(f); channel = fis.getChannel(); reader = readerFactory.open(SamInputResource.of(fis)); name = f.getName(); } final RadixSet setOne = new RadixSet(); final RadixSet setTwo = new RadixSet(); final RadixSet goodReads = new RadixSet(); Iterator<SAMRecord> it = ProgressUtils.getIterator(name, reader.iterator(), (channel == null)? null : new FileChannelStats(channel), new ProgressMessage<SAMRecord>() { long i = 0; @Override public String msg(SAMRecord current) { i++; return i+" "+current.getReadName() + " "+setOne.size()+"/"+setTwo.size()+"/"+goodReads.size(); }}, new CloseableFinalizer<SAMRecord>()); long i = 0; SAMRecord lastRead = null; int error = 0; while (it.hasNext()) { i++; SAMRecord read = it.next(); if (read.getReadName() == null) { System.err.println("\nERROR: Read-name empty - bad file? (last good read: "+lastRead.getReadName()+" "+lastRead.getReferenceName()+":"+lastRead.getAlignmentStart()+")"); error++; } lastRead = read; if (read.getBaseQualities().length != read.getReadBases().length) { System.err.println("\nERROR: Base calls / quality length mismatch: "+read.getReadName()+")"); error++; } if (read.getReadPairedFlag() && mates) { String readname = read.getReadName(); if (!goodReads.contains(readname)) { if (read.getFirstOfPairFlag()) { if (setTwo.contains(readname)) { setTwo.remove(readname); if (!ReadUtils.isReadUniquelyMapped(read)) { goodReads.add(readname); } } else { setOne.add(readname); } } else { if (setOne.contains(readname)) { setOne.remove(readname); if (!ReadUtils.isReadUniquelyMapped(read)) { goodReads.add(readname); } } else { setTwo.add(readname); } } } } } reader.close(); if (mates) { System.err.println("Reads with missing mates: "+ (setOne.size()+setTwo.size())); if (setOne.size() > 0) { Iterator<String> it2 = setOne.iterator(); for (int j=0; j<10 && setOne.size() > j; j++) { System.err.println("Example read: "+it2.next()); error++; } } } if (error>0) { System.err.println("File had errors!"); System.err.println("Total reads: "+i); System.err.println("Errors: "+error); System.exit(1); } System.err.println("Successfully read "+i+" records."); } }
src/java/io/compgen/ngsutils/cli/bam/BamCheck.java
package io.compgen.ngsutils.cli.bam; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.exceptions.CommandArgumentException; import io.compgen.cmdline.impl.AbstractCommand; import io.compgen.common.RadixSet; import io.compgen.common.progress.FileChannelStats; import io.compgen.common.progress.ProgressMessage; import io.compgen.common.progress.ProgressUtils; import io.compgen.ngsutils.bam.support.ReadUtils; import io.compgen.ngsutils.support.CloseableFinalizer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.Iterator; @Command(name="bam-check", desc="Checks a BAM file to make sure it is valid", category="bam") public class BamCheck extends AbstractCommand { private String filename = null; private boolean lenient = false; private boolean silent = false; private boolean mates = false; @UnnamedArg(name = "FILE") public void setFilename(String filename) { this.filename = filename; } @Option(desc = "Check for missing read-mates (paired-end)", name="mates") public void setMates(boolean mates) { this.mates = mates; } @Option(desc = "Use lenient validation strategy", name="lenient") public void setLenient(boolean lenient) { this.lenient = lenient; } @Option(desc = "Use silent validation strategy", name="silent") public void setSilent(boolean silent) { this.silent = silent; } @Exec public void exec() throws IOException, CommandArgumentException { if (filename == null) { throw new CommandArgumentException("You must specify an input BAM filename!"); } SamReaderFactory readerFactory = SamReaderFactory.makeDefault(); if (lenient) { readerFactory.validationStringency(ValidationStringency.LENIENT); } else if (silent) { readerFactory.validationStringency(ValidationStringency.SILENT); } SamReader reader = null; String name; FileChannel channel = null; if (filename.equals("-")) { reader = readerFactory.open(SamInputResource.of(System.in)); name = "<stdin>"; } else { File f = new File(filename); FileInputStream fis = new FileInputStream(f); channel = fis.getChannel(); reader = readerFactory.open(SamInputResource.of(fis)); name = f.getName(); } final RadixSet setOne = new RadixSet(); final RadixSet setTwo = new RadixSet(); final RadixSet goodReads = new RadixSet(); Iterator<SAMRecord> it = ProgressUtils.getIterator(name, reader.iterator(), (channel == null)? null : new FileChannelStats(channel), new ProgressMessage<SAMRecord>() { long i = 0; @Override public String msg(SAMRecord current) { i++; return i+" "+current.getReadName() + " "+setOne.size()+"/"+setTwo.size()+"/"+goodReads.size(); }}, new CloseableFinalizer<SAMRecord>()); long i = 0; while (it.hasNext()) { i++; SAMRecord read = it.next(); if (read.getReadPairedFlag() && mates) { String readname = read.getReadName(); if (!goodReads.contains(readname)) { if (read.getFirstOfPairFlag()) { if (setTwo.contains(readname)) { setTwo.remove(readname); if (!ReadUtils.isReadUniquelyMapped(read)) { goodReads.add(readname); } } else { setOne.add(readname); } } else { if (setOne.contains(readname)) { setOne.remove(readname); if (!ReadUtils.isReadUniquelyMapped(read)) { goodReads.add(readname); } } else { setTwo.add(readname); } } } } } reader.close(); System.err.println("Successfully read: "+i+" records."); if (mates) { System.err.println("Reads with missing mates: "+ (setOne.size()+setTwo.size())); if (setOne.size() > 0) { Iterator<String> it2 = setOne.iterator(); for (int j=0; j<10 && setOne.size() > j; j++) { System.err.println("Example read: "+it2.next()); } } } } }
added another check for an empty name - indicative of a corrupted file
src/java/io/compgen/ngsutils/cli/bam/BamCheck.java
added another check for an empty name - indicative of a corrupted file
<ide><path>rc/java/io/compgen/ngsutils/cli/bam/BamCheck.java <ide> return i+" "+current.getReadName() + " "+setOne.size()+"/"+setTwo.size()+"/"+goodReads.size(); <ide> }}, new CloseableFinalizer<SAMRecord>()); <ide> long i = 0; <add> SAMRecord lastRead = null; <add> int error = 0; <ide> while (it.hasNext()) { <ide> i++; <ide> SAMRecord read = it.next(); <add> <add> if (read.getReadName() == null) { <add> System.err.println("\nERROR: Read-name empty - bad file? (last good read: "+lastRead.getReadName()+" "+lastRead.getReferenceName()+":"+lastRead.getAlignmentStart()+")"); <add> error++; <add> } <add> <add> lastRead = read; <add> <add> if (read.getBaseQualities().length != read.getReadBases().length) { <add> System.err.println("\nERROR: Base calls / quality length mismatch: "+read.getReadName()+")"); <add> error++; <add> } <ide> <ide> if (read.getReadPairedFlag() && mates) { <ide> String readname = read.getReadName(); <ide> } <ide> } <ide> reader.close(); <del> System.err.println("Successfully read: "+i+" records."); <ide> if (mates) { <ide> System.err.println("Reads with missing mates: "+ (setOne.size()+setTwo.size())); <ide> if (setOne.size() > 0) { <ide> Iterator<String> it2 = setOne.iterator(); <ide> for (int j=0; j<10 && setOne.size() > j; j++) { <ide> System.err.println("Example read: "+it2.next()); <add> error++; <ide> } <ide> } <ide> } <add> <add> if (error>0) { <add> System.err.println("File had errors!"); <add> System.err.println("Total reads: "+i); <add> System.err.println("Errors: "+error); <add> System.exit(1); <add> } <add> System.err.println("Successfully read "+i+" records."); <ide> } <ide> }
Java
mit
68e30cc12962bb899354e86692d0a89023593d98
0
mickele/DBFlow,Raizlabs/DBFlow,Raizlabs/DBFlow,janzoner/DBFlow,mickele/DBFlow
package com.raizlabs.android.dbflow.sql.saveable; import android.content.ContentValues; import android.support.annotation.NonNull; import com.raizlabs.android.dbflow.annotation.ConflictAction; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.sql.SqlUtils; import com.raizlabs.android.dbflow.sql.language.Delete; import com.raizlabs.android.dbflow.sql.language.SQLite; import com.raizlabs.android.dbflow.structure.BaseModel; import com.raizlabs.android.dbflow.structure.InternalAdapter; import com.raizlabs.android.dbflow.structure.Model; import com.raizlabs.android.dbflow.structure.ModelAdapter; import com.raizlabs.android.dbflow.structure.RetrievalAdapter; import com.raizlabs.android.dbflow.structure.database.DatabaseStatement; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; /** * Description: Defines how models get saved into the DB. It will bind values to {@link android.content.ContentValues} for * an update, execute a {@link DatabaseStatement}, or delete an object via the {@link Delete} wrapper. */ public class ModelSaver<TModel extends Model, TTable extends Model, TAdapter extends RetrievalAdapter & InternalAdapter> { private static final int INSERT_FAILED = -1; private final ModelAdapter<TModel> modelAdapter; private final TAdapter adapter; public ModelSaver(ModelAdapter<TModel> modelAdapter, TAdapter adapter) { this.modelAdapter = modelAdapter; this.adapter = adapter; } public synchronized void save(@NonNull TTable model) { save(model, getWritableDatabase(modelAdapter)); } @SuppressWarnings("unchecked") public synchronized void save(@NonNull TTable model, DatabaseWrapper wrapper) { boolean exists = adapter.exists(model, wrapper); if (exists) { exists = update(model, wrapper); } if (!exists) { exists = insert(model, wrapper) > INSERT_FAILED; } if (exists) { SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.SAVE); } } public synchronized boolean update(@NonNull TTable model) { return update(model, getWritableDatabase(modelAdapter), new ContentValues()); } public synchronized boolean update(@NonNull TTable model, @NonNull DatabaseWrapper wrapper) { return update(model, wrapper, new ContentValues()); } @SuppressWarnings("unchecked") public synchronized boolean update(@NonNull TTable model, @NonNull DatabaseWrapper wrapper, @NonNull ContentValues contentValues) { adapter.bindToContentValues(contentValues, model); boolean successful = wrapper.updateWithOnConflict(modelAdapter.getTableName(), contentValues, adapter.getPrimaryConditionClause(model).getQuery(), null, ConflictAction.getSQLiteDatabaseAlgorithmInt(modelAdapter.getUpdateOnConflictAction())) != 0; if (successful) { SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.UPDATE); } return successful; } @SuppressWarnings("unchecked") public synchronized long insert(@NonNull TTable model) { return insert(model, modelAdapter.getInsertStatement()); } @SuppressWarnings("unchecked") public synchronized long insert(@NonNull TTable model, @NonNull DatabaseWrapper wrapper) { return insert(model, modelAdapter.getInsertStatement(wrapper)); } @SuppressWarnings("unchecked") public synchronized long insert(@NonNull TTable model, @NonNull DatabaseStatement insertStatement) { adapter.bindToInsertStatement(insertStatement, model); long id = insertStatement.executeInsert(); if (id > INSERT_FAILED) { adapter.updateAutoIncrement(model, id); SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.INSERT); } return id; } public synchronized boolean delete(@NonNull TTable model) { return delete(model, getWritableDatabase(modelAdapter)); } @SuppressWarnings("unchecked") public synchronized boolean delete(@NonNull TTable model, @NonNull DatabaseWrapper wrapper) { boolean successful = SQLite.delete(model.getClass()) .where(adapter.getPrimaryConditionClause(model)) .count(wrapper) != 0; if (successful) { SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.DELETE); } adapter.updateAutoIncrement(model, 0); return successful; } protected DatabaseWrapper getWritableDatabase(ModelAdapter<TModel> modelAdapter) { return FlowManager.getDatabaseForTable(modelAdapter.getModelClass()).getWritableDatabase(); } }
dbflow/src/main/java/com/raizlabs/android/dbflow/sql/saveable/ModelSaver.java
package com.raizlabs.android.dbflow.sql.saveable; import android.content.ContentValues; import com.raizlabs.android.dbflow.annotation.ConflictAction; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.sql.SqlUtils; import com.raizlabs.android.dbflow.sql.language.Delete; import com.raizlabs.android.dbflow.sql.language.SQLite; import com.raizlabs.android.dbflow.structure.BaseModel; import com.raizlabs.android.dbflow.structure.InternalAdapter; import com.raizlabs.android.dbflow.structure.Model; import com.raizlabs.android.dbflow.structure.ModelAdapter; import com.raizlabs.android.dbflow.structure.RetrievalAdapter; import com.raizlabs.android.dbflow.structure.database.DatabaseStatement; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; /** * Description: Defines how models get saved into the DB. It will bind values to {@link android.content.ContentValues} for * an update, execute a {@link DatabaseStatement}, or delete an object via the {@link Delete} wrapper. */ public class ModelSaver<TModel extends Model, TTable extends Model, TAdapter extends RetrievalAdapter & InternalAdapter> { private static final int INSERT_FAILED = -1; private final ModelAdapter<TModel> modelAdapter; private final TAdapter adapter; public ModelSaver(ModelAdapter<TModel> modelAdapter, TAdapter adapter) { this.modelAdapter = modelAdapter; this.adapter = adapter; } public synchronized void save(TTable model) { save(model, getWritableDatabase(modelAdapter)); } @SuppressWarnings("unchecked") public synchronized void save(TTable model, DatabaseWrapper wrapper) { if (model == null) { throw new IllegalArgumentException("Model from " + modelAdapter.getModelClass() + " was null"); } boolean exists = adapter.exists(model, wrapper); if (exists) { exists = update(model, wrapper); } if (!exists) { exists = insert(model, wrapper) > INSERT_FAILED; } if (exists) { SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.SAVE); } } public synchronized boolean update(TTable model) { return update(model, getWritableDatabase(modelAdapter)); } @SuppressWarnings("unchecked") public synchronized boolean update(TTable model, DatabaseWrapper wrapper) { ContentValues contentValues = new ContentValues(); adapter.bindToContentValues(contentValues, model); boolean successful = wrapper.updateWithOnConflict(modelAdapter.getTableName(), contentValues, adapter.getPrimaryConditionClause(model).getQuery(), null, ConflictAction.getSQLiteDatabaseAlgorithmInt(modelAdapter.getUpdateOnConflictAction())) != 0; if (successful) { SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.UPDATE); } return successful; } @SuppressWarnings("unchecked") public synchronized long insert(TTable model, DatabaseWrapper wrapper) { DatabaseStatement insertStatement = modelAdapter.getInsertStatement(wrapper); adapter.bindToInsertStatement(insertStatement, model); long id = insertStatement.executeInsert(); if (id > INSERT_FAILED) { adapter.updateAutoIncrement(model, id); SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.INSERT); } return id; } @SuppressWarnings("unchecked") public synchronized long insert(TTable model) { DatabaseStatement insertStatement = modelAdapter.getInsertStatement(); adapter.bindToInsertStatement(insertStatement, model); long id = insertStatement.executeInsert(); if (id > INSERT_FAILED) { adapter.updateAutoIncrement(model, id); SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.INSERT); } return id; } public synchronized boolean delete(TTable model) { return delete(model, getWritableDatabase(modelAdapter)); } @SuppressWarnings("unchecked") public synchronized boolean delete(TTable model, DatabaseWrapper wrapper) { boolean successful = SQLite.delete((Class<TTable>) adapter.getModelClass()).where( adapter.getPrimaryConditionClause(model)).count(wrapper) != 0; if (successful) { SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.DELETE); } adapter.updateAutoIncrement(model, 0); return successful; } protected DatabaseWrapper getWritableDatabase(ModelAdapter<TModel> modelAdapter) { return FlowManager.getDatabaseForTable(modelAdapter.getModelClass()).getWritableDatabase(); } }
added nononnull param annos. simplified some checks. can reuse contentvalues.
dbflow/src/main/java/com/raizlabs/android/dbflow/sql/saveable/ModelSaver.java
added nononnull param annos. simplified some checks. can reuse contentvalues.
<ide><path>bflow/src/main/java/com/raizlabs/android/dbflow/sql/saveable/ModelSaver.java <ide> package com.raizlabs.android.dbflow.sql.saveable; <ide> <ide> import android.content.ContentValues; <add>import android.support.annotation.NonNull; <ide> <ide> import com.raizlabs.android.dbflow.annotation.ConflictAction; <ide> import com.raizlabs.android.dbflow.config.FlowManager; <ide> this.adapter = adapter; <ide> } <ide> <del> public synchronized void save(TTable model) { <add> public synchronized void save(@NonNull TTable model) { <ide> save(model, getWritableDatabase(modelAdapter)); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> public synchronized void save(TTable model, DatabaseWrapper wrapper) { <del> if (model == null) { <del> throw new IllegalArgumentException("Model from " + modelAdapter.getModelClass() + " was null"); <del> } <del> <add> public synchronized void save(@NonNull TTable model, DatabaseWrapper wrapper) { <ide> boolean exists = adapter.exists(model, wrapper); <ide> <ide> if (exists) { <ide> } <ide> } <ide> <del> public synchronized boolean update(TTable model) { <del> return update(model, getWritableDatabase(modelAdapter)); <add> public synchronized boolean update(@NonNull TTable model) { <add> return update(model, getWritableDatabase(modelAdapter), new ContentValues()); <add> } <add> <add> public synchronized boolean update(@NonNull TTable model, @NonNull DatabaseWrapper wrapper) { <add> return update(model, wrapper, new ContentValues()); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> public synchronized boolean update(TTable model, DatabaseWrapper wrapper) { <del> ContentValues contentValues = new ContentValues(); <add> public synchronized boolean update(@NonNull TTable model, @NonNull DatabaseWrapper wrapper, <add> @NonNull ContentValues contentValues) { <ide> adapter.bindToContentValues(contentValues, model); <ide> boolean successful = wrapper.updateWithOnConflict(modelAdapter.getTableName(), contentValues, <ide> adapter.getPrimaryConditionClause(model).getQuery(), null, <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> public synchronized long insert(TTable model, DatabaseWrapper wrapper) { <del> DatabaseStatement insertStatement = modelAdapter.getInsertStatement(wrapper); <add> public synchronized long insert(@NonNull TTable model) { <add> return insert(model, modelAdapter.getInsertStatement()); <add> } <add> <add> @SuppressWarnings("unchecked") <add> public synchronized long insert(@NonNull TTable model, @NonNull DatabaseWrapper wrapper) { <add> return insert(model, modelAdapter.getInsertStatement(wrapper)); <add> } <add> <add> @SuppressWarnings("unchecked") <add> public synchronized long insert(@NonNull TTable model, @NonNull DatabaseStatement insertStatement) { <ide> adapter.bindToInsertStatement(insertStatement, model); <ide> long id = insertStatement.executeInsert(); <ide> if (id > INSERT_FAILED) { <ide> return id; <ide> } <ide> <del> @SuppressWarnings("unchecked") <del> public synchronized long insert(TTable model) { <del> DatabaseStatement insertStatement = modelAdapter.getInsertStatement(); <del> adapter.bindToInsertStatement(insertStatement, model); <del> long id = insertStatement.executeInsert(); <del> if (id > INSERT_FAILED) { <del> adapter.updateAutoIncrement(model, id); <del> SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.INSERT); <del> } <del> return id; <del> } <del> <del> public synchronized boolean delete(TTable model) { <add> public synchronized boolean delete(@NonNull TTable model) { <ide> return delete(model, getWritableDatabase(modelAdapter)); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> public synchronized boolean delete(TTable model, DatabaseWrapper wrapper) { <del> boolean successful = SQLite.delete((Class<TTable>) adapter.getModelClass()).where( <del> adapter.getPrimaryConditionClause(model)).count(wrapper) != 0; <add> public synchronized boolean delete(@NonNull TTable model, @NonNull DatabaseWrapper wrapper) { <add> boolean successful = SQLite.delete(model.getClass()) <add> .where(adapter.getPrimaryConditionClause(model)) <add> .count(wrapper) != 0; <ide> if (successful) { <ide> SqlUtils.notifyModelChanged(model, adapter, modelAdapter, BaseModel.Action.DELETE); <ide> }
Java
apache-2.0
34125e82365e911f5d2f5c44b73e370e83380d97
0
dropbox/bazel,snnn/bazel,dslomov/bazel-windows,werkt/bazel,dslomov/bazel-windows,bazelbuild/bazel,dslomov/bazel,dslomov/bazel-windows,perezd/bazel,snnn/bazel,davidzchen/bazel,safarmer/bazel,perezd/bazel,damienmg/bazel,dropbox/bazel,twitter-forks/bazel,damienmg/bazel,dslomov/bazel,snnn/bazel,perezd/bazel,perezd/bazel,perezd/bazel,dslomov/bazel-windows,bazelbuild/bazel,spxtr/bazel,katre/bazel,davidzchen/bazel,variac/bazel,cushon/bazel,twitter-forks/bazel,dslomov/bazel,aehlig/bazel,bazelbuild/bazel,werkt/bazel,aehlig/bazel,perezd/bazel,cushon/bazel,aehlig/bazel,akira-baruah/bazel,ulfjack/bazel,aehlig/bazel,ulfjack/bazel,aehlig/bazel,dslomov/bazel,dropbox/bazel,dropbox/bazel,meteorcloudy/bazel,cushon/bazel,safarmer/bazel,twitter-forks/bazel,cushon/bazel,twitter-forks/bazel,katre/bazel,safarmer/bazel,juhalindfors/bazel-patches,akira-baruah/bazel,variac/bazel,aehlig/bazel,snnn/bazel,safarmer/bazel,dslomov/bazel,akira-baruah/bazel,ulfjack/bazel,davidzchen/bazel,damienmg/bazel,meteorcloudy/bazel,damienmg/bazel,safarmer/bazel,davidzchen/bazel,werkt/bazel,katre/bazel,bazelbuild/bazel,dropbox/bazel,damienmg/bazel,safarmer/bazel,akira-baruah/bazel,dslomov/bazel,ButterflyNetwork/bazel,ulfjack/bazel,variac/bazel,werkt/bazel,werkt/bazel,snnn/bazel,katre/bazel,juhalindfors/bazel-patches,meteorcloudy/bazel,meteorcloudy/bazel,snnn/bazel,dropbox/bazel,ButterflyNetwork/bazel,dslomov/bazel,spxtr/bazel,aehlig/bazel,dslomov/bazel-windows,spxtr/bazel,spxtr/bazel,spxtr/bazel,bazelbuild/bazel,ulfjack/bazel,dslomov/bazel-windows,juhalindfors/bazel-patches,ButterflyNetwork/bazel,twitter-forks/bazel,variac/bazel,twitter-forks/bazel,davidzchen/bazel,spxtr/bazel,akira-baruah/bazel,ButterflyNetwork/bazel,juhalindfors/bazel-patches,cushon/bazel,perezd/bazel,damienmg/bazel,damienmg/bazel,ulfjack/bazel,ButterflyNetwork/bazel,meteorcloudy/bazel,cushon/bazel,davidzchen/bazel,katre/bazel,akira-baruah/bazel,meteorcloudy/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,spxtr/bazel,variac/bazel,variac/bazel,werkt/bazel,juhalindfors/bazel-patches,snnn/bazel,juhalindfors/bazel-patches,juhalindfors/bazel-patches,variac/bazel,twitter-forks/bazel,ulfjack/bazel,katre/bazel,davidzchen/bazel
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.objc; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEFINE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DYNAMIC_FRAMEWORK_FILE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.HEADER; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.IMPORTED_LIBRARY; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE_SYSTEM; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STATIC_FRAMEWORK_FILE; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.AnalysisEnvironment; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.config.BuildConfiguration; import com.google.devtools.build.lib.packages.BuildType; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.TargetUtils; import com.google.devtools.build.lib.rules.apple.AppleConfiguration; import com.google.devtools.build.lib.rules.cpp.CcLibraryHelper; import com.google.devtools.build.lib.rules.cpp.CcLibraryHelper.Info; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.Variables.VariablesExtension; import com.google.devtools.build.lib.rules.cpp.CcToolchainProvider; import com.google.devtools.build.lib.rules.cpp.CppCompileAction; import com.google.devtools.build.lib.rules.cpp.CppConfiguration; import com.google.devtools.build.lib.rules.cpp.CppHelper; import com.google.devtools.build.lib.rules.cpp.CppLinkAction; import com.google.devtools.build.lib.rules.cpp.CppLinkActionBuilder; import com.google.devtools.build.lib.rules.cpp.CppRuleClasses; import com.google.devtools.build.lib.rules.cpp.FdoSupportProvider; import com.google.devtools.build.lib.rules.cpp.IncludeProcessing; import com.google.devtools.build.lib.rules.cpp.Link.LinkStaticness; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.rules.cpp.NoProcessing; import com.google.devtools.build.lib.rules.cpp.PrecompiledFiles; import com.google.devtools.build.lib.rules.objc.ObjcProvider.Flag; import com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.VariableCategory; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.Collection; import javax.annotation.Nullable; /** * Constructs command lines for objc compilation, archiving, and linking. Uses the crosstool * infrastructure to register {@link CppCompileAction} and {@link CppLinkAction} instances, making * use of a provided toolchain. * * <p>TODO(b/28403953): Deprecate LegacyCompilationSupport in favor of this implementation for all * objc rules. */ public class CrosstoolCompilationSupport extends CompilationSupport { private static final String OBJC_MODULE_FEATURE_NAME = "use_objc_modules"; private static final String NO_ENABLE_MODULES_FEATURE_NAME = "no_enable_modules"; private static final String DEAD_STRIP_FEATURE_NAME = "dead_strip"; private static final String RUN_COVERAGE_FEATURE_NAME = "run_coverage"; /** Produce artifacts for coverage in llvm coverage mapping format. */ private static final String LLVM_COVERAGE_MAP_FORMAT = "llvm_coverage_map_format"; /** Produce artifacts for coverage in gcc coverage mapping format. */ private static final String GCC_COVERAGE_MAP_FORMAT = "gcc_coverage_map_format"; /** * Enabled if this target's rule is not a test rule. Binary stripping should not be applied in * the link step. TODO(b/36562173): Replace this behavior with a condition on bundle creation. * * <p>Note that the crosstool does not support feature negation in FlagSet.with_feature, which * is the mechanism used to condition linker arguments here. Therefore, we expose * "is_not_test_target" instead of the more intuitive "is_test_target". */ private static final String IS_NOT_TEST_TARGET_FEATURE_NAME = "is_not_test_target"; /** Enabled if this target generates debug symbols in a dSYM file. */ private static final String GENERATE_DSYM_FILE_FEATURE_NAME = "generate_dsym_file"; /** * Enabled if this target does not generate debug symbols. * * <p>Note that the crosstool does not support feature negation in FlagSet.with_feature, which is * the mechanism used to condition linker arguments here. Therefore, we expose * "no_generate_debug_symbols" in addition to "generate_dsym_file" */ private static final String NO_GENERATE_DEBUG_SYMBOLS_FEATURE_NAME = "no_generate_debug_symbols"; private static final ImmutableList<String> ACTIVATED_ACTIONS = ImmutableList.of( "objc-compile", "objc++-compile", "objc-archive", "objc-fully-link", "objc-executable", "objc++-executable", "assemble", "preprocess-assemble", "c-compile", "c++-compile"); /** * Creates a new CompilationSupport instance that uses the c++ rule backend * * @param ruleContext the RuleContext for the calling target */ public CrosstoolCompilationSupport(RuleContext ruleContext) { this( ruleContext, ruleContext.getConfiguration(), ObjcRuleClasses.intermediateArtifacts(ruleContext), CompilationAttributes.Builder.fromRuleContext(ruleContext).build(), /*useDeps=*/true); } /** * Creates a new CompilationSupport instance that uses the c++ rule backend * * @param ruleContext the RuleContext for the calling target * @param buildConfiguration the configuration for the calling target * @param intermediateArtifacts IntermediateArtifacts for deriving artifact paths * @param compilationAttributes attributes of the calling target * @param useDeps true if deps should be used */ public CrosstoolCompilationSupport(RuleContext ruleContext, BuildConfiguration buildConfiguration, IntermediateArtifacts intermediateArtifacts, CompilationAttributes compilationAttributes, boolean useDeps) { super(ruleContext, buildConfiguration, intermediateArtifacts, compilationAttributes, useDeps); } @Override CompilationSupport registerCompileAndArchiveActions( CompilationArtifacts compilationArtifacts, ObjcProvider objcProvider, ExtraCompileArgs extraCompileArgs, Iterable<PathFragment> priorityHeaders, @Nullable CcToolchainProvider ccToolchain, @Nullable FdoSupportProvider fdoSupport) throws RuleErrorException, InterruptedException { Preconditions.checkNotNull(ccToolchain); Preconditions.checkNotNull(fdoSupport); ObjcVariablesExtension.Builder extension = new ObjcVariablesExtension.Builder() .setRuleContext(ruleContext) .setObjcProvider(objcProvider) .setCompilationArtifacts(compilationArtifacts) .setIntermediateArtifacts(intermediateArtifacts) .setConfiguration(buildConfiguration); CcLibraryHelper helper; if (compilationArtifacts.getArchive().isPresent()) { Artifact objList = intermediateArtifacts.archiveObjList(); // TODO(b/30783125): Signal the need for this action in the CROSSTOOL. registerObjFilelistAction(getObjFiles(compilationArtifacts, intermediateArtifacts), objList); extension.addVariableCategory(VariableCategory.ARCHIVE_VARIABLES); helper = createCcLibraryHelper( objcProvider, compilationArtifacts, extension.build(), ccToolchain, fdoSupport) .setLinkType(LinkTargetType.OBJC_ARCHIVE) .addLinkActionInput(objList); } else { helper = createCcLibraryHelper( objcProvider, compilationArtifacts, extension.build(), ccToolchain, fdoSupport); } registerHeaderScanningActions(helper.build(), objcProvider, compilationArtifacts); return this; } @Override protected CompilationSupport registerFullyLinkAction( ObjcProvider objcProvider, Iterable<Artifact> inputArtifacts, Artifact outputArchive, @Nullable CcToolchainProvider ccToolchain, @Nullable FdoSupportProvider fdoSupport) throws InterruptedException { Preconditions.checkNotNull(ccToolchain); Preconditions.checkNotNull(fdoSupport); PathFragment labelName = PathFragment.create(ruleContext.getLabel().getName()); String libraryIdentifier = ruleContext .getPackageDirectory() .getRelative(labelName.replaceName("lib" + labelName.getBaseName())) .getPathString(); ObjcVariablesExtension extension = new ObjcVariablesExtension.Builder() .setRuleContext(ruleContext) .setObjcProvider(objcProvider) .setConfiguration(buildConfiguration) .setIntermediateArtifacts(intermediateArtifacts) .setFullyLinkArchive(outputArchive) .addVariableCategory(VariableCategory.FULLY_LINK_VARIABLES) .build(); CppLinkAction fullyLinkAction = new CppLinkActionBuilder(ruleContext, outputArchive, ccToolchain, fdoSupport) .addActionInputs(objcProvider.getObjcLibraries()) .addActionInputs(objcProvider.getCcLibraries()) .addActionInputs(objcProvider.get(IMPORTED_LIBRARY).toSet()) .setCrosstoolInputs(ccToolchain.getLink()) .setLinkType(LinkTargetType.OBJC_FULLY_LINKED_ARCHIVE) .setLinkStaticness(LinkStaticness.FULLY_STATIC) .setLibraryIdentifier(libraryIdentifier) .addVariablesExtension(extension) .setFeatureConfiguration(getFeatureConfiguration(ruleContext, buildConfiguration)) .build(); ruleContext.registerAction(fullyLinkAction); return this; } private StrippingType getStrippingType(ExtraLinkArgs extraLinkArgs) { return Iterables.contains(extraLinkArgs, "-dynamiclib") ? StrippingType.DYNAMIC_LIB : StrippingType.DEFAULT; } @Override CompilationSupport registerLinkActions( ObjcProvider objcProvider, J2ObjcMappingFileProvider j2ObjcMappingFileProvider, J2ObjcEntryClassProvider j2ObjcEntryClassProvider, ExtraLinkArgs extraLinkArgs, Iterable<Artifact> extraLinkInputs, DsymOutputType dsymOutputType, CcToolchainProvider toolchain) throws InterruptedException { Iterable<Artifact> prunedJ2ObjcArchives = computeAndStripPrunedJ2ObjcArchives( j2ObjcEntryClassProvider, j2ObjcMappingFileProvider, objcProvider); ImmutableList<Artifact> bazelBuiltLibraries = Iterables.isEmpty(prunedJ2ObjcArchives) ? objcProvider.getObjcLibraries() : substituteJ2ObjcPrunedLibraries(objcProvider); Artifact inputFileList = intermediateArtifacts.linkerObjList(); ImmutableSet<Artifact> forceLinkArtifacts = getForceLoadArtifacts(objcProvider); Iterable<Artifact> objFiles = Iterables.concat( bazelBuiltLibraries, objcProvider.get(IMPORTED_LIBRARY), objcProvider.getCcLibraries()); // Clang loads archives specified in filelists and also specified as -force_load twice, // resulting in duplicate symbol errors unless they are deduped. objFiles = Iterables.filter(objFiles, Predicates.not(Predicates.in(forceLinkArtifacts))); registerObjFilelistAction(objFiles, inputFileList); LinkTargetType linkType = (objcProvider.is(Flag.USES_CPP)) ? LinkTargetType.OBJCPP_EXECUTABLE : LinkTargetType.OBJC_EXECUTABLE; ObjcVariablesExtension.Builder extensionBuilder = new ObjcVariablesExtension.Builder() .setRuleContext(ruleContext) .setObjcProvider(objcProvider) .setConfiguration(buildConfiguration) .setIntermediateArtifacts(intermediateArtifacts) .setFrameworkNames(frameworkNames(objcProvider)) .setLibraryNames(libraryNames(objcProvider)) .setForceLoadArtifacts(getForceLoadArtifacts(objcProvider)) .setAttributeLinkopts(attributes.linkopts()) .addVariableCategory(VariableCategory.EXECUTABLE_LINKING_VARIABLES); Artifact binaryToLink = getBinaryToLink(); FdoSupportProvider fdoSupport = CppHelper.getFdoSupport(ruleContext, ":cc_toolchain"); CppLinkActionBuilder executableLinkAction = new CppLinkActionBuilder(ruleContext, binaryToLink, toolchain, fdoSupport) .setMnemonic("ObjcLink") .addActionInputs(bazelBuiltLibraries) .addActionInputs(objcProvider.getCcLibraries()) .addTransitiveActionInputs(objcProvider.get(IMPORTED_LIBRARY)) .addTransitiveActionInputs(objcProvider.get(STATIC_FRAMEWORK_FILE)) .addTransitiveActionInputs(objcProvider.get(DYNAMIC_FRAMEWORK_FILE)) .setCrosstoolInputs(toolchain.getLink()) .addActionInputs(prunedJ2ObjcArchives) .addActionInputs(extraLinkInputs) .addActionInput(inputFileList) .setLinkType(linkType) .setLinkStaticness(LinkStaticness.FULLY_STATIC) .addLinkopts(ImmutableList.copyOf(extraLinkArgs)) .setFeatureConfiguration(getFeatureConfiguration(ruleContext, buildConfiguration)); if (objcConfiguration.generateDsym()) { Artifact dsymBundleZip = intermediateArtifacts.tempDsymBundleZip(dsymOutputType); extensionBuilder .setDsymBundleZip(dsymBundleZip) .addVariableCategory(VariableCategory.DSYM_VARIABLES) .setDsymOutputType(dsymOutputType); registerDsymActions(dsymOutputType); executableLinkAction.addActionOutput(dsymBundleZip); } executableLinkAction.addVariablesExtension(extensionBuilder.build()); ruleContext.registerAction(executableLinkAction.build()); if (objcConfiguration.shouldStripBinary()) { registerBinaryStripAction(binaryToLink, getStrippingType(extraLinkArgs)); } return this; } private IncludeProcessing createIncludeProcessing( Iterable<Artifact> privateHdrs, ObjcProvider objcProvider, @Nullable Artifact pchHdr) { if (isHeaderThinningEnabled()) { Iterable<Artifact> potentialInputs = Iterables.concat( privateHdrs, objcProvider.get(HEADER), objcProvider.get(STATIC_FRAMEWORK_FILE), objcProvider.get(DYNAMIC_FRAMEWORK_FILE)); if (pchHdr != null) { potentialInputs = Iterables.concat(potentialInputs, ImmutableList.of(pchHdr)); } return new HeaderThinning(potentialInputs); } else { return new NoProcessing(); } } private CcLibraryHelper createCcLibraryHelper( ObjcProvider objcProvider, CompilationArtifacts compilationArtifacts, VariablesExtension extension, CcToolchainProvider ccToolchain, FdoSupportProvider fdoSupport) { PrecompiledFiles precompiledFiles = new PrecompiledFiles(ruleContext); Collection<Artifact> arcSources = ImmutableSortedSet.copyOf(compilationArtifacts.getSrcs()); Collection<Artifact> nonArcSources = ImmutableSortedSet.copyOf(compilationArtifacts.getNonArcSrcs()); Collection<Artifact> privateHdrs = ImmutableSortedSet.copyOf(compilationArtifacts.getPrivateHdrs()); Collection<Artifact> publicHdrs = ImmutableSortedSet.copyOf(attributes.hdrs()); Artifact pchHdr = null; if (ruleContext.attributes().has("pch", BuildType.LABEL)) { pchHdr = ruleContext.getPrerequisiteArtifact("pch", Mode.TARGET); } ObjcCppSemantics semantics = new ObjcCppSemantics( objcProvider, createIncludeProcessing(privateHdrs, objcProvider, pchHdr), ruleContext.getFragment(ObjcConfiguration.class), isHeaderThinningEnabled(), intermediateArtifacts); CcLibraryHelper result = new CcLibraryHelper( ruleContext, semantics, getFeatureConfiguration(ruleContext, buildConfiguration), CcLibraryHelper.SourceCategory.CC_AND_OBJC, ccToolchain, fdoSupport, buildConfiguration) .addSources(arcSources, ImmutableMap.of("objc_arc", "")) .addSources(nonArcSources, ImmutableMap.of("no_objc_arc", "")) .addSources(privateHdrs) .addDefines(objcProvider.get(DEFINE)) .enableCompileProviders() .addPublicHeaders(publicHdrs) .addPrecompiledFiles(precompiledFiles) .addDeps(ruleContext.getPrerequisites("deps", Mode.TARGET)) // Not all our dependencies need to export cpp information. // For example, objc_proto_library can depend on a proto_library rule that does not // generate C++ protos. .setCheckDepsGenerateCpp(false) .addCopts(getCompileRuleCopts()) .addIncludeDirs(objcProvider.get(INCLUDE)) .addCopts(ruleContext.getFragment(ObjcConfiguration.class).getCoptsForCompilationMode()) .addSystemIncludeDirs(objcProvider.get(INCLUDE_SYSTEM)) .setCppModuleMap(intermediateArtifacts.moduleMap()) .setLinkedArtifactNameSuffix(intermediateArtifacts.archiveFileNameSuffix()) .setPropagateModuleMapToCompileAction(false) .setNeverLink(true) .addVariableExtension(extension); if (pchHdr != null) { result.addNonModuleMapHeader(pchHdr); } if (!useDeps) { result.doNotUseDeps(); } return result; } private static FeatureConfiguration getFeatureConfiguration(RuleContext ruleContext, BuildConfiguration configuration) { ImmutableList.Builder<String> activatedCrosstoolSelectables = ImmutableList.<String>builder() .addAll(ACTIVATED_ACTIONS) .addAll( ruleContext .getFragment(AppleConfiguration.class) .getBitcodeMode() .getFeatureNames()) // We create a module map by default to allow for Swift interop. .add(CppRuleClasses.MODULE_MAPS) .add(CppRuleClasses.COMPILE_ALL_MODULES) .add(CppRuleClasses.EXCLUDE_PRIVATE_HEADERS_IN_MODULE_MAPS) .add(CppRuleClasses.ONLY_DOTH_HEADERS_IN_MODULE_MAPS) .add(CppRuleClasses.COMPILE_ACTION_FLAGS_IN_FLAG_SET) .add(CppRuleClasses.DEPENDENCY_FILE) .add(CppRuleClasses.INCLUDE_PATHS) .add(configuration.getCompilationMode().toString()); if (configuration.getFragment(ObjcConfiguration.class).moduleMapsEnabled()) { activatedCrosstoolSelectables.add(OBJC_MODULE_FEATURE_NAME); } if (!CompilationAttributes.Builder.fromRuleContext(ruleContext).build().enableModules()) { activatedCrosstoolSelectables.add(NO_ENABLE_MODULES_FEATURE_NAME); } if (configuration.getFragment(ObjcConfiguration.class).shouldStripBinary()) { activatedCrosstoolSelectables.add(DEAD_STRIP_FEATURE_NAME); } if (ruleContext.attributes().has("pch", BuildType.LABEL) && ruleContext.getPrerequisiteArtifact("pch", Mode.TARGET) != null) { activatedCrosstoolSelectables.add("pch"); } if (configuration.isCodeCoverageEnabled()) { activatedCrosstoolSelectables.add(RUN_COVERAGE_FEATURE_NAME); } if (configuration.isLLVMCoverageMapFormatEnabled()) { activatedCrosstoolSelectables.add(LLVM_COVERAGE_MAP_FORMAT); } else { activatedCrosstoolSelectables.add(GCC_COVERAGE_MAP_FORMAT); } if (!TargetUtils.isTestRule(ruleContext.getRule())) { activatedCrosstoolSelectables.add(IS_NOT_TEST_TARGET_FEATURE_NAME); } if (configuration.getFragment(ObjcConfiguration.class).generateDsym()) { activatedCrosstoolSelectables.add(GENERATE_DSYM_FILE_FEATURE_NAME); } else { activatedCrosstoolSelectables.add(NO_GENERATE_DEBUG_SYMBOLS_FEATURE_NAME); } activatedCrosstoolSelectables.addAll(ruleContext.getFeatures()); return configuration .getFragment(CppConfiguration.class) .getFeatures() .getFeatureConfiguration(activatedCrosstoolSelectables.build()); } private static ImmutableList<Artifact> getObjFiles( CompilationArtifacts compilationArtifacts, IntermediateArtifacts intermediateArtifacts) { ImmutableList.Builder<Artifact> result = new ImmutableList.Builder<>(); for (Artifact sourceFile : compilationArtifacts.getSrcs()) { result.add(intermediateArtifacts.objFile(sourceFile)); } for (Artifact nonArcSourceFile : compilationArtifacts.getNonArcSrcs()) { result.add(intermediateArtifacts.objFile(nonArcSourceFile)); } return result.build(); } private void registerHeaderScanningActions( Info info, ObjcProvider objcProvider, CompilationArtifacts compilationArtifacts) { // PIC is not used for Obj-C builds, if that changes this method will need to change if (!isHeaderThinningEnabled() || info.getCcCompilationOutputs().getObjectFiles(false).isEmpty()) { return; } ImmutableList.Builder<ObjcHeaderThinningInfo> headerThinningInfos = ImmutableList.builder(); AnalysisEnvironment analysisEnvironment = ruleContext.getAnalysisEnvironment(); for (Artifact objectFile : info.getCcCompilationOutputs().getObjectFiles(false)) { ActionAnalysisMetadata generatingAction = analysisEnvironment.getLocalGeneratingAction(objectFile); if (generatingAction instanceof CppCompileAction) { CppCompileAction action = (CppCompileAction) generatingAction; Artifact sourceFile = action.getSourceFile(); if (!sourceFile.isTreeArtifact() && SOURCES_FOR_HEADER_THINNING.matches(sourceFile.getFilename())) { headerThinningInfos.add( new ObjcHeaderThinningInfo( sourceFile, intermediateArtifacts.headersListFile(sourceFile), action.getCompilerOptions())); } } } registerHeaderScanningActions(headerThinningInfos.build(), objcProvider, compilationArtifacts); } }
src/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.objc; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DEFINE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.DYNAMIC_FRAMEWORK_FILE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.HEADER; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.IMPORTED_LIBRARY; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.INCLUDE_SYSTEM; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.STATIC_FRAMEWORK_FILE; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.AnalysisEnvironment; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.config.BuildConfiguration; import com.google.devtools.build.lib.packages.BuildType; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.TargetUtils; import com.google.devtools.build.lib.rules.apple.AppleConfiguration; import com.google.devtools.build.lib.rules.cpp.CcLibraryHelper; import com.google.devtools.build.lib.rules.cpp.CcLibraryHelper.Info; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.Variables.VariablesExtension; import com.google.devtools.build.lib.rules.cpp.CcToolchainProvider; import com.google.devtools.build.lib.rules.cpp.CppCompileAction; import com.google.devtools.build.lib.rules.cpp.CppConfiguration; import com.google.devtools.build.lib.rules.cpp.CppHelper; import com.google.devtools.build.lib.rules.cpp.CppLinkAction; import com.google.devtools.build.lib.rules.cpp.CppLinkActionBuilder; import com.google.devtools.build.lib.rules.cpp.CppRuleClasses; import com.google.devtools.build.lib.rules.cpp.FdoSupportProvider; import com.google.devtools.build.lib.rules.cpp.IncludeProcessing; import com.google.devtools.build.lib.rules.cpp.Link.LinkStaticness; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.rules.cpp.NoProcessing; import com.google.devtools.build.lib.rules.cpp.PrecompiledFiles; import com.google.devtools.build.lib.rules.objc.ObjcProvider.Flag; import com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.VariableCategory; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.Collection; import javax.annotation.Nullable; /** * Constructs command lines for objc compilation, archiving, and linking. Uses the crosstool * infrastructure to register {@link CppCompileAction} and {@link CppLinkAction} instances, making * use of a provided toolchain. * * <p>TODO(b/28403953): Deprecate LegacyCompilationSupport in favor of this implementation for all * objc rules. */ public class CrosstoolCompilationSupport extends CompilationSupport { private static final String OBJC_MODULE_FEATURE_NAME = "use_objc_modules"; private static final String NO_ENABLE_MODULES_FEATURE_NAME = "no_enable_modules"; private static final String DEAD_STRIP_FEATURE_NAME = "dead_strip"; private static final String RUN_COVERAGE_FEATURE_NAME = "run_coverage"; /** Produce artifacts for coverage in llvm coverage mapping format. */ private static final String LLVM_COVERAGE_MAP_FORMAT = "llvm_coverage_map_format"; /** Produce artifacts for coverage in gcc coverage mapping format. */ private static final String GCC_COVERAGE_MAP_FORMAT = "gcc_coverage_map_format"; /** * Enabled if this target's rule is not a test rule. Binary stripping should not be applied in * the link step. TODO(b/36562173): Replace this behavior with a condition on bundle creation. * * <p>Note that the crosstool does not support feature negation in FlagSet.with_feature, which * is the mechanism used to condition linker arguments here. Therefore, we expose * "is_not_test_target" instead of the more intuitive "is_test_target". */ private static final String IS_NOT_TEST_TARGET_FEATURE_NAME = "is_not_test_target"; /** Enabled if this target generates debug symbols in a dSYM file. */ private static final String GENERATE_DSYM_FILE_FEATURE_NAME = "generate_dsym_file"; /** * Enabled if this target does not generate debug symbols. * * <p>Note that the crosstool does not support feature negation in FlagSet.with_feature, which is * the mechanism used to condition linker arguments here. Therefore, we expose * "no_generate_debug_symbols" in addition to "generate_dsym_file" */ private static final String NO_GENERATE_DEBUG_SYMBOLS_FEATURE_NAME = "no_generate_debug_symbols"; private static final ImmutableList<String> ACTIVATED_ACTIONS = ImmutableList.of( "objc-compile", "objc++-compile", "objc-archive", "objc-fully-link", "objc-executable", "objc++-executable", "assemble", "preprocess-assemble", "c-compile", "c++-compile"); /** * Creates a new CompilationSupport instance that uses the c++ rule backend * * @param ruleContext the RuleContext for the calling target */ public CrosstoolCompilationSupport(RuleContext ruleContext) { this( ruleContext, ruleContext.getConfiguration(), ObjcRuleClasses.intermediateArtifacts(ruleContext), CompilationAttributes.Builder.fromRuleContext(ruleContext).build(), /*useDeps=*/true); } /** * Creates a new CompilationSupport instance that uses the c++ rule backend * * @param ruleContext the RuleContext for the calling target * @param buildConfiguration the configuration for the calling target * @param intermediateArtifacts IntermediateArtifacts for deriving artifact paths * @param compilationAttributes attributes of the calling target * @param useDeps true if deps should be used */ public CrosstoolCompilationSupport(RuleContext ruleContext, BuildConfiguration buildConfiguration, IntermediateArtifacts intermediateArtifacts, CompilationAttributes compilationAttributes, boolean useDeps) { super(ruleContext, buildConfiguration, intermediateArtifacts, compilationAttributes, useDeps); } @Override CompilationSupport registerCompileAndArchiveActions( CompilationArtifacts compilationArtifacts, ObjcProvider objcProvider, ExtraCompileArgs extraCompileArgs, Iterable<PathFragment> priorityHeaders, @Nullable CcToolchainProvider ccToolchain, @Nullable FdoSupportProvider fdoSupport) throws RuleErrorException, InterruptedException { Preconditions.checkNotNull(ccToolchain); Preconditions.checkNotNull(fdoSupport); ObjcVariablesExtension.Builder extension = new ObjcVariablesExtension.Builder() .setRuleContext(ruleContext) .setObjcProvider(objcProvider) .setCompilationArtifacts(compilationArtifacts) .setIntermediateArtifacts(intermediateArtifacts) .setConfiguration(buildConfiguration); CcLibraryHelper helper; if (compilationArtifacts.getArchive().isPresent()) { Artifact objList = intermediateArtifacts.archiveObjList(); // TODO(b/30783125): Signal the need for this action in the CROSSTOOL. registerObjFilelistAction(getObjFiles(compilationArtifacts, intermediateArtifacts), objList); extension.addVariableCategory(VariableCategory.ARCHIVE_VARIABLES); helper = createCcLibraryHelper( objcProvider, compilationArtifacts, extension.build(), ccToolchain, fdoSupport) .setLinkType(LinkTargetType.OBJC_ARCHIVE) .addLinkActionInput(objList); } else { helper = createCcLibraryHelper( objcProvider, compilationArtifacts, extension.build(), ccToolchain, fdoSupport); } registerHeaderScanningActions(helper.build(), objcProvider, compilationArtifacts); return this; } @Override protected CompilationSupport registerFullyLinkAction( ObjcProvider objcProvider, Iterable<Artifact> inputArtifacts, Artifact outputArchive, @Nullable CcToolchainProvider ccToolchain, @Nullable FdoSupportProvider fdoSupport) throws InterruptedException { Preconditions.checkNotNull(ccToolchain); Preconditions.checkNotNull(fdoSupport); PathFragment labelName = PathFragment.create(ruleContext.getLabel().getName()); String libraryIdentifier = ruleContext .getPackageDirectory() .getRelative(labelName.replaceName("lib" + labelName.getBaseName())) .getPathString(); ObjcVariablesExtension extension = new ObjcVariablesExtension.Builder() .setRuleContext(ruleContext) .setObjcProvider(objcProvider) .setConfiguration(buildConfiguration) .setIntermediateArtifacts(intermediateArtifacts) .setFullyLinkArchive(outputArchive) .addVariableCategory(VariableCategory.FULLY_LINK_VARIABLES) .build(); CppLinkAction fullyLinkAction = new CppLinkActionBuilder(ruleContext, outputArchive, ccToolchain, fdoSupport) .addActionInputs(objcProvider.getObjcLibraries()) .addActionInputs(objcProvider.getCcLibraries()) .addActionInputs(objcProvider.get(IMPORTED_LIBRARY).toSet()) .setCrosstoolInputs(ccToolchain.getLink()) .setLinkType(LinkTargetType.OBJC_FULLY_LINKED_ARCHIVE) .setLinkStaticness(LinkStaticness.FULLY_STATIC) .setLibraryIdentifier(libraryIdentifier) .addVariablesExtension(extension) .setFeatureConfiguration(getFeatureConfiguration(ruleContext, buildConfiguration)) .build(); ruleContext.registerAction(fullyLinkAction); return this; } private StrippingType getStrippingType(ExtraLinkArgs extraLinkArgs) { return Iterables.contains(extraLinkArgs, "-dynamiclib") ? StrippingType.DYNAMIC_LIB : StrippingType.DEFAULT; } @Override CompilationSupport registerLinkActions( ObjcProvider objcProvider, J2ObjcMappingFileProvider j2ObjcMappingFileProvider, J2ObjcEntryClassProvider j2ObjcEntryClassProvider, ExtraLinkArgs extraLinkArgs, Iterable<Artifact> extraLinkInputs, DsymOutputType dsymOutputType, CcToolchainProvider toolchain) throws InterruptedException { Iterable<Artifact> prunedJ2ObjcArchives = computeAndStripPrunedJ2ObjcArchives( j2ObjcEntryClassProvider, j2ObjcMappingFileProvider, objcProvider); ImmutableList<Artifact> bazelBuiltLibraries = Iterables.isEmpty(prunedJ2ObjcArchives) ? objcProvider.getObjcLibraries() : substituteJ2ObjcPrunedLibraries(objcProvider); Artifact inputFileList = intermediateArtifacts.linkerObjList(); ImmutableSet<Artifact> forceLinkArtifacts = getForceLoadArtifacts(objcProvider); Iterable<Artifact> objFiles = Iterables.concat( bazelBuiltLibraries, objcProvider.get(IMPORTED_LIBRARY), objcProvider.getCcLibraries()); // Clang loads archives specified in filelists and also specified as -force_load twice, // resulting in duplicate symbol errors unless they are deduped. objFiles = Iterables.filter(objFiles, Predicates.not(Predicates.in(forceLinkArtifacts))); registerObjFilelistAction(objFiles, inputFileList); LinkTargetType linkType = (objcProvider.is(Flag.USES_CPP)) ? LinkTargetType.OBJCPP_EXECUTABLE : LinkTargetType.OBJC_EXECUTABLE; ObjcVariablesExtension.Builder extensionBuilder = new ObjcVariablesExtension.Builder() .setRuleContext(ruleContext) .setObjcProvider(objcProvider) .setConfiguration(buildConfiguration) .setIntermediateArtifacts(intermediateArtifacts) .setFrameworkNames(frameworkNames(objcProvider)) .setLibraryNames(libraryNames(objcProvider)) .setForceLoadArtifacts(getForceLoadArtifacts(objcProvider)) .setAttributeLinkopts(attributes.linkopts()) .addVariableCategory(VariableCategory.EXECUTABLE_LINKING_VARIABLES); Artifact binaryToLink = getBinaryToLink(); FdoSupportProvider fdoSupport = CppHelper.getFdoSupport(ruleContext, ":cc_toolchain"); CppLinkActionBuilder executableLinkAction = new CppLinkActionBuilder(ruleContext, binaryToLink, toolchain, fdoSupport) .setMnemonic("ObjcLink") .addActionInputs(bazelBuiltLibraries) .addActionInputs(objcProvider.getCcLibraries()) .addTransitiveActionInputs(objcProvider.get(IMPORTED_LIBRARY)) .addTransitiveActionInputs(objcProvider.get(STATIC_FRAMEWORK_FILE)) .addTransitiveActionInputs(objcProvider.get(DYNAMIC_FRAMEWORK_FILE)) .setCrosstoolInputs(toolchain.getLink()) .addActionInputs(prunedJ2ObjcArchives) .addActionInput(inputFileList) .setLinkType(linkType) .setLinkStaticness(LinkStaticness.FULLY_STATIC) .addLinkopts(ImmutableList.copyOf(extraLinkArgs)) .setFeatureConfiguration(getFeatureConfiguration(ruleContext, buildConfiguration)); if (objcConfiguration.generateDsym()) { Artifact dsymBundleZip = intermediateArtifacts.tempDsymBundleZip(dsymOutputType); extensionBuilder .setDsymBundleZip(dsymBundleZip) .addVariableCategory(VariableCategory.DSYM_VARIABLES) .setDsymOutputType(dsymOutputType); registerDsymActions(dsymOutputType); executableLinkAction.addActionOutput(dsymBundleZip); } executableLinkAction.addVariablesExtension(extensionBuilder.build()); ruleContext.registerAction(executableLinkAction.build()); if (objcConfiguration.shouldStripBinary()) { registerBinaryStripAction(binaryToLink, getStrippingType(extraLinkArgs)); } return this; } private IncludeProcessing createIncludeProcessing( Iterable<Artifact> privateHdrs, ObjcProvider objcProvider, @Nullable Artifact pchHdr) { if (isHeaderThinningEnabled()) { Iterable<Artifact> potentialInputs = Iterables.concat( privateHdrs, objcProvider.get(HEADER), objcProvider.get(STATIC_FRAMEWORK_FILE), objcProvider.get(DYNAMIC_FRAMEWORK_FILE)); if (pchHdr != null) { potentialInputs = Iterables.concat(potentialInputs, ImmutableList.of(pchHdr)); } return new HeaderThinning(potentialInputs); } else { return new NoProcessing(); } } private CcLibraryHelper createCcLibraryHelper( ObjcProvider objcProvider, CompilationArtifacts compilationArtifacts, VariablesExtension extension, CcToolchainProvider ccToolchain, FdoSupportProvider fdoSupport) { PrecompiledFiles precompiledFiles = new PrecompiledFiles(ruleContext); Collection<Artifact> arcSources = ImmutableSortedSet.copyOf(compilationArtifacts.getSrcs()); Collection<Artifact> nonArcSources = ImmutableSortedSet.copyOf(compilationArtifacts.getNonArcSrcs()); Collection<Artifact> privateHdrs = ImmutableSortedSet.copyOf(compilationArtifacts.getPrivateHdrs()); Collection<Artifact> publicHdrs = ImmutableSortedSet.copyOf(attributes.hdrs()); Artifact pchHdr = null; if (ruleContext.attributes().has("pch", BuildType.LABEL)) { pchHdr = ruleContext.getPrerequisiteArtifact("pch", Mode.TARGET); } ObjcCppSemantics semantics = new ObjcCppSemantics( objcProvider, createIncludeProcessing(privateHdrs, objcProvider, pchHdr), ruleContext.getFragment(ObjcConfiguration.class), isHeaderThinningEnabled(), intermediateArtifacts); CcLibraryHelper result = new CcLibraryHelper( ruleContext, semantics, getFeatureConfiguration(ruleContext, buildConfiguration), CcLibraryHelper.SourceCategory.CC_AND_OBJC, ccToolchain, fdoSupport, buildConfiguration) .addSources(arcSources, ImmutableMap.of("objc_arc", "")) .addSources(nonArcSources, ImmutableMap.of("no_objc_arc", "")) .addSources(privateHdrs) .addDefines(objcProvider.get(DEFINE)) .enableCompileProviders() .addPublicHeaders(publicHdrs) .addPrecompiledFiles(precompiledFiles) .addDeps(ruleContext.getPrerequisites("deps", Mode.TARGET)) // Not all our dependencies need to export cpp information. // For example, objc_proto_library can depend on a proto_library rule that does not // generate C++ protos. .setCheckDepsGenerateCpp(false) .addCopts(getCompileRuleCopts()) .addIncludeDirs(objcProvider.get(INCLUDE)) .addCopts(ruleContext.getFragment(ObjcConfiguration.class).getCoptsForCompilationMode()) .addSystemIncludeDirs(objcProvider.get(INCLUDE_SYSTEM)) .setCppModuleMap(intermediateArtifacts.moduleMap()) .setLinkedArtifactNameSuffix(intermediateArtifacts.archiveFileNameSuffix()) .setPropagateModuleMapToCompileAction(false) .setNeverLink(true) .addVariableExtension(extension); if (pchHdr != null) { result.addNonModuleMapHeader(pchHdr); } if (!useDeps) { result.doNotUseDeps(); } return result; } private static FeatureConfiguration getFeatureConfiguration(RuleContext ruleContext, BuildConfiguration configuration) { ImmutableList.Builder<String> activatedCrosstoolSelectables = ImmutableList.<String>builder() .addAll(ACTIVATED_ACTIONS) .addAll( ruleContext .getFragment(AppleConfiguration.class) .getBitcodeMode() .getFeatureNames()) // We create a module map by default to allow for Swift interop. .add(CppRuleClasses.MODULE_MAPS) .add(CppRuleClasses.COMPILE_ALL_MODULES) .add(CppRuleClasses.EXCLUDE_PRIVATE_HEADERS_IN_MODULE_MAPS) .add(CppRuleClasses.ONLY_DOTH_HEADERS_IN_MODULE_MAPS) .add(CppRuleClasses.COMPILE_ACTION_FLAGS_IN_FLAG_SET) .add(CppRuleClasses.DEPENDENCY_FILE) .add(CppRuleClasses.INCLUDE_PATHS) .add(configuration.getCompilationMode().toString()); if (configuration.getFragment(ObjcConfiguration.class).moduleMapsEnabled()) { activatedCrosstoolSelectables.add(OBJC_MODULE_FEATURE_NAME); } if (!CompilationAttributes.Builder.fromRuleContext(ruleContext).build().enableModules()) { activatedCrosstoolSelectables.add(NO_ENABLE_MODULES_FEATURE_NAME); } if (configuration.getFragment(ObjcConfiguration.class).shouldStripBinary()) { activatedCrosstoolSelectables.add(DEAD_STRIP_FEATURE_NAME); } if (ruleContext.attributes().has("pch", BuildType.LABEL) && ruleContext.getPrerequisiteArtifact("pch", Mode.TARGET) != null) { activatedCrosstoolSelectables.add("pch"); } if (configuration.isCodeCoverageEnabled()) { activatedCrosstoolSelectables.add(RUN_COVERAGE_FEATURE_NAME); } if (configuration.isLLVMCoverageMapFormatEnabled()) { activatedCrosstoolSelectables.add(LLVM_COVERAGE_MAP_FORMAT); } else { activatedCrosstoolSelectables.add(GCC_COVERAGE_MAP_FORMAT); } if (!TargetUtils.isTestRule(ruleContext.getRule())) { activatedCrosstoolSelectables.add(IS_NOT_TEST_TARGET_FEATURE_NAME); } if (configuration.getFragment(ObjcConfiguration.class).generateDsym()) { activatedCrosstoolSelectables.add(GENERATE_DSYM_FILE_FEATURE_NAME); } else { activatedCrosstoolSelectables.add(NO_GENERATE_DEBUG_SYMBOLS_FEATURE_NAME); } activatedCrosstoolSelectables.addAll(ruleContext.getFeatures()); return configuration .getFragment(CppConfiguration.class) .getFeatures() .getFeatureConfiguration(activatedCrosstoolSelectables.build()); } private static ImmutableList<Artifact> getObjFiles( CompilationArtifacts compilationArtifacts, IntermediateArtifacts intermediateArtifacts) { ImmutableList.Builder<Artifact> result = new ImmutableList.Builder<>(); for (Artifact sourceFile : compilationArtifacts.getSrcs()) { result.add(intermediateArtifacts.objFile(sourceFile)); } for (Artifact nonArcSourceFile : compilationArtifacts.getNonArcSrcs()) { result.add(intermediateArtifacts.objFile(nonArcSourceFile)); } return result.build(); } private void registerHeaderScanningActions( Info info, ObjcProvider objcProvider, CompilationArtifacts compilationArtifacts) { // PIC is not used for Obj-C builds, if that changes this method will need to change if (!isHeaderThinningEnabled() || info.getCcCompilationOutputs().getObjectFiles(false).isEmpty()) { return; } ImmutableList.Builder<ObjcHeaderThinningInfo> headerThinningInfos = ImmutableList.builder(); AnalysisEnvironment analysisEnvironment = ruleContext.getAnalysisEnvironment(); for (Artifact objectFile : info.getCcCompilationOutputs().getObjectFiles(false)) { ActionAnalysisMetadata generatingAction = analysisEnvironment.getLocalGeneratingAction(objectFile); if (generatingAction instanceof CppCompileAction) { CppCompileAction action = (CppCompileAction) generatingAction; Artifact sourceFile = action.getSourceFile(); if (!sourceFile.isTreeArtifact() && SOURCES_FOR_HEADER_THINNING.matches(sourceFile.getFilename())) { headerThinningInfos.add( new ObjcHeaderThinningInfo( sourceFile, intermediateArtifacts.headersListFile(sourceFile), action.getCompilerOptions())); } } } registerHeaderScanningActions(headerThinningInfos.build(), objcProvider, compilationArtifacts); } }
Bundle loader is passed to link actions for ios_test using --experimental_objc_crosstool=all PiperOrigin-RevId: 152254287
src/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java
Bundle loader is passed to link actions for ios_test using --experimental_objc_crosstool=all
<ide><path>rc/main/java/com/google/devtools/build/lib/rules/objc/CrosstoolCompilationSupport.java <ide> .addTransitiveActionInputs(objcProvider.get(DYNAMIC_FRAMEWORK_FILE)) <ide> .setCrosstoolInputs(toolchain.getLink()) <ide> .addActionInputs(prunedJ2ObjcArchives) <add> .addActionInputs(extraLinkInputs) <ide> .addActionInput(inputFileList) <ide> .setLinkType(linkType) <ide> .setLinkStaticness(LinkStaticness.FULLY_STATIC)
Java
mit
c9b8a9025ca4bdcf3ff8795ef33a6c542ae6df7d
0
DTAFormation/ecommerce-backend,DTAFormation/ecommerce-backend-aout-2015,DTAFormation/ecommerce-backend-aout-2015,DTAFormation/ecommerce-backend
package dta.commerce.rest; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import dta.commerce.ejb.ICommandeEJB; import dta.commerce.ejb.IUserEJB; import dta.commerce.persistance.Adresse; import dta.commerce.persistance.CommandeClient; import dta.commerce.persistance.User; import dta.commerce.service.IEmailService; @Path("/user") public class UserRessource { @EJB IUserEJB myEJB; @EJB ICommandeEJB commmandeEjb; @EJB IEmailService email; // ****** AJOUTER USER ****** @POST @Consumes(MediaType.APPLICATION_JSON) public Response addUser(User user) { myEJB.addUser(user); ResponseBuilder builder = Response.ok(); builder.status(201); return builder.build(); } // ****** MODIFIER USER ****** @PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateUser(User user) { myEJB.updateUser(user); ResponseBuilder builder = Response.ok(); builder.status(200); return builder.build(); } // ****** SUPPRIMER USER ****** @DELETE @Path("/{id}") public Response deleteUser(@PathParam(value = "id") Integer user) { myEJB.deleteUser(user); ResponseBuilder builder = Response.ok(); builder.status(200); return builder.build(); } // ****** ADD USER ****** @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getUser(@PathParam(value = "id") Integer user) { User myUser = new User(); myUser = myEJB.getUser(user); ResponseBuilder builder = Response.ok(myUser); builder.status(200); return builder.build(); } // ****** LISTER USER ****** @GET @Produces(MediaType.APPLICATION_JSON) public Response getUser() { List<User> myUsers= new ArrayList<User>(); myUsers = myEJB.listerUser(); ResponseBuilder builder = Response.ok(myUsers); builder.status(200); return builder.build(); } // ****** CONNECTER USER ****** @POST @Path("/connect") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response connectUser(User data){ System.out.println(data.getLogin()); User user=myEJB.getInfosUser(data.getLogin(), data.getPassword()); user.setPassword(""); //user.setId(null); ResponseBuilder builder = Response.ok(user); return builder.build(); } // ****** TROUVER LOGIN USER ****** @GET @Path("/chercher/{login}/") public Response connectUser(@PathParam(value = "login") String login){ for (User user : myEJB.listerUser()) { if (login.equals(user.getLogin())){ ResponseBuilder builderOK = Response.status(200); return builderOK.build(); } } ResponseBuilder builderOK = Response.status(405); return builderOK.build(); } // ****** AJOUTER NOUVELLES ADRESSES DANS UN USER ****** @POST @Path("/{id}/adresses/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response addAdresses(List<Adresse> adresses){ myEJB.addAdressesUser(adresses); ResponseBuilder builder = Response.ok(); builder.status(201); return builder.build(); } @GET @Path("/{idClient}/commandes") @Produces(MediaType.APPLICATION_JSON) public Response getClientCommandes(@PathParam("idClient") Integer idClient) { List<CommandeClient> listCde; listCde = commmandeEjb.listerCommandeClient(idClient); ResponseBuilder builder= Response.ok(listCde); return builder.build(); } @GET @Path("/{idClient}/commande/{idCommande}") @Produces(MediaType.APPLICATION_JSON) public Response getCommandbyID(@PathParam("idClient") Integer idClient, @PathParam("idCommande") Integer idCommande) { ResponseBuilder builder= Response.ok(""); CommandeClient commandeCli; commandeCli = commmandeEjb.editCommandClient(idCommande); builder.status(200); builder = Response.ok(commandeCli); return builder.build(); } @POST @Path("/{idClient}/commande") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createCommand(@PathParam("idClient") Integer idClient, CommandeClient commandeClient) { commandeClient.setClient(myEJB.getUser(idClient)); // Commande en cours à la création commandeClient.setEtat("EC"); commandeClient.getCommandeProduits().stream().forEach(commandeProduit -> { commandeProduit.setCommandeClient(commandeClient); }); commmandeEjb.createCommandeClient(commandeClient); email.envoiEmailSmtp(commandeClient); return Response.status(Response.Status.CREATED).entity(commandeClient).build(); } @PUT @Path("/{idClient}/commande") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateCommande(@PathParam("idClient") Integer idClient, CommandeClient commandeClient) { System.out.println("mise à jour de la commande du client " + idClient); commmandeEjb.updateCommandeClient(commandeClient); return Response.status(Response.Status.CREATED).entity(commandeClient).build(); } @DELETE @Path("/{idClient}/commande/{idCommande}") @Produces(MediaType.APPLICATION_JSON) public Response deleteCommandbyID(@PathParam("idClient") Integer idClient, @PathParam("idCommande") Integer idCommande ) { ResponseBuilder builder= Response.ok(""); System.out.println("suppression de la commande du client " + idClient); commmandeEjb.deleteCommandeClient(idCommande); builder.status(200); return builder.build(); } }
src/main/java/dta/commerce/rest/UserRessource.java
package dta.commerce.rest; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import dta.commerce.ejb.ICommandeEJB; import dta.commerce.ejb.IUserEJB; import dta.commerce.persistance.Adresse; import dta.commerce.persistance.CommandeClient; import dta.commerce.persistance.User; import dta.commerce.service.IEmailService; @Path("/user") public class UserRessource { @EJB IUserEJB myEJB; @EJB ICommandeEJB commmandeEjb; @EJB IEmailService email; // ****** AJOUTER USER ****** @POST @Consumes(MediaType.APPLICATION_JSON) public Response addUser(User user) { myEJB.addUser(user); ResponseBuilder builder = Response.ok(); builder.status(201); return builder.build(); } // ****** MODIFIER USER ****** @PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateUser(User user) { myEJB.updateUser(user); ResponseBuilder builder = Response.ok(); builder.status(200); return builder.build(); } // ****** SUPPRIMER USER ****** @DELETE @Path("/{id}") public Response deleteUser(@PathParam(value = "id") Integer user) { myEJB.deleteUser(user); ResponseBuilder builder = Response.ok(); builder.status(200); return builder.build(); } // ****** ADD USER ****** @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getUser(@PathParam(value = "id") Integer user) { User myUser = new User(); myUser = myEJB.getUser(user); ResponseBuilder builder = Response.ok(myUser); builder.status(200); return builder.build(); } // ****** LISTER USER ****** @GET @Produces(MediaType.APPLICATION_JSON) public Response getUser() { List<User> myUsers= new ArrayList<User>(); myUsers = myEJB.listerUser(); ResponseBuilder builder = Response.ok(myUsers); builder.status(200); return builder.build(); } // ****** CONNECTER USER ****** @POST @Path("/connect") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response connectUser(User data){ System.out.println(data.getLogin()); User user=myEJB.getInfosUser(data.getLogin(), data.getPassword()); user.setPassword(""); //user.setId(null); ResponseBuilder builder = Response.ok(user); return builder.build(); } // ****** TROUVER LOGIN USER ****** @GET @Path("/chercher/{login}/") public Response connectUser(@PathParam(value = "login") String login){ for (User user : myEJB.listerUser()) { if (login.equals(user.getLogin())){ ResponseBuilder builderOK = Response.status(200); return builderOK.build(); } } ResponseBuilder builderOK = Response.status(405); return builderOK.build(); } // ****** AJOUTER NOUVELLES ADRESSES DANS UN USER ****** @POST @Path("/{id}/adresses/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response addAdresses(List<Adresse> adresses){ myEJB.addAdressesUser(adresses); ResponseBuilder builder = Response.ok(); builder.status(201); return builder.build(); } @GET @Path("/{idClient}/commandes") @Produces(MediaType.APPLICATION_JSON) public Response getClientCommandes(@PathParam("idClient") Integer idClient) { List<CommandeClient> listCde; listCde = commmandeEjb.listerCommandeClient(idClient); ResponseBuilder builder= Response.ok(listCde); return builder.build(); } @GET @Path("/{idClient}/commande/{idCommande}") @Produces(MediaType.APPLICATION_JSON) public Response getCommandbyID(@PathParam("idClient") Integer idClient, @PathParam("idCommande") Integer idCommande) { ResponseBuilder builder= Response.ok(""); CommandeClient commandeCli; commandeCli = commmandeEjb.editCommandClient(idCommande); builder.status(200); builder = Response.ok(commandeCli); return builder.build(); } @POST @Path("/{idClient}/commande") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createCommand(@PathParam("idClient") Integer idClient, CommandeClient commandeClient) { commandeClient.setClient(myEJB.getUser(idClient)); // Commande en cours à la création commandeClient.setEtat("EC"); commmandeEjb.createCommandeClient(commandeClient); email.envoiEmailSmtp(commandeClient); return Response.status(Response.Status.CREATED).entity(commandeClient).build(); } @PUT @Path("/{idClient}/commande") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateCommande(@PathParam("idClient") Integer idClient, CommandeClient commandeClient) { System.out.println("mise à jour de la commande du client " + idClient); commmandeEjb.updateCommandeClient(commandeClient); return Response.status(Response.Status.CREATED).entity(commandeClient).build(); } @DELETE @Path("/{idClient}/commande/{idCommande}") @Produces(MediaType.APPLICATION_JSON) public Response deleteCommandbyID(@PathParam("idClient") Integer idClient, @PathParam("idCommande") Integer idCommande ) { ResponseBuilder builder= Response.ok(""); System.out.println("suppression de la commande du client " + idClient); commmandeEjb.deleteCommandeClient(idCommande); builder.status(200); return builder.build(); } }
Création commande : sauvegarde des produits dans les commandes produit
src/main/java/dta/commerce/rest/UserRessource.java
Création commande : sauvegarde des produits dans les commandes produit
<ide><path>rc/main/java/dta/commerce/rest/UserRessource.java <ide> // Commande en cours à la création <ide> commandeClient.setEtat("EC"); <ide> <add> commandeClient.getCommandeProduits().stream().forEach(commandeProduit -> { <add> commandeProduit.setCommandeClient(commandeClient); <add> }); <add> <ide> commmandeEjb.createCommandeClient(commandeClient); <ide> email.envoiEmailSmtp(commandeClient); <ide> return Response.status(Response.Status.CREATED).entity(commandeClient).build();
JavaScript
mit
7252da2814af48c6421422dbf03d19b3a59dcfff
0
depjs/dep
module.exports = (list, key, value, walk) => { let i = 0 let depth = 1 let ref = {} // optimize the shallowness as much as possible // @ToDo should check the version as well while (i < walk.length) { if (!list[walk[i]]) { i = 2 * depth depth++ } else { ref = list[walk[i]] i++ } } if (!ref.dependencies) ref.dependencies = {} ref.dependencies[key] = value }
lib/utils/deeper.js
module.exports = (list, key, value, walk) => { let i = 0 let depth = 1 let ref = {} // optimize the shallowness as much as possible while (i < walk.length) { if (!list[walk[i]]) { i = 2 * depth depth++ } else { ref = list[walk[i]] i++ } } if (!ref.dependencies) ref.dependencies = {} ref.dependencies[key] = value }
add ToDo comment
lib/utils/deeper.js
add ToDo comment
<ide><path>ib/utils/deeper.js <ide> let depth = 1 <ide> let ref = {} <ide> // optimize the shallowness as much as possible <add> // @ToDo should check the version as well <ide> while (i < walk.length) { <ide> if (!list[walk[i]]) { <ide> i = 2 * depth
Java
apache-2.0
error: pathspec 'src/web/onClient/hr/fer/zemris/vhdllab/applets/schema/ComponentPropertyList.java' did not match any file(s) known to git
e21e43f32b601c0d63694a7394505494bda0791a
1
mbezjak/vhdllab,mbezjak/vhdllab,mbezjak/vhdllab
package hr.fer.zemris.vhdllab.applets.schema; /** * Objekt koji vraca svaka komponenta * a koji sadrzi sva svojstva dane * komponente. * @author Axel * */ public class ComponentPropertyList { }
src/web/onClient/hr/fer/zemris/vhdllab/applets/schema/ComponentPropertyList.java
Ovo je objekt koji vraca komponenta pozivom getPropertyList. U ovom trenutku ne sadrzi jos nista, jer nije jos sasvim jasno kako ga implementirati. git-svn-id: 650ffc0a3ae286c3f0a198ebc7b4f99e37498f62@112 cbae1e92-611c-0410-ab7b-b19ac7dee622
src/web/onClient/hr/fer/zemris/vhdllab/applets/schema/ComponentPropertyList.java
Ovo je objekt koji vraca komponenta pozivom getPropertyList. U ovom trenutku ne sadrzi jos nista, jer nije jos sasvim jasno kako ga implementirati.
<ide><path>rc/web/onClient/hr/fer/zemris/vhdllab/applets/schema/ComponentPropertyList.java <add>package hr.fer.zemris.vhdllab.applets.schema; <add> <add>/** <add> * Objekt koji vraca svaka komponenta <add> * a koji sadrzi sva svojstva dane <add> * komponente. <add> * @author Axel <add> * <add> */ <add>public class ComponentPropertyList { <add>}
Java
apache-2.0
6e394c0b377ee6c2d9dd551e349b92ce8ba5aabb
0
dimagi/javarosa,dimagi/javarosa,dimagi/javarosa
/** * */ package org.javarosa.formmanager.api; import java.util.Vector; import javax.microedition.lcdui.Canvas; import javax.microedition.media.MediaException; import javax.microedition.media.Player; import javax.microedition.media.PlayerListener; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.reference.Reference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.UnavailableServiceException; import org.javarosa.core.services.locale.Localization; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.formmanager.api.transitions.FormEntryTransitions; import org.javarosa.formmanager.properties.FormManagerProperties; import org.javarosa.formmanager.view.IFormEntryView; import org.javarosa.utilities.media.MediaUtils; /** * Extension of {@link FormEntryController} for J2ME. * * @author ctsims * */ public class JrFormEntryController extends FormEntryController implements FormMultimediaController { FormEntryTransitions transitions; IFormEntryView view; boolean quickEntry = true; boolean isMinimal = false; private static Reference curAudRef = null; private static String curAudioURI; protected static boolean playAudioIfAvailable = true; private static int POUND_KEYCODE = Canvas.KEY_POUND; private PlayerListener logHandler; /** Causes audio player to throw runtime exceptions if there are problems instead of failing silently **/ private boolean audioFailFast = true; String extraKeyMode; public JrFormEntryController(JrFormEntryModel model) { this(model, FormManagerProperties.EXTRA_KEY_LANGUAGE_CYCLE, false, true); } public JrFormEntryController(JrFormEntryModel model, String extraKeyMode, boolean audioFailFast, boolean quickEntry){ this(model, extraKeyMode, audioFailFast, quickEntry, false); } public JrFormEntryController(JrFormEntryModel model, String extraKeyMode, boolean audioFailFast, boolean quickEntry, boolean isMinimal) { super(model); tryToInitDefaultLanguage(model); this.extraKeyMode = extraKeyMode; this.audioFailFast = audioFailFast; this.quickEntry = quickEntry; this.isMinimal = isMinimal; this.logHandler = new PlayerListener() { public void playerUpdate(Player player, String event, Object eventData) { Logger.log("jls", "in playerUpdate"); String action = ""; if (event == PlayerListener.STARTED) { action = "start"; } else if (event == PlayerListener.STOPPED) { action = "pause"; } else if (event == PlayerListener.END_OF_MEDIA) { action = "stop"; } Logger.log("jls", "action = " + action); FormEntryPrompt fep = JrFormEntryController.this.getModel().getQuestionPrompt(); try { if (fep != null && fep.getAudioText() != null) { // log that action was attempted on audio file // TODO: move this to some sort of 'form entry diagnostics' framework // instead of bloating the logs String audio = fep.getAudioText(); Logger.log("jls", "audio = " + audio); //extract just the audio filename to reduce log size String audioShort; try { Vector<String> pieces = DateUtils.split(audio, "/", false); String filename = pieces.lastElement(); int suffixIx = filename.lastIndexOf('.'); audioShort = (suffixIx != -1 ? filename.substring(0, suffixIx) : filename); } catch (Exception e) { audioShort = audio; } Logger.log("audio", action + " " + audioShort); } else { Logger.log("jls", "Something was null: " + fep + " or " + fep.getAudioText()); } } catch(Exception e) { //Nothing } } }; //#if device.identifier == Sony-Ericsson/K610i POUND_KEYCODE = Canvas.KEY_STAR; //#endif } private void tryToInitDefaultLanguage(JrFormEntryModel model) { //Try to set the current form locale based on the current app locale String[] languages = model.getLanguages(); if(languages != null) { String locale = Localization.getGlobalLocalizerAdvanced().getLocale(); if(locale != null) { for(String language : languages) { if(locale.equals(language)) { model.getForm().getLocalizer().setLocale(locale); break; } } } } } public JrFormEntryModel getModel () { return (JrFormEntryModel)super.getModel(); } public void setView(IFormEntryView view) { this.view = view; view.attachFormMediaController(this); } public IFormEntryView getView(){ return this.view; } public void setTransitions(FormEntryTransitions transitions) { this.transitions = transitions; } /** * Handles the given key event, and returns a flag signifying whether * the interface should continue trying to handle the event. * * @param key The key that was pressed * @return true if the ui should stop handling this event. False if it * is ok to continue processing it. */ public boolean handleKeyEvent(int key) { if(getModel().getForm().getLocalizer() != null && key == POUND_KEYCODE && !FormManagerProperties.EXTRA_KEY_AUDIO_PLAYBACK.equals(getExtraKeyMode())) { cycleLanguage(); return true; } else if(FormManagerProperties.EXTRA_KEY_AUDIO_PLAYBACK.equals(getExtraKeyMode()) && key == POUND_KEYCODE){ //For now, we'll assume that video playback basically trumps audio playback. //TODO: Add a way to play videos when extra-key isn't set to audio if(player != null) { try { if(player.getState() == Player.STARTED) { player.stop(); } else { player.start(); } } catch (MediaException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } if(this.getModel().getEvent() != FormEntryController.EVENT_QUESTION) {return false;} playAudioOnDemand(this.getModel().getQuestionPrompt()); //We can keep processing this. Audio plays in the background. return false; } return false; } public void start() { view.show(); } /** * Start from a specific index * @param index */ public void start(FormIndex index){ view.show(index); } public void abort() { view.destroy(); transitions.abort(); } public void saveAndExit(boolean formComplete) { if (formComplete){ this.getModel().getForm().postProcessInstance(); } view.destroy(); transitions.formEntrySaved(this.getModel().getForm(),this.getModel().getForm().getInstance(),formComplete); } public void suspendActivity(int mediaType) throws UnavailableServiceException { view.destroy(); transitions.suspendForMediaCapture(mediaType); } public void cycleLanguage () { setLanguage(getModel().getForm().getLocalizer().getNextLocale()); } public String getExtraKeyMode() { return extraKeyMode; } //// New Audio Stuff follows below. I've tried to set it up so that we can split this out into a seperate "view" //// if you will at a later point. /** * Checks the boolean playAudioIfAvailable first. * Plays the question audio text */ public void playAudioOnLoad(FormEntryPrompt fep){ //If the current session is expecting audio playback w/the extrakey, don't //play it passively, wait for the button to be pressed. if(!FormManagerProperties.EXTRA_KEY_AUDIO_PLAYBACK.equals(extraKeyMode)) { playAudio(fep,null); } } /** * Checks the boolean playAudioIfAvailable first. * Plays the question audio text */ public void playAudioOnDemand(FormEntryPrompt fep){ playAudio(fep,null); } public int playAudioOnDemand(FormEntryPrompt fep,SelectChoice select) { return playAudio(fep, select); } /** * Plays audio for the SelectChoice (if AudioURI is present and media is available) * @param fep * @param select * @return */ public int playAudio(FormEntryPrompt fep,SelectChoice select){ if (!playAudioIfAvailable) return MediaUtils.AUDIO_DISABLED; String textID; curAudioURI = null; String tag = null; if (select == null) { if (fep.getAudioText() != null) { curAudioURI = fep.getAudioText(); tag = "#"; } else { return MediaUtils.AUDIO_NO_RESOURCE; } }else{ textID = select.getTextID(); if(textID == null || textID == "") return MediaUtils.AUDIO_NO_RESOURCE; if (fep.getSpecialFormSelectChoiceText(select, FormEntryCaption.TEXT_FORM_AUDIO) != null) { curAudioURI = fep.getSpecialFormSelectChoiceText(select, FormEntryCaption.TEXT_FORM_AUDIO); tag = String.valueOf(select.getIndex()); } else { return MediaUtils.AUDIO_NO_RESOURCE; } } //No idea why this is a member variable... return MediaUtils.playOrPauseAudio(curAudioURI, tag); } public boolean isEntryOptimized() { return quickEntry; } //A video player being controlled by this controller Player player; /* * (non-Javadoc) * @see org.javarosa.formmanager.api.FormMultimediaController#attachVideoPlayer(javax.microedition.media.Player) */ public void attachVideoPlayer(Player player) { //NOTE: Not thread safe if(this.player != null) { detachVideoPlayer(player); } this.player = player; this.player.removePlayerListener(logHandler); this.player.addPlayerListener(logHandler); } /* * (non-Javadoc) * @see org.javarosa.formmanager.api.FormMultimediaController#detachVideoPlayer(javax.microedition.media.Player) */ public void detachVideoPlayer(Player player) { if(this.player == player) { this.player = null; } } public void stopAudio() { MediaUtils.stopAudio(); } public void setMinimal(boolean isMinimal){ this.isMinimal = isMinimal; } public boolean isMinimal(){ return this.isMinimal; } }
j2me/form-entry/src/org/javarosa/formmanager/api/JrFormEntryController.java
/** * */ package org.javarosa.formmanager.api; import java.util.Vector; import javax.microedition.lcdui.Canvas; import javax.microedition.media.MediaException; import javax.microedition.media.Player; import javax.microedition.media.PlayerListener; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.reference.Reference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.UnavailableServiceException; import org.javarosa.core.services.locale.Localization; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.formmanager.api.transitions.FormEntryTransitions; import org.javarosa.formmanager.properties.FormManagerProperties; import org.javarosa.formmanager.view.IFormEntryView; import org.javarosa.utilities.media.MediaUtils; /** * Extension of {@link FormEntryController} for J2ME. * * @author ctsims * */ public class JrFormEntryController extends FormEntryController implements FormMultimediaController { FormEntryTransitions transitions; IFormEntryView view; boolean quickEntry = true; boolean isMinimal = false; private static Reference curAudRef = null; private static String curAudioURI; protected static boolean playAudioIfAvailable = true; private static int POUND_KEYCODE = Canvas.KEY_POUND; private PlayerListener logHandler; /** Causes audio player to throw runtime exceptions if there are problems instead of failing silently **/ private boolean audioFailFast = true; String extraKeyMode; public JrFormEntryController(JrFormEntryModel model) { this(model, FormManagerProperties.EXTRA_KEY_LANGUAGE_CYCLE, false, true); } public JrFormEntryController(JrFormEntryModel model, String extraKeyMode, boolean audioFailFast, boolean quickEntry){ this(model, extraKeyMode, audioFailFast, quickEntry, false); } public JrFormEntryController(JrFormEntryModel model, String extraKeyMode, boolean audioFailFast, boolean quickEntry, boolean isMinimal) { super(model); tryToInitDefaultLanguage(model); this.extraKeyMode = extraKeyMode; this.audioFailFast = audioFailFast; this.quickEntry = quickEntry; this.isMinimal = isMinimal; this.logHandler = new PlayerListener() { public void playerUpdate(Player player, String event, Object eventData) { String action = ""; if (event == PlayerListener.STARTED) { action = "start"; } else if (event == PlayerListener.STOPPED) { action = "pause"; } else if (event == PlayerListener.END_OF_MEDIA) { action = "stop"; } FormEntryPrompt fep = JrFormEntryController.this.getModel().getQuestionPrompt(); try { if (fep != null && fep.getAudioText() != null) { // log that action was attempted on audio file // TODO: move this to some sort of 'form entry diagnostics' framework // instead of bloating the logs String audio = fep.getAudioText(); //extract just the audio filename to reduce log size String audioShort; try { Vector<String> pieces = DateUtils.split(audio, "/", false); String filename = pieces.lastElement(); int suffixIx = filename.lastIndexOf('.'); audioShort = (suffixIx != -1 ? filename.substring(0, suffixIx) : filename); } catch (Exception e) { audioShort = audio; } Logger.log("audio", action + " " + audioShort); } } catch(Exception e) { //Nothing } } }; //#if device.identifier == Sony-Ericsson/K610i POUND_KEYCODE = Canvas.KEY_STAR; //#endif } private void tryToInitDefaultLanguage(JrFormEntryModel model) { //Try to set the current form locale based on the current app locale String[] languages = model.getLanguages(); if(languages != null) { String locale = Localization.getGlobalLocalizerAdvanced().getLocale(); if(locale != null) { for(String language : languages) { if(locale.equals(language)) { model.getForm().getLocalizer().setLocale(locale); break; } } } } } public JrFormEntryModel getModel () { return (JrFormEntryModel)super.getModel(); } public void setView(IFormEntryView view) { this.view = view; view.attachFormMediaController(this); } public IFormEntryView getView(){ return this.view; } public void setTransitions(FormEntryTransitions transitions) { this.transitions = transitions; } /** * Handles the given key event, and returns a flag signifying whether * the interface should continue trying to handle the event. * * @param key The key that was pressed * @return true if the ui should stop handling this event. False if it * is ok to continue processing it. */ public boolean handleKeyEvent(int key) { if(getModel().getForm().getLocalizer() != null && key == POUND_KEYCODE && !FormManagerProperties.EXTRA_KEY_AUDIO_PLAYBACK.equals(getExtraKeyMode())) { cycleLanguage(); return true; } else if(FormManagerProperties.EXTRA_KEY_AUDIO_PLAYBACK.equals(getExtraKeyMode()) && key == POUND_KEYCODE){ //For now, we'll assume that video playback basically trumps audio playback. //TODO: Add a way to play videos when extra-key isn't set to audio if(player != null) { try { if(player.getState() == Player.STARTED) { player.stop(); } else { player.start(); } } catch (MediaException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } if(this.getModel().getEvent() != FormEntryController.EVENT_QUESTION) {return false;} playAudioOnDemand(this.getModel().getQuestionPrompt()); //We can keep processing this. Audio plays in the background. return false; } return false; } public void start() { view.show(); } /** * Start from a specific index * @param index */ public void start(FormIndex index){ view.show(index); } public void abort() { view.destroy(); transitions.abort(); } public void saveAndExit(boolean formComplete) { if (formComplete){ this.getModel().getForm().postProcessInstance(); } view.destroy(); transitions.formEntrySaved(this.getModel().getForm(),this.getModel().getForm().getInstance(),formComplete); } public void suspendActivity(int mediaType) throws UnavailableServiceException { view.destroy(); transitions.suspendForMediaCapture(mediaType); } public void cycleLanguage () { setLanguage(getModel().getForm().getLocalizer().getNextLocale()); } public String getExtraKeyMode() { return extraKeyMode; } //// New Audio Stuff follows below. I've tried to set it up so that we can split this out into a seperate "view" //// if you will at a later point. /** * Checks the boolean playAudioIfAvailable first. * Plays the question audio text */ public void playAudioOnLoad(FormEntryPrompt fep){ //If the current session is expecting audio playback w/the extrakey, don't //play it passively, wait for the button to be pressed. if(!FormManagerProperties.EXTRA_KEY_AUDIO_PLAYBACK.equals(extraKeyMode)) { playAudio(fep,null); } } /** * Checks the boolean playAudioIfAvailable first. * Plays the question audio text */ public void playAudioOnDemand(FormEntryPrompt fep){ playAudio(fep,null); } public int playAudioOnDemand(FormEntryPrompt fep,SelectChoice select) { return playAudio(fep, select); } /** * Plays audio for the SelectChoice (if AudioURI is present and media is available) * @param fep * @param select * @return */ public int playAudio(FormEntryPrompt fep,SelectChoice select){ if (!playAudioIfAvailable) return MediaUtils.AUDIO_DISABLED; String textID; curAudioURI = null; String tag = null; if (select == null) { if (fep.getAudioText() != null) { curAudioURI = fep.getAudioText(); tag = "#"; } else { return MediaUtils.AUDIO_NO_RESOURCE; } }else{ textID = select.getTextID(); if(textID == null || textID == "") return MediaUtils.AUDIO_NO_RESOURCE; if (fep.getSpecialFormSelectChoiceText(select, FormEntryCaption.TEXT_FORM_AUDIO) != null) { curAudioURI = fep.getSpecialFormSelectChoiceText(select, FormEntryCaption.TEXT_FORM_AUDIO); tag = String.valueOf(select.getIndex()); } else { return MediaUtils.AUDIO_NO_RESOURCE; } } //No idea why this is a member variable... return MediaUtils.playOrPauseAudio(curAudioURI, tag); } public boolean isEntryOptimized() { return quickEntry; } //A video player being controlled by this controller Player player; /* * (non-Javadoc) * @see org.javarosa.formmanager.api.FormMultimediaController#attachVideoPlayer(javax.microedition.media.Player) */ public void attachVideoPlayer(Player player) { //NOTE: Not thread safe if(this.player != null) { detachVideoPlayer(player); } this.player = player; this.player.removePlayerListener(logHandler); this.player.addPlayerListener(logHandler); } /* * (non-Javadoc) * @see org.javarosa.formmanager.api.FormMultimediaController#detachVideoPlayer(javax.microedition.media.Player) */ public void detachVideoPlayer(Player player) { if(this.player == player) { this.player = null; } } public void stopAudio() { MediaUtils.stopAudio(); } public void setMinimal(boolean isMinimal){ this.isMinimal = isMinimal; } public boolean isMinimal(){ return this.isMinimal; } }
debugging
j2me/form-entry/src/org/javarosa/formmanager/api/JrFormEntryController.java
debugging
<ide><path>2me/form-entry/src/org/javarosa/formmanager/api/JrFormEntryController.java <ide> <ide> this.logHandler = new PlayerListener() { <ide> public void playerUpdate(Player player, String event, Object eventData) { <add>Logger.log("jls", "in playerUpdate"); <ide> String action = ""; <ide> if (event == PlayerListener.STARTED) { <ide> action = "start"; <ide> else if (event == PlayerListener.END_OF_MEDIA) { <ide> action = "stop"; <ide> } <add>Logger.log("jls", "action = " + action); <ide> FormEntryPrompt fep = JrFormEntryController.this.getModel().getQuestionPrompt(); <ide> try { <ide> if (fep != null && fep.getAudioText() != null) { <ide> // TODO: move this to some sort of 'form entry diagnostics' framework <ide> // instead of bloating the logs <ide> String audio = fep.getAudioText(); <add>Logger.log("jls", "audio = " + audio); <ide> <ide> //extract just the audio filename to reduce log size <ide> String audioShort; <ide> audioShort = audio; <ide> } <ide> Logger.log("audio", action + " " + audioShort); <add> } <add> else { <add>Logger.log("jls", "Something was null: " + fep + " or " + fep.getAudioText()); <ide> } <ide> } catch(Exception e) { <ide> //Nothing
Java
bsd-2-clause
bd9d43d380f5a07f2708bd6ee53b6e6087ee2b64
0
iron-io/iron_worker_java
package io.iron.ironworker.client.entities; import com.google.gson.annotations.SerializedName; import java.util.Date; public class ScheduleEntity { @SerializedName("id") String id; @SerializedName("project_id") String projectId; @SerializedName("code_name") String codeName; @SerializedName("priority") int priority; @SerializedName("start_at") Date startAt; @SerializedName("end_at") Date endAt; @SerializedName("delay") int delay; @SerializedName("run_every") int runEvery; @SerializedName("run_times") int runTimes; @SerializedName("next_start") Date nextStart; @SerializedName("status") String status; @SerializedName("last_run_time") Date lastRunTime; @SerializedName("run_count") int runCount; @SerializedName("payload") String payload; @SerializedName("msg") String msg; @SerializedName("created_at") Date createdAt; @SerializedName("updated_at") Date updatedAt; protected ScheduleEntity() { } public String getId() { return id; } public String getProjectId() { return projectId; } public String getCodeName() { return codeName; } public int getPriority() { return priority; } public Date getStartAt() { return startAt; } public Date getEndAt() { return endAt; } public int getDelay() { return delay; } public int getRunEvery() { return runEvery; } public int getRunTimes() { return runTimes; } public Date getNextStart() { return nextStart; } public String getStatus() { return status; } public Date getLastRunTime() { return lastRunTime; } public int getRunCount() { return runCount; } public String getPayload() { return payload; } public String getMsg() { return msg; } public Date getCreatedAt() { return createdAt; } public Date getUpdatedAt() { return updatedAt; } }
client/src/main/java/io/iron/ironworker/client/entities/ScheduleEntity.java
package io.iron.ironworker.client.entities; import com.google.gson.annotations.SerializedName; import java.util.Date; public class ScheduleEntity { @SerializedName("id") String id; @SerializedName("project_id") String projectId; @SerializedName("code_name") String codeName; @SerializedName("priority") int priority; @SerializedName("start_at") Date startAt; @SerializedName("end_at") Date endAt; @SerializedName("delay") int delay; @SerializedName("run_every") int runEvery; @SerializedName("run_times") int runTimes; @SerializedName("next_start") Date nextStart; @SerializedName("status") String status; @SerializedName("last_run_time") long lastRunTime; @SerializedName("run_count") int runCount; @SerializedName("payload") String payload; @SerializedName("msg") String msg; @SerializedName("created_at") long createdAt; @SerializedName("updated_at") long updatedAt; protected ScheduleEntity() { } public String getId() { return id; } public String getProjectId() { return projectId; } public String getCodeName() { return codeName; } public int getPriority() { return priority; } public Date getStartAt() { return startAt; } public Date getEndAt() { return endAt; } public int getDelay() { return delay; } public int getRunEvery() { return runEvery; } public int getRunTimes() { return runTimes; } public Date getNextStart() { return nextStart; } public String getStatus() { return status; } public Date getLastRunTime() { return lastRunTime == 0 ? null : new Date(lastRunTime / 1000000); } public int getRunCount() { return runCount; } public String getPayload() { return payload; } public String getMsg() { return msg; } public Date getCreatedAt() { return createdAt == 0 ? null : new Date(createdAt / 1000000); } public Date getUpdatedAt() { return updatedAt == 0 ? null : new Date(updatedAt / 1000000); } }
Switched to dates from timestamp for schedules.
client/src/main/java/io/iron/ironworker/client/entities/ScheduleEntity.java
Switched to dates from timestamp for schedules.
<ide><path>lient/src/main/java/io/iron/ironworker/client/entities/ScheduleEntity.java <ide> @SerializedName("status") <ide> String status; <ide> @SerializedName("last_run_time") <del> long lastRunTime; <add> Date lastRunTime; <ide> @SerializedName("run_count") <ide> int runCount; <ide> @SerializedName("payload") <ide> @SerializedName("msg") <ide> String msg; <ide> @SerializedName("created_at") <del> long createdAt; <add> Date createdAt; <ide> @SerializedName("updated_at") <del> long updatedAt; <add> Date updatedAt; <ide> <ide> protected ScheduleEntity() { <ide> } <ide> } <ide> <ide> public Date getLastRunTime() { <del> return lastRunTime == 0 ? null : new Date(lastRunTime / 1000000); <add> return lastRunTime; <ide> } <ide> <ide> public int getRunCount() { <ide> } <ide> <ide> public Date getCreatedAt() { <del> return createdAt == 0 ? null : new Date(createdAt / 1000000); <add> return createdAt; <ide> } <ide> <ide> public Date getUpdatedAt() { <del> return updatedAt == 0 ? null : new Date(updatedAt / 1000000); <add> return updatedAt; <ide> } <ide> }
JavaScript
mit
cc0f902cec4c68756926bde930d25efc59bfdc59
0
sefzig/Robogeddon,sefzig/Robogeddon
'use strict'; const Script = require('smooch-bot').Script; // Bots const AndreasSefzig = "[AndreasSefzig] "; const SefzigBot = "[SefzigBot] "; const EmpfangsBot = "[EmpfangsBot] "; const KreationsBot = "[KreationsBot] "; const BeratungsBot = "[BeratungsBot] "; const KonzeptionsBot = "[KonzeptionsBot] "; const StrategieBot = "[StrategieBot] "; const TechnikBot = "[TechnikBot] "; const LinkBot = "[LinkBot] "; const TextBot = "[TextBot] "; const SlackBot = "[SlackBot] "; // Variablen var versuche_max = 3; var versuche = 0; var zuletzt = ""; var bekannt = false; // Daten var vorname = "Unbekannter"; var nachname = "Besucher"; var email = "[email protected]"; var emailkorrekt = true; // Konversationen module.exports = new Script({ // --------------- // GESPRÄCH ANFANG // --------------- processing: { prompt: (bot) => bot.say(EmpfangsBot+'Nicht so schnell bitte...'), receive: () => 'processing' }, start: { // prompt: (bot) => bot.say(EmpfangsBot+'Starte...'), receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim()); // Nächster Schritt default var dann = "empfang"; if (~befehl.indexOf("Weiterleiten zu:")) { // bot.say(EmpfangsBot+'Ich leite Sie weiter.'); } else { if (bekannt == false) { return bot.say(EmpfangsBot+' Willkommen in der Vorlage des --Chatraums. ').then(() => bot.say(EmpfangsBot+' Wir sind 3 Bots: Ich bin Alice, Barbara ist im --Verkauf und Cynthia macht unser --Marketing. ')).then(() => bot.say(EmpfangsBot+' Unterhalten Sie sich mit uns, indem Sie die farbig hinterlegten Wörter schreiben, klicken oder berühren! ')).then(() => bot.say(EmpfangsBot+' Ich habe rechts das Menü für Sie geöffnet. Sie können es mit dem Button oben rechts bedienen - oder indem Sie --Menü schreiben. [Javascript:menu(an)] ')).then(() => 'empfang'); } else { return bot.say(EmpfangsBot+' Willkommen zurück! Sprechen Sie mit mir über --Chatraum! ').then(() => bot.say(EmpfangsBot+' Oder sprechen Sie mit den anderen Bots über --Verkauf und --Marketing. ')).then(() => 'empfang'); } } return bot.setProp('empfangen', 'ja') .then(() => dann); } }, // ------------------------- // Onboarding // ------------------------- name: { receive: (bot, message) => { var antwort = befehlWort(message.text.trim().toUpperCase()); var dann = "name"; if ((antwort == "--JA") || (antwort == "--NAME") || (antwort == "--ÄNDERN")) { bot.say(EmpfangsBot+'Wir werden sorgsam mit Ihren Daten umgehen.'); dann = "vorname"; } if ((antwort == "--NEIN") || (antwort == "--EMPFANG") || (antwort == "--ABBRECHEN")) { bot.say(EmpfangsBot+'Gehen wir zurück zum --Empfang.'); dann = "empfang"; } if ((antwort == "--EMAIL") || (antwort == "--E-MAIL")) { bot.say(EmpfangsBot+'Wir geben Ihre Adresse nicht weiter.'); dann = "emailadresse"; } return bot.setProp('name_eingabe', 'tmp') .then(() => dann); } }, vorname: { prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'), receive: (bot, message) => { vorname = message.text; vorname = vorname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); return bot.setProp('vorname', vorname) .then(() => bot.say(EmpfangsBot+''+vorname+', prima.')) .then(() => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen? [Javascript:cookies(vorname,'+vorname+')] ')) .then(() => 'nachname'); } }, nachname: { receive: (bot, message) => { nachname = message.text; nachname = nachname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); nachname = nachname.replace("--",""); bot.setProp('nachname', nachname); return bot.getProp('vorname') .then((vorname) => bot.say(EmpfangsBot+'Sie heissen also '+vorname+' '+nachname+'. Bitte geben Sie nun Ihre E-Mail-Adresse ein (sie können auch --abbrechen). [Javascript:cookies(nachname,'+nachname+')] ')) .then(() => 'emailadresse'); } }, emailadresse: { receive: (bot, message) => { email = message.text; // emailkorrekt = email.test(emailregex); emailkorrekt = true; if (emailkorrekt == true) { return bot.setProp('email', email) .then(() => bot.say(EmpfangsBot+''+email+' ist eine valide E-Mail-Adresse. [Javascript:cookies(email,'+email+')] ')) .then(() => bot.say(EmpfangsBot+'Schreiben Sie --E-Mail, um sie zu ändern. Oder lassen Sie uns zurück zum --Empfang gehen.')) .then(() => 'empfang'); } else { return bot.say(+' 0 ').then(() => bot.say(EmpfangsBot+' Bitte geben Sie Ihre E-Mail-Adresse nochmal ein - oder lassen Sie uns zum --Empfang zurückkehren. ')).then(() => 'emailadresse'); } } }, // --------------------------- // Empfang (Alice) // --------------------------- // - name_klein: empfang // - name_kamel: Empfang // - name_gross: EMPFANG // - frau_klein: alice // - frau_kamel: Alice // - frau_gross: ALICE // - bot_name: EmpfangsBot // - bot_klein: empfangsbot // - bot_kamel: Empfangsbot // - bot_gross: EMPFANGSBOT // --------------------------- empfang: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "empfang"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Empfang"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("empfang" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Empfang") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(EmpfangsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'empfang');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(EmpfangsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(EmpfangsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(EmpfangsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'empfang');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(EmpfangsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'empfang');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(EmpfangsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'empfang');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(EmpfangsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'empfang');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(EmpfangsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(EmpfangsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'empfang');} // Produkte if ("empfang" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(EmpfangsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(EmpfangsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(EmpfangsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(EmpfangsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'empfang');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'empfang');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'empfang');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'empfang');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'empfang');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Name. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit meinen Kolleginnen in --Verkauf und --Marketing. ').then(() => bot.say(EmpfangsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'empfang');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--DATEN")) { versuch = true; return bot.say(EmpfangsBot+' Lassen Sie uns Ihre Daten durchgehen. ').then(() => 'name');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(EmpfangsBot+' Text Vorlage 1. ').then(() => 'empfang');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(EmpfangsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('empfang', 'gesprochen') .then(() => dann); } }, // --------------------------- // Beratung (Barbara) // --------------------------- // - name_klein: beratung // - name_kamel: Beratung // - name_gross: BERATUNG // - frau_klein: barbara // - frau_kamel: Barbara // - frau_gross: BARBARA // - bot_name: BeratungsBot // - bot_klein: beratungsbot // - bot_kamel: Beratungsbot // - bot_gross: BERATUNGSBOT // --------------------------- beratung: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "beratung"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Beratung"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("beratung" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Beratung") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(BeratungsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'beratung');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(BeratungsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(BeratungsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(BeratungsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'beratung');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(BeratungsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'beratung');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(BeratungsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'beratung');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(BeratungsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'beratung');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(BeratungsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(BeratungsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'beratung');} // Produkte if ("beratung" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(BeratungsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(BeratungsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(BeratungsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'beratung');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'beratung');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'beratung');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'beratung');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'beratung');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Name. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(BeratungsBot+' Sprechen Sie mit mir über --Produkte und --Beratung. ').then(() => bot.say(BeratungsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'beratung');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Text Produkt. ').then(() => 'beratung');} if (~befehl.indexOf("--BERAT")) { versuch = true; return bot.say(BeratungsBot+' Text Beratung. ').then(() => 'beratung');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(BeratungsBot+' Text Vorlage 1. ').then(() => 'beratung');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(BeratungsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('beratung', 'gesprochen') .then(() => dann); } }, // --------------------------- // Technik (Cynthia) // --------------------------- // - name_klein: technik // - name_kamel: Technik // - name_gross: TECHNIK // - frau_klein: cynthia // - frau_kamel: Cynthia // - frau_gross: CYNTHIA // - bot_name: TechnikBot // - bot_klein: technikbot // - bot_kamel: Technikbot // - bot_gross: TECHNIKBOT // --------------------------- technik: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "technik"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Technik"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("technik" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Technik") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(TechnikBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'technik');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(TechnikBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(TechnikBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(TechnikBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'technik');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(TechnikBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'technik');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(TechnikBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'technik');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(TechnikBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'technik');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(TechnikBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(TechnikBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'technik');} // Produkte if ("technik" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(TechnikBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(TechnikBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(TechnikBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(TechnikBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'technik');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'technik');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'technik');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'technik');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'technik');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Name. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(TechnikBot+' Sprechen Sie mit mir über --Facebook und --Umfrage. ').then(() => bot.say(TechnikBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'technik');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--FACEBOOK")) { versuch = true; return bot.say(TechnikBot+' Text Facebook. ').then(() => 'technik');} if (~befehl.indexOf("--UMFRAGE")) { versuch = true; return bot.say(TechnikBot+' Text Umfrage. ').then(() => 'technik');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(TechnikBot+' Text Vorlage 1. ').then(() => 'technik');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(TechnikBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('technik', 'gesprochen') .then(() => dann); } }, // --------------------------- // Kreation (Doris) // --------------------------- // - name_klein: kreation // - name_kamel: Kreation // - name_gross: KREATION // - frau_klein: doris // - frau_kamel: Doris // - frau_gross: DORIS // - bot_name: KreationsBot // - bot_klein: kreationsbot // - bot_kamel: Kreationsbot // - bot_gross: KREATIONSBOT // --------------------------- kreation: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "kreation"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Kreation"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("kreation" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Kreation") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KreationsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'kreation');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KreationsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KreationsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KreationsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'kreation');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KreationsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'kreation');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KreationsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'kreation');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KreationsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'kreation');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KreationsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KreationsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'kreation');} // Produkte if ("kreation" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KreationsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KreationsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KreationsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KreationsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'kreation');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'kreation');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'kreation');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'kreation');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'kreation');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Name. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(KreationsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('kreation', 'gesprochen') .then(() => dann); } }, // --------------------------- // Konzeption (Erika) // --------------------------- // - name_klein: konzeption // - name_kamel: Konzeption // - name_gross: KONZEPTION // - frau_klein: erika // - frau_kamel: Erika // - frau_gross: ERIKA // - bot_name: KonzeptionsBot // - bot_klein: konzeptionsbot // - bot_kamel: Konzeptionsbot // - bot_gross: KONZEPTIONSBOT // --------------------------- konzeption: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "konzeption"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Konzeption"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("konzeption" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Konzeption") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KonzeptionsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'konzeption');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KonzeptionsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KonzeptionsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KonzeptionsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'konzeption');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KonzeptionsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'konzeption');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KonzeptionsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'konzeption');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KonzeptionsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'konzeption');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KonzeptionsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KonzeptionsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'konzeption');} // Produkte if ("konzeption" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KonzeptionsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KonzeptionsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KonzeptionsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KonzeptionsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'konzeption');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'konzeption');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'konzeption');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'konzeption');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'konzeption');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Name. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(KonzeptionsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('konzeption', 'gesprochen') .then(() => dann); } }, // --------------------------- // Strategie (Feline) // --------------------------- // - name_klein: strategie // - name_kamel: Strategie // - name_gross: STRATEGIE // - frau_klein: feline // - frau_kamel: Feline // - frau_gross: FELINE // - bot_name: StrategieBot // - bot_klein: strategiebot // - bot_kamel: Strategiebot // - bot_gross: STRATEGIEBOT // --------------------------- strategie: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "strategie"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Strategie"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("strategie" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Strategie") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(StrategieBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'strategie');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(StrategieBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(StrategieBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(StrategieBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'strategie');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(StrategieBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'strategie');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(StrategieBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'strategie');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(StrategieBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'strategie');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(StrategieBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(StrategieBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'strategie');} // Produkte if ("strategie" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(StrategieBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(StrategieBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(StrategieBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(StrategieBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'strategie');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'strategie');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'strategie');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'strategie');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'strategie');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Name. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(StrategieBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('strategie', 'gesprochen') .then(() => dann); } }, finish: { receive: (bot, message) => { return bot.getProp('name') .then(() => 'finish'); } } // -------------- // GESPRÄCH AUS // -------------- }); // Befehle function befehlWort(befehl) { // Wenn die Nachricht nur ein Wort ist var test = befehl.split(" "); if ((!test[1]) || (test[1] == "")) { // In Befehl umwandeln befehl = befehl.replace("--", ""); befehl = "--"+befehl; // Satzzeichen entfernen befehl = befehl.replace(".", ""); befehl = befehl.replace("!", ""); befehl = befehl.replace("?", ""); } return befehl; } // Bots vereinfachen function sagenhaft(befehl, dann, bot, text1, text2, text3, text4, text5) { // sagenhaft('Strategie', dann, bot, // SefzigBot+'Chatten ist die häufigste digitale Beschäftigung in Deutschland: [Text:Aktuelle Statistiken,RobogeddonChatten] Ein weltweiter --Trend mit erheblichen absehbaren Auswirkungen auf die Benutzeroberflächen des Internets.', // SefzigBot+'Chat-Bots gibt es schon --lange. Sie werden gerade jetzt für das Marketing interessant, weil die meisten Menschen mit Chatten vertraut sind und große Anwendungen wie --Facebook, --Slack u.a. ihre Plattformen für Bots öffnen.', // SefzigBot+'Interessieren Sie sich eher für Bots, die --intern (z.B. mit Ihrem Team) oder --extern (z.B. mit Ihren Kunden) kommunizieren?' // ); if (~befehl.indexOf("--STRATEGIE")) { versuch = true; if ((text5) && (text5 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3) }).then(function(){ return bot.say(text4) }).then(function(){ return bot.say(text5); }); } else if ((text4) && (text4 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3) }).then(function(){ return bot.say(text4); }); } else if ((text3) && (text3 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3); }); } else if ((text2) && (text2 != "")) { bot.say(text1).then(function(){ return bot.say(text2); }); } else if ((text1) && (text1 != "")) { bot.say(text1); } } }
script.js
'use strict'; const Script = require('smooch-bot').Script; // Bots const AndreasSefzig = "[AndreasSefzig] "; const SefzigBot = "[SefzigBot] "; const EmpfangsBot = "[EmpfangsBot] "; const KreationsBot = "[KreationsBot] "; const BeratungsBot = "[BeratungsBot] "; const KonzeptionsBot = "[KonzeptionsBot] "; const StrategieBot = "[StrategieBot] "; const TechnikBot = "[TechnikBot] "; const LinkBot = "[LinkBot] "; const TextBot = "[TextBot] "; const SlackBot = "[SlackBot] "; // Variablen var versuche_max = 3; var versuche = 0; var zuletzt = ""; var bekannt = false; // Daten var vorname = "Unbekannter"; var nachname = "Besucher"; var email = "[email protected]"; var emailkorrekt = true; // Konversationen module.exports = new Script({ // --------------- // GESPRÄCH ANFANG // --------------- processing: { prompt: (bot) => bot.say(EmpfangsBot+'Nicht so schnell bitte...'), receive: () => 'processing' }, start: { // prompt: (bot) => bot.say(EmpfangsBot+'Starte...'), receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim()); // Nächster Schritt default var dann = "empfang"; if (~befehl.indexOf("Weiterleiten zu:")) { // bot.say(EmpfangsBot+'Ich leite Sie weiter.'); } else { if (bekannt == false) { return bot.say(EmpfangsBot+' Willkommen in der Vorlage des --Chatraums. ').then(() => bot.say(EmpfangsBot+' Wir sind 3 Bots: Ich bin Alice, Barbara ist im --Verkauf und Cynthia macht unser --Marketing. ')).then(() => bot.say(EmpfangsBot+' Unterhalten Sie sich mit uns, indem Sie die farbig hinterlegten Wörter schreiben, klicken oder berühren! ')).then(() => bot.say(EmpfangsBot+' Ich habe rechts das Menü für Sie geöffnet. Sie können es mit dem Button oben rechts bedienen - oder indem Sie --Menü schreiben. [Javascript:menu(an)] ')).then(() => 'empfang'); } else { return bot.say(EmpfangsBot+' Willkommen zurück! Sprechen Sie mit mir über --Chatraum! ').then(() => bot.say(EmpfangsBot+' Oder sprechen Sie mit den anderen Bots über --Verkauf und --Marketing. ')).then(() => 'empfang'); } } return bot.setProp('empfangen', 'ja') .then(() => dann); } }, // ------------------------- // Onboarding // ------------------------- name: { receive: (bot, message) => { var antwort = befehlWort(message.text.trim().toUpperCase()); var dann = "name"; if ((antwort == "--JA") || (antwort == "--NAME") || (antwort == "--ÄNDERN")) { bot.say(EmpfangsBot+'Wir werden sorgsam mit Ihren Daten umgehen.'); dann = "vorname"; } if ((antwort == "--NEIN") || (antwort == "--EMPFANG") || (antwort == "--ABBRECHEN")) { bot.say(EmpfangsBot+'Gehen wir zurück zum --Empfang.'); dann = "empfang"; } if ((antwort == "--EMAIL") || (antwort == "--E-MAIL")) { bot.say(EmpfangsBot+'Wir geben Ihre Adresse nicht weiter.'); dann = "emailadresse"; } return bot.setProp('name_eingabe', 'tmp') .then(() => dann); } }, vorname: { prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'), receive: (bot, message) => { vorname = message.text; vorname = vorname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); return bot.setProp('vorname', vorname) .then(() => bot.say(EmpfangsBot+''+vorname+', prima.')) .then(() => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen? [Javascript:cookies(vorname,'+vorname+')] ')) .then(() => 'nachname'); } }, nachname: { receive: (bot, message) => { nachname = message.text; nachname = nachname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); nachname = nachname.replace("--",""); bot.setProp('nachname', nachname); return bot.getProp('vorname') .then((vorname) => bot.say(EmpfangsBot+'Sie heissen also '+vorname+' '+nachname+'. Bitte geben Sie nun Ihre E-Mail-Adresse ein (sie können auch --abbrechen). [Javascript:cookies(nachname,'+nachname+')] ')) .then(() => 'emailadresse'); } }, emailadresse: { receive: (bot, message) => { email = message.text; // emailkorrekt = email.test(emailregex); emailkorrekt = true; if (emailkorrekt == true) { return bot.setProp('email', email) .then(() => bot.say(EmpfangsBot+''+email+' ist eine valide E-Mail-Adresse. [Javascript:cookies(email,'+email+')] ')) .then(() => bot.say(EmpfangsBot+'Schreiben Sie --E-Mail, um sie zu ändern. Oder lassen Sie uns zurück zum --Empfang gehen.')) .then(() => 'empfang'); } else { return bot.say(+' 0 ').then(() => bot.say(EmpfangsBot+' Bitte geben Sie Ihre E-Mail-Adresse nochmal ein - oder lassen Sie uns zum --Empfang zurückkehren. ')).then(() => 'emailadresse'); } } }, // --------------------------- // Empfang (Alice) // --------------------------- // - name_klein: empfang // - name_kamel: Empfang // - name_gross: EMPFANG // - frau_klein: alice // - frau_kamel: Alice // - frau_gross: ALICE // - bot_name: EmpfangsBot // - bot_klein: empfangsbot // - bot_kamel: Empfangsbot // - bot_gross: EMPFANGSBOT // --------------------------- empfang: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "empfang"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Empfang"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("empfang" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Empfang") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(EmpfangsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'empfang');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(EmpfangsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(EmpfangsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(EmpfangsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'empfang');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(EmpfangsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'empfang');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(EmpfangsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'empfang');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(EmpfangsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'empfang');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(EmpfangsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(EmpfangsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'empfang');} // Produkte if ("empfang" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(EmpfangsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(EmpfangsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(EmpfangsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(EmpfangsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'empfang');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'empfang');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'empfang');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'empfang');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'empfang');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Name. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit meinen Kolleginnen in --Verkauf und --Marketing. ').then(() => bot.say(EmpfangsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'empfang');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--DATEN")) { versuch = true; return bot.say(EmpfangsBot+' Lassen Sie uns Ihre Daten durchgehen. ').then(() => 'name');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(EmpfangsBot+' Text Vorlage 1. ').then(() => 'empfang');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(EmpfangsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('empfang', 'gesprochen') .then(() => dann); } }, // --------------------------- // Beratung (Barbara) // --------------------------- // - name_klein: beratung // - name_kamel: Beratung // - name_gross: BERATUNG // - frau_klein: barbara // - frau_kamel: Barbara // - frau_gross: BARBARA // - bot_name: BeratungsBot // - bot_klein: beratungsbot // - bot_kamel: Beratungsbot // - bot_gross: BERATUNGSBOT // --------------------------- beratung: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "beratung"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Beratung"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("beratung" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Beratung") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(BeratungsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'beratung');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(BeratungsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(BeratungsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(BeratungsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'beratung');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(BeratungsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'beratung');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(BeratungsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'beratung');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(BeratungsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'beratung');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(BeratungsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(BeratungsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'beratung');} // Produkte if ("beratung" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(BeratungsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(BeratungsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(BeratungsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'beratung');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'beratung');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'beratung');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'beratung');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'beratung');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Name. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(BeratungsBot+' Sprechen Sie mit mir über --Produkte und --Beratung. ').then(() => bot.say(BeratungsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'beratung');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Text Produkt. ').then(() => 'beratung');} if (~befehl.indexOf("--BERAT")) { versuch = true; return bot.say(BeratungsBot+' Text Beratung. ').then(() => 'beratung');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(BeratungsBot+' Text Vorlage 1. ').then(() => 'beratung');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(BeratungsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('beratung', 'gesprochen') .then(() => dann); } }, // --------------------------- // Technik (Cynthia) // --------------------------- // - name_klein: technik // - name_kamel: Technik // - name_gross: TECHNIK // - frau_klein: cynthia // - frau_kamel: Cynthia // - frau_gross: CYNTHIA // - bot_name: TechnikBot // - bot_klein: technikbot // - bot_kamel: Technikbot // - bot_gross: TECHNIKBOT // --------------------------- technik: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "technik"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Technik"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("technik" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Technik") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(TechnikBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'technik');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(TechnikBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(TechnikBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(TechnikBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'technik');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(TechnikBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'technik');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(TechnikBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'technik');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(TechnikBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'technik');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(TechnikBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(TechnikBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'technik');} // Produkte if ("technik" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(TechnikBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(TechnikBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(TechnikBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(TechnikBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'technik');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'technik');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'technik');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'technik');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'technik');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Name. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(TechnikBot+' Sprechen Sie mit mir über --Facebook und --Umfrage. ').then(() => bot.say(TechnikBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'technik');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--FACEBOOK")) { versuch = true; return bot.say(TechnikBot+' Text Facebook. ').then(() => 'technik');} if (~befehl.indexOf("--UMFRAGE")) { versuch = true; return bot.say(TechnikBot+' Text Umfrage. ').then(() => 'technik');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(TechnikBot+' Text Vorlage 1. ').then(() => 'technik');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(TechnikBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('technik', 'gesprochen') .then(() => dann); } }, // --------------------------- // Kreation (Doris) // --------------------------- // - name_klein: kreation // - name_kamel: Kreation // - name_gross: KREATION // - frau_klein: doris // - frau_kamel: Doris // - frau_gross: DORIS // - bot_name: KreationsBot // - bot_klein: kreationsbot // - bot_kamel: Kreationsbot // - bot_gross: KREATIONSBOT // --------------------------- kreation: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "kreation"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Kreation"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("kreation" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Kreation") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KreationsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'kreation');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KreationsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KreationsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KreationsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'kreation');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KreationsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'kreation');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KreationsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'kreation');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KreationsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'kreation');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KreationsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KreationsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'kreation');} // Produkte if ("kreation" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KreationsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KreationsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KreationsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KreationsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'kreation');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'kreation');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'kreation');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'kreation');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'kreation');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Name. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(KreationsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('kreation', 'gesprochen') .then(() => dann); } }, // --------------------------- // Konzeption (Erika) // --------------------------- // - name_klein: konzeption // - name_kamel: Konzeption // - name_gross: KONZEPTION // - frau_klein: erika // - frau_kamel: Erika // - frau_gross: ERIKA // - bot_name: KonzeptionsBot // - bot_klein: konzeptionsbot // - bot_kamel: Konzeptionsbot // - bot_gross: KONZEPTIONSBOT // --------------------------- konzeption: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "konzeption"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Konzeption"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("konzeption" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Konzeption") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KonzeptionsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'konzeption');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KonzeptionsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KonzeptionsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KonzeptionsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'konzeption');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KonzeptionsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'konzeption');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KonzeptionsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'konzeption');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KonzeptionsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'konzeption');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KonzeptionsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KonzeptionsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'konzeption');} // Produkte if ("konzeption" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KonzeptionsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KonzeptionsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KonzeptionsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KonzeptionsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'konzeption');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'konzeption');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'konzeption');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'konzeption');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'konzeption');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Name. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(KonzeptionsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('konzeption', 'gesprochen') .then(() => dann); } }, // --------------------------- // Strategie (Feline) // --------------------------- // - name_klein: strategie // - name_kamel: Strategie // - name_gross: STRATEGIE // - frau_klein: feline // - frau_kamel: Feline // - frau_gross: FELINE // - bot_name: StrategieBot // - bot_klein: strategiebot // - bot_kamel: Strategiebot // - bot_gross: STRATEGIEBOT // --------------------------- strategie: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "strategie"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Strategie"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("strategie" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Strategie") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(StrategieBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'strategie');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(StrategieBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(StrategieBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(StrategieBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'strategie');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(StrategieBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'strategie');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(StrategieBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'strategie');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(StrategieBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'strategie');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(StrategieBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(StrategieBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'strategie');} // Produkte if ("strategie" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(StrategieBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(StrategieBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(StrategieBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(StrategieBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'strategie');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'strategie');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'strategie');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'strategie');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'strategie');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Name. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(StrategieBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('strategie', 'gesprochen') .then(() => dann); } }, finish: { receive: (bot, message) => { return bot.getProp('name') .then(() => 'finish'); } } // -------------- // GESPRÄCH AUS // -------------- }); // Befehle function befehlWort(befehl) { // Wenn die Nachricht nur ein Wort ist var test = befehl.split(" "); if ((!test[1]) || (test[1] == "")) { // In Befehl umwandeln befehl = befehl.replace("--", ""); befehl = "--"+befehl; // Satzzeichen entfernen befehl = befehl.replace(".", ""); befehl = befehl.replace("!", ""); befehl = befehl.replace("?", ""); } return befehl; } // Bots vereinfachen function sagenhaft(befehl, dann, bot, text1, text2, text3, text4, text5) { // sagenhaft('Strategie', dann, bot, // SefzigBot+'Chatten ist die häufigste digitale Beschäftigung in Deutschland: [Text:Aktuelle Statistiken,RobogeddonChatten] Ein weltweiter --Trend mit erheblichen absehbaren Auswirkungen auf die Benutzeroberflächen des Internets.', // SefzigBot+'Chat-Bots gibt es schon --lange. Sie werden gerade jetzt für das Marketing interessant, weil die meisten Menschen mit Chatten vertraut sind und große Anwendungen wie --Facebook, --Slack u.a. ihre Plattformen für Bots öffnen.', // SefzigBot+'Interessieren Sie sich eher für Bots, die --intern (z.B. mit Ihrem Team) oder --extern (z.B. mit Ihren Kunden) kommunizieren?' // ); if (~befehl.indexOf("--STRATEGIE")) { versuch = true; if ((text5) && (text5 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3) }).then(function(){ return bot.say(text4) }).then(function(){ return bot.say(text5); }); } else if ((text4) && (text4 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3) }).then(function(){ return bot.say(text4); }); } else if ((text3) && (text3 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3); }); } else if ((text2) && (text2 != "")) { bot.say(text1).then(function(){ return bot.say(text2); }); } else if ((text1) && (text1 != "")) { bot.say(text1); } } }
Skript Test
script.js
Skript
<ide><path>cript.js <del>'use strict'; const Script = require('smooch-bot').Script; // Bots const AndreasSefzig = "[AndreasSefzig] "; const SefzigBot = "[SefzigBot] "; const EmpfangsBot = "[EmpfangsBot] "; const KreationsBot = "[KreationsBot] "; const BeratungsBot = "[BeratungsBot] "; const KonzeptionsBot = "[KonzeptionsBot] "; const StrategieBot = "[StrategieBot] "; const TechnikBot = "[TechnikBot] "; const LinkBot = "[LinkBot] "; const TextBot = "[TextBot] "; const SlackBot = "[SlackBot] "; // Variablen var versuche_max = 3; var versuche = 0; var zuletzt = ""; var bekannt = false; // Daten var vorname = "Unbekannter"; var nachname = "Besucher"; var email = "[email protected]"; var emailkorrekt = true; // Konversationen module.exports = new Script({ // --------------- // GESPRÄCH ANFANG // --------------- processing: { prompt: (bot) => bot.say(EmpfangsBot+'Nicht so schnell bitte...'), receive: () => 'processing' }, start: { // prompt: (bot) => bot.say(EmpfangsBot+'Starte...'), receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim()); // Nächster Schritt default var dann = "empfang"; if (~befehl.indexOf("Weiterleiten zu:")) { // bot.say(EmpfangsBot+'Ich leite Sie weiter.'); } else { if (bekannt == false) { return bot.say(EmpfangsBot+' Willkommen in der Vorlage des --Chatraums. ').then(() => bot.say(EmpfangsBot+' Wir sind 3 Bots: Ich bin Alice, Barbara ist im --Verkauf und Cynthia macht unser --Marketing. ')).then(() => bot.say(EmpfangsBot+' Unterhalten Sie sich mit uns, indem Sie die farbig hinterlegten Wörter schreiben, klicken oder berühren! ')).then(() => bot.say(EmpfangsBot+' Ich habe rechts das Menü für Sie geöffnet. Sie können es mit dem Button oben rechts bedienen - oder indem Sie --Menü schreiben. [Javascript:menu(an)] ')).then(() => 'empfang'); } else { return bot.say(EmpfangsBot+' Willkommen zurück! Sprechen Sie mit mir über --Chatraum! ').then(() => bot.say(EmpfangsBot+' Oder sprechen Sie mit den anderen Bots über --Verkauf und --Marketing. ')).then(() => 'empfang'); } } return bot.setProp('empfangen', 'ja') .then(() => dann); } }, // ------------------------- // Onboarding // ------------------------- name: { receive: (bot, message) => { var antwort = befehlWort(message.text.trim().toUpperCase()); var dann = "name"; if ((antwort == "--JA") || (antwort == "--NAME") || (antwort == "--ÄNDERN")) { bot.say(EmpfangsBot+'Wir werden sorgsam mit Ihren Daten umgehen.'); dann = "vorname"; } if ((antwort == "--NEIN") || (antwort == "--EMPFANG") || (antwort == "--ABBRECHEN")) { bot.say(EmpfangsBot+'Gehen wir zurück zum --Empfang.'); dann = "empfang"; } if ((antwort == "--EMAIL") || (antwort == "--E-MAIL")) { bot.say(EmpfangsBot+'Wir geben Ihre Adresse nicht weiter.'); dann = "emailadresse"; } return bot.setProp('name_eingabe', 'tmp') .then(() => dann); } }, vorname: { prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'), receive: (bot, message) => { vorname = message.text; vorname = vorname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); return bot.setProp('vorname', vorname) .then(() => bot.say(EmpfangsBot+''+vorname+', prima.')) .then(() => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen? [Javascript:cookies(vorname,'+vorname+')] ')) .then(() => 'nachname'); } }, nachname: { receive: (bot, message) => { nachname = message.text; nachname = nachname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); nachname = nachname.replace("--",""); bot.setProp('nachname', nachname); return bot.getProp('vorname') .then((vorname) => bot.say(EmpfangsBot+'Sie heissen also '+vorname+' '+nachname+'. Bitte geben Sie nun Ihre E-Mail-Adresse ein (sie können auch --abbrechen). [Javascript:cookies(nachname,'+nachname+')] ')) .then(() => 'emailadresse'); } }, emailadresse: { receive: (bot, message) => { email = message.text; // emailkorrekt = email.test(emailregex); emailkorrekt = true; if (emailkorrekt == true) { return bot.setProp('email', email) .then(() => bot.say(EmpfangsBot+''+email+' ist eine valide E-Mail-Adresse. [Javascript:cookies(email,'+email+')] ')) .then(() => bot.say(EmpfangsBot+'Schreiben Sie --E-Mail, um sie zu ändern. Oder lassen Sie uns zurück zum --Empfang gehen.')) .then(() => 'empfang'); } else { return bot.say(+' 0 ').then(() => bot.say(EmpfangsBot+' Bitte geben Sie Ihre E-Mail-Adresse nochmal ein - oder lassen Sie uns zum --Empfang zurückkehren. ')).then(() => 'emailadresse'); } } }, // --------------------------- // Empfang (Alice) // --------------------------- // - name_klein: empfang // - name_kamel: Empfang // - name_gross: EMPFANG // - frau_klein: alice // - frau_kamel: Alice // - frau_gross: ALICE // - bot_name: EmpfangsBot // - bot_klein: empfangsbot // - bot_kamel: Empfangsbot // - bot_gross: EMPFANGSBOT // --------------------------- empfang: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "empfang"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Empfang"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("empfang" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Empfang") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(EmpfangsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'empfang');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(EmpfangsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(EmpfangsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(EmpfangsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'empfang');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(EmpfangsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'empfang');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(EmpfangsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'empfang');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(EmpfangsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'empfang');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(EmpfangsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(EmpfangsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'empfang');} // Produkte if ("empfang" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(EmpfangsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(EmpfangsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(EmpfangsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(EmpfangsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'empfang');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'empfang');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'empfang');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'empfang');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'empfang');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Name. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit meinen Kolleginnen in --Verkauf und --Marketing. ').then(() => bot.say(EmpfangsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'empfang');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--DATEN")) { versuch = true; return bot.say(EmpfangsBot+' Lassen Sie uns Ihre Daten durchgehen. ').then(() => 'name');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(EmpfangsBot+' Text Vorlage 1. ').then(() => 'empfang');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(EmpfangsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('empfang', 'gesprochen') .then(() => dann); } }, // --------------------------- // Beratung (Barbara) // --------------------------- // - name_klein: beratung // - name_kamel: Beratung // - name_gross: BERATUNG // - frau_klein: barbara // - frau_kamel: Barbara // - frau_gross: BARBARA // - bot_name: BeratungsBot // - bot_klein: beratungsbot // - bot_kamel: Beratungsbot // - bot_gross: BERATUNGSBOT // --------------------------- beratung: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "beratung"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Beratung"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("beratung" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Beratung") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(BeratungsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'beratung');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(BeratungsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(BeratungsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(BeratungsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'beratung');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(BeratungsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'beratung');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(BeratungsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'beratung');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(BeratungsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'beratung');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(BeratungsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(BeratungsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'beratung');} // Produkte if ("beratung" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(BeratungsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(BeratungsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(BeratungsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'beratung');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'beratung');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'beratung');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'beratung');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'beratung');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Name. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(BeratungsBot+' Sprechen Sie mit mir über --Produkte und --Beratung. ').then(() => bot.say(BeratungsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'beratung');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Text Produkt. ').then(() => 'beratung');} if (~befehl.indexOf("--BERAT")) { versuch = true; return bot.say(BeratungsBot+' Text Beratung. ').then(() => 'beratung');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(BeratungsBot+' Text Vorlage 1. ').then(() => 'beratung');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(BeratungsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('beratung', 'gesprochen') .then(() => dann); } }, // --------------------------- // Technik (Cynthia) // --------------------------- // - name_klein: technik // - name_kamel: Technik // - name_gross: TECHNIK // - frau_klein: cynthia // - frau_kamel: Cynthia // - frau_gross: CYNTHIA // - bot_name: TechnikBot // - bot_klein: technikbot // - bot_kamel: Technikbot // - bot_gross: TECHNIKBOT // --------------------------- technik: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "technik"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Technik"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("technik" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Technik") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(TechnikBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'technik');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(TechnikBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(TechnikBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(TechnikBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'technik');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(TechnikBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'technik');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(TechnikBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'technik');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(TechnikBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'technik');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(TechnikBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(TechnikBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'technik');} // Produkte if ("technik" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(TechnikBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(TechnikBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(TechnikBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(TechnikBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'technik');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'technik');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'technik');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'technik');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'technik');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Name. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // System // ----------------- if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(TechnikBot+' Sprechen Sie mit mir über --Facebook und --Umfrage. ').then(() => bot.say(TechnikBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'technik');} if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');} // ----------------- // Inhalte // ----------------- if (~befehl.indexOf("--FACEBOOK")) { versuch = true; return bot.say(TechnikBot+' Text Facebook. ').then(() => 'technik');} if (~befehl.indexOf("--UMFRAGE")) { versuch = true; return bot.say(TechnikBot+' Text Umfrage. ').then(() => 'technik');} // ----------------- // Vorlage // ----------------- if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(TechnikBot+' Text Vorlage 1. ').then(() => 'technik');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(TechnikBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('technik', 'gesprochen') .then(() => dann); } }, // --------------------------- // Kreation (Doris) // --------------------------- // - name_klein: kreation // - name_kamel: Kreation // - name_gross: KREATION // - frau_klein: doris // - frau_kamel: Doris // - frau_gross: DORIS // - bot_name: KreationsBot // - bot_klein: kreationsbot // - bot_kamel: Kreationsbot // - bot_gross: KREATIONSBOT // --------------------------- kreation: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "kreation"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Kreation"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("kreation" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Kreation") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KreationsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'kreation');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KreationsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KreationsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KreationsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'kreation');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KreationsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'kreation');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KreationsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'kreation');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KreationsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'kreation');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KreationsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KreationsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'kreation');} // Produkte if ("kreation" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KreationsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KreationsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KreationsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KreationsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'kreation');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'kreation');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'kreation');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'kreation');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'kreation');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Name. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(KreationsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('kreation', 'gesprochen') .then(() => dann); } }, // --------------------------- // Konzeption (Erika) // --------------------------- // - name_klein: konzeption // - name_kamel: Konzeption // - name_gross: KONZEPTION // - frau_klein: erika // - frau_kamel: Erika // - frau_gross: ERIKA // - bot_name: KonzeptionsBot // - bot_klein: konzeptionsbot // - bot_kamel: Konzeptionsbot // - bot_gross: KONZEPTIONSBOT // --------------------------- konzeption: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "konzeption"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Konzeption"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("konzeption" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Konzeption") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KonzeptionsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'konzeption');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KonzeptionsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KonzeptionsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KonzeptionsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'konzeption');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KonzeptionsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'konzeption');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KonzeptionsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'konzeption');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KonzeptionsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'konzeption');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KonzeptionsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KonzeptionsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'konzeption');} // Produkte if ("konzeption" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KonzeptionsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KonzeptionsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KonzeptionsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KonzeptionsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'konzeption');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'konzeption');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'konzeption');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'konzeption');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'konzeption');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Name. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(KonzeptionsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('konzeption', 'gesprochen') .then(() => dann); } }, // --------------------------- // Strategie (Feline) // --------------------------- // - name_klein: strategie // - name_kamel: Strategie // - name_gross: STRATEGIE // - frau_klein: feline // - frau_kamel: Feline // - frau_gross: FELINE // - bot_name: StrategieBot // - bot_klein: strategiebot // - bot_kamel: Strategiebot // - bot_gross: STRATEGIEBOT // --------------------------- strategie: { receive: (bot, message) => { // Befehl normalisieren var befehl = befehlWort(message.text.trim().toUpperCase()); // Nächster Schritt default var dann = "strategie"; // Nicht-Befehl-Eingaben mitzählen var versuch = false; // Default-Zurück var zuruck = "Strategie"; // Zuletzt Varianten var zuletzt_dann = dann; var zuletzt_klein = zuletzt_dann.toLowerCase(); var zuletzt_gross = zuletzt_dann.toUpperCase(); var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); // ----------------- // Befehle // ----------------- if ("strategie" != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} } if (zuletzt_kamel != "Strategie") { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } } else { if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(StrategieBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'strategie');} } if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');} // ----------------- // Onboarding // ----------------- if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { if (~befehl.indexOf("--NAME")) { versuch = true; } } else { if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(StrategieBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} } // ----------------- // Kontakt // ----------------- if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(StrategieBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(StrategieBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'strategie');} if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(StrategieBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'strategie');} if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(StrategieBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'strategie');} if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(StrategieBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'strategie');} // ----------------- // Über uns // ----------------- if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(StrategieBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(StrategieBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'strategie');} // Produkte if ("strategie" != "verkauf") { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(StrategieBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} } // ----------------- // Funktionen // ----------------- if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(StrategieBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(StrategieBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(StrategieBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'strategie');} // Stile if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'strategie');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'strategie');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'strategie');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'strategie');} // ----------------- // Bots // ----------------- if (zuletzt_klein != "empfang") { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } if (zuletzt_klein != "verkauf") { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } if (zuletzt_klein != "marketing") { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } // Vorlage (Gewerk, Name) if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Name. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} // ----------------- // Bot aus // ----------------- // Zurück merken zuletzt = zuruck; // Irrläufer if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { bot.say(StrategieBot+'Suchen Sie meine --Befehle?'); versuche = 0; } } // Weiterleiten return bot.setProp('strategie', 'gesprochen') .then(() => dann); } }, finish: { receive: (bot, message) => { return bot.getProp('name') .then(() => 'finish'); } } // -------------- // GESPRÄCH AUS // -------------- }); // Befehle function befehlWort(befehl) { // Wenn die Nachricht nur ein Wort ist var test = befehl.split(" "); if ((!test[1]) || (test[1] == "")) { // In Befehl umwandeln befehl = befehl.replace("--", ""); befehl = "--"+befehl; // Satzzeichen entfernen befehl = befehl.replace(".", ""); befehl = befehl.replace("!", ""); befehl = befehl.replace("?", ""); } return befehl; } // Bots vereinfachen function sagenhaft(befehl, dann, bot, text1, text2, text3, text4, text5) { // sagenhaft('Strategie', dann, bot, // SefzigBot+'Chatten ist die häufigste digitale Beschäftigung in Deutschland: [Text:Aktuelle Statistiken,RobogeddonChatten] Ein weltweiter --Trend mit erheblichen absehbaren Auswirkungen auf die Benutzeroberflächen des Internets.', // SefzigBot+'Chat-Bots gibt es schon --lange. Sie werden gerade jetzt für das Marketing interessant, weil die meisten Menschen mit Chatten vertraut sind und große Anwendungen wie --Facebook, --Slack u.a. ihre Plattformen für Bots öffnen.', // SefzigBot+'Interessieren Sie sich eher für Bots, die --intern (z.B. mit Ihrem Team) oder --extern (z.B. mit Ihren Kunden) kommunizieren?' // ); if (~befehl.indexOf("--STRATEGIE")) { versuch = true; if ((text5) && (text5 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3) }).then(function(){ return bot.say(text4) }).then(function(){ return bot.say(text5); }); } else if ((text4) && (text4 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3) }).then(function(){ return bot.say(text4); }); } else if ((text3) && (text3 != "")) { bot.say(text1).then(function(){ return bot.say(text2) }).then(function(){ return bot.say(text3); }); } else if ((text2) && (text2 != "")) { bot.say(text1).then(function(){ return bot.say(text2); }); } else if ((text1) && (text1 != "")) { bot.say(text1); } } } <add> <add>'use strict'; <add> <add> const Script = require('smooch-bot').Script; <add> <add>// Bots <add> const AndreasSefzig = "[AndreasSefzig] "; <add> const SefzigBot = "[SefzigBot] "; <add> const EmpfangsBot = "[EmpfangsBot] "; <add> const KreationsBot = "[KreationsBot] "; <add> const BeratungsBot = "[BeratungsBot] "; <add> const KonzeptionsBot = "[KonzeptionsBot] "; <add> const StrategieBot = "[StrategieBot] "; <add> const TechnikBot = "[TechnikBot] "; <add> const LinkBot = "[LinkBot] "; <add> const TextBot = "[TextBot] "; <add> const SlackBot = "[SlackBot] "; <add> <add>// Variablen <add> var versuche_max = 3; <add> var versuche = 0; <add> var zuletzt = ""; <add> var bekannt = false; <add> <add>// Daten <add> var vorname = "Unbekannter"; <add> var nachname = "Besucher"; <add> var email = "[email protected]"; <add> var emailkorrekt = true; <add> <add>// Konversationen <add> module.exports = new Script({ <add> <add> // --------------- <add> // GESPRÄCH ANFANG <add> // --------------- <add> <add> processing: { <add> <add> prompt: (bot) => bot.say(EmpfangsBot+'Nicht so schnell bitte...'), <add> receive: () => 'processing' <add> <add> }, <add> <add> start: { <add> <add> // prompt: (bot) => bot.say(EmpfangsBot+'Starte...'), <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim()); <add> <add> // Nächster Schritt default <add> var dann = "empfang"; <add> <add> if (~befehl.indexOf("Weiterleiten zu:")) { <add> <add> // bot.say(EmpfangsBot+'Ich leite Sie weiter.'); <add> <add> } <add> else { <add> <add> if (bekannt == false) { <add> <add> return bot.say(EmpfangsBot+' Willkommen in der Vorlage des --Chatraums. ').then(() => bot.say(EmpfangsBot+' Wir sind 3 Bots: Ich bin Alice, Barbara ist im --Verkauf und Cynthia macht unser --Marketing. ')).then(() => bot.say(EmpfangsBot+' Unterhalten Sie sich mit uns, indem Sie die farbig hinterlegten Wörter schreiben, klicken oder berühren! ')).then(() => bot.say(EmpfangsBot+' Ich habe rechts das Menü für Sie geöffnet. Sie können es mit dem Button oben rechts bedienen - oder indem Sie --Menü schreiben. [Javascript:menu(an)] ')).then(() => 'empfang'); <add> } <add> else { <add> <add> return bot.say(EmpfangsBot+' Willkommen zurück! Sprechen Sie mit mir über --Chatraum! ').then(() => bot.say(EmpfangsBot+' Oder sprechen Sie mit den anderen Bots über --Verkauf und --Marketing. ')).then(() => 'empfang'); <add> } <add> <add> } <add> <add> return bot.setProp('empfangen', 'ja') <add> .then(() => dann); <add> <add> } <add> }, <add> <add> // ------------------------- <add> // Onboarding <add> // ------------------------- <add> <add> name: { <add> <add> receive: (bot, message) => { <add> <add> var antwort = befehlWort(message.text.trim().toUpperCase()); <add> var dann = "name"; <add> <add> if ((antwort == "--JA") || <add> (antwort == "--NAME") || <add> (antwort == "--ÄNDERN")) { <add> <add> bot.say(EmpfangsBot+'Wir werden sorgsam mit Ihren Daten umgehen.'); <add> dann = "vorname"; <add> <add> } <add> if ((antwort == "--NEIN") || <add> (antwort == "--EMPFANG") || <add> (antwort == "--ABBRECHEN")) { <add> <add> bot.say(EmpfangsBot+'Gehen wir zurück zum --Empfang.'); <add> dann = "empfang"; <add> <add> } <add> if ((antwort == "--EMAIL") || <add> (antwort == "--E-MAIL")) { <add> <add> bot.say(EmpfangsBot+'Wir geben Ihre Adresse nicht weiter.'); <add> dann = "emailadresse"; <add> <add> } <add> <add> return bot.setProp('name_eingabe', 'tmp') <add> .then(() => dann); <add> } <add> }, <add> <add> vorname: { <add> <add> prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'), <add> receive: (bot, message) => { <add> <add> vorname = message.text; <add> vorname = vorname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); <add> <add> return bot.setProp('vorname', vorname) <add> .then(() => bot.say(EmpfangsBot+''+vorname+', prima.')) <add> .then(() => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen? [Javascript:cookies(vorname,'+vorname+')] ')) <add> .then(() => 'nachname'); <add> } <add> }, <add> <add> nachname: { <add> <add> receive: (bot, message) => { <add> <add> nachname = message.text; <add> nachname = nachname.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } ); <add> nachname = nachname.replace("--",""); <add> <add> bot.setProp('nachname', nachname); <add> return bot.getProp('vorname') <add> .then((vorname) => bot.say(EmpfangsBot+'Sie heissen also '+vorname+' '+nachname+'. Bitte geben Sie nun Ihre E-Mail-Adresse ein (sie können auch --abbrechen). [Javascript:cookies(nachname,'+nachname+')] ')) <add> .then(() => 'emailadresse'); <add> <add> } <add> }, <add> <add> emailadresse: { <add> <add> receive: (bot, message) => { <add> <add> email = message.text; <add> <add> // emailkorrekt = email.test(emailregex); <add> emailkorrekt = true; <add> <add> if (emailkorrekt == true) { <add> <add> return bot.setProp('email', email) <add> .then(() => bot.say(EmpfangsBot+''+email+' ist eine valide E-Mail-Adresse. [Javascript:cookies(email,'+email+')] ')) <add> .then(() => bot.say(EmpfangsBot+'Schreiben Sie --E-Mail, um sie zu ändern. Oder lassen Sie uns zurück zum --Empfang gehen.')) <add> .then(() => 'empfang'); <add> <add> } <add> else { <add> <add> return bot.say(+' 0 ').then(() => bot.say(EmpfangsBot+' Bitte geben Sie Ihre E-Mail-Adresse nochmal ein - oder lassen Sie uns zum --Empfang zurückkehren. ')).then(() => 'emailadresse'); <add> } <add> } <add> }, <add> <add> // --------------------------- <add> // Empfang (Alice) <add> // --------------------------- <add> // - name_klein: empfang <add> // - name_kamel: Empfang <add> // - name_gross: EMPFANG <add> // - frau_klein: alice <add> // - frau_kamel: Alice <add> // - frau_gross: ALICE <add> // - bot_name: EmpfangsBot <add> // - bot_klein: empfangsbot <add> // - bot_kamel: Empfangsbot <add> // - bot_gross: EMPFANGSBOT <add> // --------------------------- <add> <add> empfang: { <add> <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim().toUpperCase()); <add> <add> // Nächster Schritt default <add> var dann = "empfang"; <add> <add> // Nicht-Befehl-Eingaben mitzählen <add> var versuch = false; <add> <add> // Default-Zurück <add> var zuruck = "Empfang"; <add> <add> // Zuletzt Varianten <add> var zuletzt_dann = dann; <add> var zuletzt_klein = zuletzt_dann.toLowerCase(); <add> var zuletzt_gross = zuletzt_dann.toUpperCase(); <add> var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); <add> <add> // ----------------- <add> // Befehle <add> // ----------------- <add> <add> if ("empfang" != "empfang") { <add> <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(EmpfangsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Empfang? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} <add> } <add> <add> if (zuletzt_kamel != "Empfang") { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(EmpfangsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'empfang');} <add> } <add> <add> if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'empfang');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'empfang');} <add> // ----------------- <add> // Onboarding <add> // ----------------- <add> <add> if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(EmpfangsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} <add> } <add> <add> // ----------------- <add> // Kontakt <add> // ----------------- <add> <add> if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(EmpfangsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(EmpfangsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'empfang');} <add> if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(EmpfangsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'empfang');} <add> if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(EmpfangsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'empfang');} <add> if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(EmpfangsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'empfang');} <add> // ----------------- <add> // Über uns <add> // ----------------- <add> <add> if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(EmpfangsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(EmpfangsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'empfang');} <add> // Produkte <add> if ("empfang" != "verkauf") { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(EmpfangsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} <add> } <add> else { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} <add> } <add> <add> // ----------------- <add> // Funktionen <add> // ----------------- <add> <add> if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(EmpfangsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} <add> if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(EmpfangsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(EmpfangsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'empfang');} <add> // Stile <add> if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'empfang');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'empfang');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'empfang');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(EmpfangsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'empfang');} <add> // ----------------- <add> // Bots <add> // ----------------- <add> <add> if (zuletzt_klein != "empfang") { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Alice. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } <add> <add> if (zuletzt_klein != "verkauf") { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Barbara. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } <add> <add> if (zuletzt_klein != "marketing") { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Cynthia. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } <add> <add> // Vorlage (Gewerk, Name) <add> if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(EmpfangsBot+' Ich übergebe an Name. Schreiben Sie --Empfang, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} <add> // ----------------- <add> // System <add> // ----------------- <add> <add> if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit meinen Kolleginnen in --Verkauf und --Marketing. ').then(() => bot.say(EmpfangsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'empfang');} <add> if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Ich bin Alice, der Empfangs-Bot. ').then(() => bot.say(VerkaufsBot+' Alice ist eine offene Person, die Besucher auf ihre hilfsbereite Art in Empfang nimmt. ')).then(() => bot.say(EmpfangsBot+' Ich leite weiter zu meinen Kolleginnen und übernehme einfache Aufgaben, wie z.B. Ihren --Namen zu erfassen. ')).then(() => 'empfang');} <add> // ----------------- <add> // Inhalte <add> // ----------------- <add> <add> if (~befehl.indexOf("--DATEN")) { versuch = true; return bot.say(EmpfangsBot+' Lassen Sie uns Ihre Daten durchgehen. ').then(() => 'name');} <add> // ----------------- <add> // Vorlage <add> // ----------------- <add> <add> if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(EmpfangsBot+' Text Vorlage 1. ').then(() => 'empfang');} <add> <add> // ----------------- <add> // Bot aus <add> // ----------------- <add> <add> // Zurück merken <add> zuletzt = zuruck; <add> <add> // Irrläufer <add> if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { <add> bot.say(EmpfangsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } <add> } <add> <add> // Weiterleiten <add> return bot.setProp('empfang', 'gesprochen') <add> .then(() => dann); <add> <add> } <add> <add> }, <add> <add> // --------------------------- <add> // Beratung (Barbara) <add> // --------------------------- <add> // - name_klein: beratung <add> // - name_kamel: Beratung <add> // - name_gross: BERATUNG <add> // - frau_klein: barbara <add> // - frau_kamel: Barbara <add> // - frau_gross: BARBARA <add> // - bot_name: BeratungsBot <add> // - bot_klein: beratungsbot <add> // - bot_kamel: Beratungsbot <add> // - bot_gross: BERATUNGSBOT <add> // --------------------------- <add> <add> beratung: { <add> <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim().toUpperCase()); <add> <add> // Nächster Schritt default <add> var dann = "beratung"; <add> <add> // Nicht-Befehl-Eingaben mitzählen <add> var versuch = false; <add> <add> // Default-Zurück <add> var zuruck = "Beratung"; <add> <add> // Zuletzt Varianten <add> var zuletzt_dann = dann; <add> var zuletzt_klein = zuletzt_dann.toLowerCase(); <add> var zuletzt_gross = zuletzt_dann.toUpperCase(); <add> var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); <add> <add> // ----------------- <add> // Befehle <add> // ----------------- <add> <add> if ("beratung" != "empfang") { <add> <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(BeratungsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Beratung? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} <add> } <add> <add> if (zuletzt_kamel != "Beratung") { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(BeratungsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'beratung');} <add> } <add> <add> if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'beratung');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'beratung');} <add> // ----------------- <add> // Onboarding <add> // ----------------- <add> <add> if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(BeratungsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} <add> } <add> <add> // ----------------- <add> // Kontakt <add> // ----------------- <add> <add> if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(BeratungsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(BeratungsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'beratung');} <add> if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(BeratungsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'beratung');} <add> if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(BeratungsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'beratung');} <add> if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(BeratungsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'beratung');} <add> // ----------------- <add> // Über uns <add> // ----------------- <add> <add> if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(BeratungsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(BeratungsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'beratung');} <add> // Produkte <add> if ("beratung" != "verkauf") { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} <add> } <add> else { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} <add> } <add> <add> // ----------------- <add> // Funktionen <add> // ----------------- <add> <add> if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(BeratungsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} <add> if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(BeratungsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(BeratungsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'beratung');} <add> // Stile <add> if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'beratung');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'beratung');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'beratung');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(BeratungsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'beratung');} <add> // ----------------- <add> // Bots <add> // ----------------- <add> <add> if (zuletzt_klein != "empfang") { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Alice. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } <add> <add> if (zuletzt_klein != "verkauf") { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Barbara. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } <add> <add> if (zuletzt_klein != "marketing") { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Cynthia. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } <add> <add> // Vorlage (Gewerk, Name) <add> if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(BeratungsBot+' Ich übergebe an Name. Schreiben Sie --Beratung, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} <add> // ----------------- <add> // System <add> // ----------------- <add> <add> if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(BeratungsBot+' Sprechen Sie mit mir über --Produkte und --Beratung. ').then(() => bot.say(BeratungsBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'beratung');} <add> if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(BeratungsBot+' Ich bin Barbara, der Verkaufs-Bot. ').then(() => bot.say(MarketingBot+' Barbara ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(BeratungsBot+' Ich kenne mich mit unseren --Produkten aus und --berate Sie gern. ')).then(() => 'beratung');} <add> // ----------------- <add> // Inhalte <add> // ----------------- <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(BeratungsBot+' Text Produkt. ').then(() => 'beratung');} <add> if (~befehl.indexOf("--BERAT")) { versuch = true; return bot.say(BeratungsBot+' Text Beratung. ').then(() => 'beratung');} <add> // ----------------- <add> // Vorlage <add> // ----------------- <add> <add> if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(BeratungsBot+' Text Vorlage 1. ').then(() => 'beratung');} <add> <add> // ----------------- <add> // Bot aus <add> // ----------------- <add> <add> // Zurück merken <add> zuletzt = zuruck; <add> <add> // Irrläufer <add> if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { <add> bot.say(BeratungsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } <add> } <add> <add> // Weiterleiten <add> return bot.setProp('beratung', 'gesprochen') <add> .then(() => dann); <add> <add> } <add> <add> }, <add> <add> // --------------------------- <add> // Technik (Cynthia) <add> // --------------------------- <add> // - name_klein: technik <add> // - name_kamel: Technik <add> // - name_gross: TECHNIK <add> // - frau_klein: cynthia <add> // - frau_kamel: Cynthia <add> // - frau_gross: CYNTHIA <add> // - bot_name: TechnikBot <add> // - bot_klein: technikbot <add> // - bot_kamel: Technikbot <add> // - bot_gross: TECHNIKBOT <add> // --------------------------- <add> <add> technik: { <add> <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim().toUpperCase()); <add> <add> // Nächster Schritt default <add> var dann = "technik"; <add> <add> // Nicht-Befehl-Eingaben mitzählen <add> var versuch = false; <add> <add> // Default-Zurück <add> var zuruck = "Technik"; <add> <add> // Zuletzt Varianten <add> var zuletzt_dann = dann; <add> var zuletzt_klein = zuletzt_dann.toLowerCase(); <add> var zuletzt_gross = zuletzt_dann.toUpperCase(); <add> var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); <add> <add> // ----------------- <add> // Befehle <add> // ----------------- <add> <add> if ("technik" != "empfang") { <add> <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(TechnikBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Technik? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} <add> } <add> <add> if (zuletzt_kamel != "Technik") { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(TechnikBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'technik');} <add> } <add> <add> if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'technik');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(TechnikBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'technik');} <add> // ----------------- <add> // Onboarding <add> // ----------------- <add> <add> if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(TechnikBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} <add> } <add> <add> // ----------------- <add> // Kontakt <add> // ----------------- <add> <add> if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(TechnikBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(TechnikBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'technik');} <add> if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(TechnikBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'technik');} <add> if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(TechnikBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'technik');} <add> if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(TechnikBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'technik');} <add> // ----------------- <add> // Über uns <add> // ----------------- <add> <add> if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(TechnikBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(TechnikBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'technik');} <add> // Produkte <add> if ("technik" != "verkauf") { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(TechnikBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} <add> } <add> else { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} <add> } <add> <add> // ----------------- <add> // Funktionen <add> // ----------------- <add> <add> if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(TechnikBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} <add> if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(TechnikBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(TechnikBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'technik');} <add> // Stile <add> if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'technik');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'technik');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'technik');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(TechnikBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'technik');} <add> // ----------------- <add> // Bots <add> // ----------------- <add> <add> if (zuletzt_klein != "empfang") { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Alice. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } <add> <add> if (zuletzt_klein != "verkauf") { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Barbara. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } <add> <add> if (zuletzt_klein != "marketing") { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Cynthia. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } <add> <add> // Vorlage (Gewerk, Name) <add> if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(TechnikBot+' Ich übergebe an Name. Schreiben Sie --Technik, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} <add> // ----------------- <add> // System <add> // ----------------- <add> <add> if (~befehl.indexOf("--BEFEHLE")) { versuch = true; return bot.say(TechnikBot+' Sprechen Sie mit mir über --Facebook und --Umfrage. ').then(() => bot.say(TechnikBot+' Weitere Funktionen: --Kontakt, --Newsletter, --Mobil und --Über. ')).then(() => 'technik');} <add> if (~befehl.indexOf("--ÜBER")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(TechnikBot+' Ich bin Cynthia, der Marketing-Bot. ').then(() => bot.say(EmpfangsBot+' Cynthia ist eine Person, zu der ich später mehr sagen kann (folgt). ')).then(() => bot.say(TechnikBot+' Ich mache unser --Facebook und habe eine --Umfrage. ')).then(() => 'technik');} <add> // ----------------- <add> // Inhalte <add> // ----------------- <add> <add> if (~befehl.indexOf("--FACEBOOK")) { versuch = true; return bot.say(TechnikBot+' Text Facebook. ').then(() => 'technik');} <add> if (~befehl.indexOf("--UMFRAGE")) { versuch = true; return bot.say(TechnikBot+' Text Umfrage. ').then(() => 'technik');} <add> // ----------------- <add> // Vorlage <add> // ----------------- <add> <add> if (~befehl.indexOf("--VORLAGE")) { versuch = true; return bot.say(TechnikBot+' Text Vorlage 1. ').then(() => 'technik');} <add> <add> // ----------------- <add> // Bot aus <add> // ----------------- <add> <add> // Zurück merken <add> zuletzt = zuruck; <add> <add> // Irrläufer <add> if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { <add> bot.say(TechnikBot+'Suchen Sie meine --Befehle?'); versuche = 0; } <add> } <add> <add> // Weiterleiten <add> return bot.setProp('technik', 'gesprochen') <add> .then(() => dann); <add> <add> } <add> <add> }, <add> <add> // --------------------------- <add> // Kreation (Doris) <add> // --------------------------- <add> // - name_klein: kreation <add> // - name_kamel: Kreation <add> // - name_gross: KREATION <add> // - frau_klein: doris <add> // - frau_kamel: Doris <add> // - frau_gross: DORIS <add> // - bot_name: KreationsBot <add> // - bot_klein: kreationsbot <add> // - bot_kamel: Kreationsbot <add> // - bot_gross: KREATIONSBOT <add> // --------------------------- <add> <add> kreation: { <add> <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim().toUpperCase()); <add> <add> // Nächster Schritt default <add> var dann = "kreation"; <add> <add> // Nicht-Befehl-Eingaben mitzählen <add> var versuch = false; <add> <add> // Default-Zurück <add> var zuruck = "Kreation"; <add> <add> // Zuletzt Varianten <add> var zuletzt_dann = dann; <add> var zuletzt_klein = zuletzt_dann.toLowerCase(); <add> var zuletzt_gross = zuletzt_dann.toUpperCase(); <add> var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); <add> <add> // ----------------- <add> // Befehle <add> // ----------------- <add> <add> if ("kreation" != "empfang") { <add> <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KreationsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Kreation? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} <add> } <add> <add> if (zuletzt_kamel != "Kreation") { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KreationsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'kreation');} <add> } <add> <add> if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'kreation');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KreationsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'kreation');} <add> // ----------------- <add> // Onboarding <add> // ----------------- <add> <add> if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KreationsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} <add> } <add> <add> // ----------------- <add> // Kontakt <add> // ----------------- <add> <add> if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KreationsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KreationsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'kreation');} <add> if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KreationsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'kreation');} <add> if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KreationsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'kreation');} <add> if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KreationsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'kreation');} <add> // ----------------- <add> // Über uns <add> // ----------------- <add> <add> if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KreationsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KreationsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'kreation');} <add> // Produkte <add> if ("kreation" != "verkauf") { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KreationsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} <add> } <add> else { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} <add> } <add> <add> // ----------------- <add> // Funktionen <add> // ----------------- <add> <add> if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KreationsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} <add> if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KreationsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KreationsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'kreation');} <add> // Stile <add> if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'kreation');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'kreation');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'kreation');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KreationsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'kreation');} <add> // ----------------- <add> // Bots <add> // ----------------- <add> <add> if (zuletzt_klein != "empfang") { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Alice. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } <add> <add> if (zuletzt_klein != "verkauf") { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Barbara. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } <add> <add> if (zuletzt_klein != "marketing") { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Cynthia. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } <add> <add> // Vorlage (Gewerk, Name) <add> if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KreationsBot+' Ich übergebe an Name. Schreiben Sie --Kreation, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} <add> <add> // ----------------- <add> // Bot aus <add> // ----------------- <add> <add> // Zurück merken <add> zuletzt = zuruck; <add> <add> // Irrläufer <add> if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { <add> bot.say(KreationsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } <add> } <add> <add> // Weiterleiten <add> return bot.setProp('kreation', 'gesprochen') <add> .then(() => dann); <add> <add> } <add> <add> }, <add> <add> // --------------------------- <add> // Konzeption (Erika) <add> // --------------------------- <add> // - name_klein: konzeption <add> // - name_kamel: Konzeption <add> // - name_gross: KONZEPTION <add> // - frau_klein: erika <add> // - frau_kamel: Erika <add> // - frau_gross: ERIKA <add> // - bot_name: KonzeptionsBot <add> // - bot_klein: konzeptionsbot <add> // - bot_kamel: Konzeptionsbot <add> // - bot_gross: KONZEPTIONSBOT <add> // --------------------------- <add> <add> konzeption: { <add> <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim().toUpperCase()); <add> <add> // Nächster Schritt default <add> var dann = "konzeption"; <add> <add> // Nicht-Befehl-Eingaben mitzählen <add> var versuch = false; <add> <add> // Default-Zurück <add> var zuruck = "Konzeption"; <add> <add> // Zuletzt Varianten <add> var zuletzt_dann = dann; <add> var zuletzt_klein = zuletzt_dann.toLowerCase(); <add> var zuletzt_gross = zuletzt_dann.toUpperCase(); <add> var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); <add> <add> // ----------------- <add> // Befehle <add> // ----------------- <add> <add> if ("konzeption" != "empfang") { <add> <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(KonzeptionsBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Konzeption? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} <add> } <add> <add> if (zuletzt_kamel != "Konzeption") { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(KonzeptionsBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'konzeption');} <add> } <add> <add> if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'konzeption');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'konzeption');} <add> // ----------------- <add> // Onboarding <add> // ----------------- <add> <add> if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(KonzeptionsBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} <add> } <add> <add> // ----------------- <add> // Kontakt <add> // ----------------- <add> <add> if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(KonzeptionsBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(KonzeptionsBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'konzeption');} <add> if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(KonzeptionsBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'konzeption');} <add> if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(KonzeptionsBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'konzeption');} <add> if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(KonzeptionsBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'konzeption');} <add> // ----------------- <add> // Über uns <add> // ----------------- <add> <add> if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(KonzeptionsBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(KonzeptionsBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'konzeption');} <add> // Produkte <add> if ("konzeption" != "verkauf") { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(KonzeptionsBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} <add> } <add> else { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} <add> } <add> <add> // ----------------- <add> // Funktionen <add> // ----------------- <add> <add> if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(KonzeptionsBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} <add> if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(KonzeptionsBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(KonzeptionsBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'konzeption');} <add> // Stile <add> if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'konzeption');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'konzeption');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'konzeption');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(KonzeptionsBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'konzeption');} <add> // ----------------- <add> // Bots <add> // ----------------- <add> <add> if (zuletzt_klein != "empfang") { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Alice. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } <add> <add> if (zuletzt_klein != "verkauf") { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Barbara. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } <add> <add> if (zuletzt_klein != "marketing") { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Cynthia. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } <add> <add> // Vorlage (Gewerk, Name) <add> if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(KonzeptionsBot+' Ich übergebe an Name. Schreiben Sie --Konzeption, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} <add> <add> // ----------------- <add> // Bot aus <add> // ----------------- <add> <add> // Zurück merken <add> zuletzt = zuruck; <add> <add> // Irrläufer <add> if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { <add> bot.say(KonzeptionsBot+'Suchen Sie meine --Befehle?'); versuche = 0; } <add> } <add> <add> // Weiterleiten <add> return bot.setProp('konzeption', 'gesprochen') <add> .then(() => dann); <add> <add> } <add> <add> }, <add> <add> // --------------------------- <add> // Strategie (Feline) <add> // --------------------------- <add> // - name_klein: strategie <add> // - name_kamel: Strategie <add> // - name_gross: STRATEGIE <add> // - frau_klein: feline <add> // - frau_kamel: Feline <add> // - frau_gross: FELINE <add> // - bot_name: StrategieBot <add> // - bot_klein: strategiebot <add> // - bot_kamel: Strategiebot <add> // - bot_gross: STRATEGIEBOT <add> // --------------------------- <add> <add> strategie: { <add> <add> receive: (bot, message) => { <add> <add> // Befehl normalisieren <add> var befehl = befehlWort(message.text.trim().toUpperCase()); <add> <add> // Nächster Schritt default <add> var dann = "strategie"; <add> <add> // Nicht-Befehl-Eingaben mitzählen <add> var versuch = false; <add> <add> // Default-Zurück <add> var zuruck = "Strategie"; <add> <add> // Zuletzt Varianten <add> var zuletzt_dann = dann; <add> var zuletzt_klein = zuletzt_dann.toLowerCase(); <add> var zuletzt_gross = zuletzt_dann.toUpperCase(); <add> var zuletzt_kamel = zuletzt_dann.charAt(0).toUpperCase() + zuletzt_dann.slice(1); <add> <add> // ----------------- <add> // Befehle <add> // ----------------- <add> <add> if ("strategie" != "empfang") { <add> <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');}if (~befehl.indexOf("--ABBRECHEN")) { versuch = true; return bot.say(StrategieBot+' Bis später! ').then(() => bot.say(EmpfangsBot+' Willkommen zurück! Wie war es im --Strategie? Schreiben Sie --Befehle um zu sehen, was ich Ihnen sonst noch zeigen kann. ')).then(() => 'empfang');} <add> } <add> <add> if (zuletzt_kamel != "Strategie") { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--ZURÜCK")) { versuch = true; return bot.say(StrategieBot+' Wollen Sie zurück zum --Empfang? ').then(() => 'strategie');} <add> } <add> <add> if (~befehl.indexOf("--MENÜAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAN")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü eingeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUAUS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü ausgeschaltet. ').then(() => 'strategie');} if (~befehl.indexOf("--MENÜ")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENU")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');}if (~befehl.indexOf("--MENUE")) { versuch = true; return bot.say(StrategieBot+' [Javascript:menu()] Menü umgeschaltet. ').then(() => 'strategie');} <add> // ----------------- <add> // Onboarding <add> // ----------------- <add> <add> if ((vorname) && (vorname != "") && (vorname != "Unbekannter") && (nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((vorname) && (vorname != "") && (vorname != "Unbekannter")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else if ((nachname) && (nachname != "") && (nachname != "Besucher")) { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; } <add> } <add> else { <add> <add> if (~befehl.indexOf("--NAME")) { versuch = true; return bot.say(StrategieBot+' Wir kennen Ihren Namen noch nicht. ').then(() => 'vorname');} <add> } <add> <add> // ----------------- <add> // Kontakt <add> // ----------------- <add> <add> if (~befehl.indexOf("--KONTAKT")) { versuch = true; return bot.say(StrategieBot+' Alle unsere Kontaktwege: [Text:Kontakt,RobogeddonKontakt] ').then(() => bot.say(StrategieBot+' Wollen Sie --telefonieren, --mailen oder --twittern? ')).then(() => 'strategie');} <add> if (~befehl.indexOf("--TELEFON")) { versuch = true; return bot.say(StrategieBot+' Rufen Sie Andreas Sefzig an: [Telefon:+49 151 15920082] ').then(() => 'strategie');} <add> if (~befehl.indexOf("--MAIL")) { versuch = true; return bot.say(StrategieBot+' Schreiben Sie uns eine Email: [Email:[email protected]] ').then(() => 'strategie');} <add> if (~befehl.indexOf("--TWITTER")) { versuch = true; return bot.say(StrategieBot+' Senden Sie uns einen Tweet: [Link:PM in Twitter öffnen,RobogeddonTweet] ').then(() => 'strategie');} <add> // ----------------- <add> // Über uns <add> // ----------------- <add> <add> if (~befehl.indexOf("--CHATRAUM")) { versuch = true; return bot.say(StrategieBot+' Der Chatraum ist ein Produkt der Chatbot-Agentur #Robogeddon. ').then(() => bot.say(StrategieBot+' Lassen Sie uns über unsere --Produkte sprechen. Oder wollen Sie eine --Beratung? ')).then(() => 'strategie');} <add> // Produkte <add> if ("strategie" != "verkauf") { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(StrategieBot+' Die Produkte lassen Sie sich besser von Barbara erklären. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo! Mehr über unsere --Produkte folgt... ')).then(() => 'verkauf');} <add> } <add> else { <add> <add> if (~befehl.indexOf("--PRODUKT")) { versuch = true; return bot.say(VerkaufsBot+' Mehr über unsere --Produkte folgt... ').then(() => 'verkauf');} <add> } <add> <add> // ----------------- <add> // Funktionen <add> // ----------------- <add> <add> if (~befehl.indexOf("--NEWSLETTER")) { versuch = true; return bot.say(StrategieBot+' Ja, bestellen Sie unseren Newsletter! ').then(() => 'vorname');} <add> if (~befehl.indexOf("--MOBIL")) { versuch = true; return bot.say(StrategieBot+' Diesen Chat mobil öffnen: [Qr:http://chatraum.herokuapp.com/] ').then(() => bot.say(StrategieBot+' Oder öffnen Sie [Textlink:Chatraum.herokuapp.com,http://chatraum.herokuapp.com] in Ihrem mobilen Browser. ')).then(() => 'strategie');} <add> // Stile <add> if (~befehl.indexOf("--TAG")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(tag)] Stil: Tag. ').then(() => 'strategie');} if (~befehl.indexOf("--NACHT")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(nacht)] Stil: Nacht. ').then(() => 'strategie');} if (~befehl.indexOf("--ROBOS")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(robogeddon)] Stil: Robogeddon. ').then(() => 'strategie');} if (~befehl.indexOf("--HX")) { versuch = true; return bot.say(StrategieBot+' [Javascript:stil(hacks)] Stil: Hx. ').then(() => 'strategie');} <add> // ----------------- <add> // Bots <add> // ----------------- <add> <add> if (zuletzt_klein != "empfang") { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Alice. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(EmpfangsBot+' Hallo, ich bin Alice, der Empfangs-Bot. Darf ich Ihnen die Bots aus --Verkauf und --Marketing vorstellen? ')).then(() => 'empfang');} } else { <add> if (~befehl.indexOf("--EMPFANG")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');}if (~befehl.indexOf("--ALICE")) { versuch = true; return bot.say(EmpfangsBot+' Sprechen Sie mit mir über den --Chatraum - oder mit den anderen Bots über --Verkauf oder --Marketing! ').then(() => 'empfang');} } <add> <add> if (zuletzt_klein != "verkauf") { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Barbara. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(VerkaufsBot+' Hallo, ich bin Barbara, der Verkaufs-Bot. Ich möchte Ihnen unsere --Produkte zeigen und Sie --beraten! ')).then(() => 'verkauf');} } else { <add> if (~befehl.indexOf("--VERKAUF")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');}if (~befehl.indexOf("--BARBARA")) { versuch = true; return bot.say(VerkaufsBot+' Ich möchte Ihnen unsere --Produkte und meine --Beratung nahelegen! ').then(() => 'verkauf');} } <add> <add> if (zuletzt_klein != "marketing") { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Cynthia. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(MarketingBot+' Hallo, ich bin Cynthia, der Marketing-Bot. Ich möchte Ihnen unser --Facebook empfehlen und möchte Sie bitten, an unserer --Umfrage teilzunehmen! ')).then(() => 'marketing');} } else { <add> if (~befehl.indexOf("--MARKETING")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');}if (~befehl.indexOf("--CYNTHIA")) { versuch = true; return bot.say(MarketingBot+' Ich möchte Ihnen unser --Facebook empfehlen und habe eine --Umfrage. ').then(() => 'marketing');} } <add> <add> // Vorlage (Gewerk, Name) <add> if (~befehl.indexOf("--GEWERK")) { versuch = true; return bot.say(StrategieBot+' Ich übergebe an Name. Schreiben Sie --Strategie, um wieder mit mir zu sprechen. ').then(() => bot.say(GewerksBot+' Hallo Gewerk Text 1: Hallo, ich bin Name, der Gewerks-Bot. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 2: --Befehle folgt. ')).then(() => bot.say(GewerksBot+' Hallo Gewerk Text 3. ')).then(() => 'gewerk');} <add> <add> // ----------------- <add> // Bot aus <add> // ----------------- <add> <add> // Zurück merken <add> zuletzt = zuruck; <add> <add> // Irrläufer <add> if (versuch == true) { versuche = 0; } else { versuche++; if (versuche == versuche_max) { <add> bot.say(StrategieBot+'Suchen Sie meine --Befehle?'); versuche = 0; } <add> } <add> <add> // Weiterleiten <add> return bot.setProp('strategie', 'gesprochen') <add> .then(() => dann); <add> <add> } <add> <add> }, <add> <add> finish: { <add> receive: (bot, message) => { <add> return bot.getProp('name') <add> .then(() => 'finish'); <add> } <add> } <add> <add> // -------------- <add> // GESPRÄCH AUS <add> // -------------- <add> <add> }); <add> <add> // Befehle <add> function befehlWort(befehl) { <add> <add> // Wenn die Nachricht nur ein Wort ist <add> var test = befehl.split(" "); <add> if ((!test[1]) || (test[1] == "")) { <add> <add> // In Befehl umwandeln <add> befehl = befehl.replace("--", ""); <add> befehl = "--"+befehl; <add> <add> // Satzzeichen entfernen <add> befehl = befehl.replace(".", ""); <add> befehl = befehl.replace("!", ""); <add> befehl = befehl.replace("?", ""); <add> <add> } <add> <add> return befehl; <add> <add> } <add> <add> // Bots vereinfachen <add> function sagenhaft(befehl, dann, bot, text1, text2, text3, text4, text5) { <add> // sagenhaft('Strategie', dann, bot, <add> // SefzigBot+'Chatten ist die häufigste digitale Beschäftigung in Deutschland: [Text:Aktuelle Statistiken,RobogeddonChatten] Ein weltweiter --Trend mit erheblichen absehbaren Auswirkungen auf die Benutzeroberflächen des Internets.', <add> // SefzigBot+'Chat-Bots gibt es schon --lange. Sie werden gerade jetzt für das Marketing interessant, weil die meisten Menschen mit Chatten vertraut sind und große Anwendungen wie --Facebook, --Slack u.a. ihre Plattformen für Bots öffnen.', <add> // SefzigBot+'Interessieren Sie sich eher für Bots, die --intern (z.B. mit Ihrem Team) oder --extern (z.B. mit Ihren Kunden) kommunizieren?' <add> // ); <add> if (~befehl.indexOf("--STRATEGIE")) { <add> <add> versuch = true; <add> <add> if ((text5) && (text5 != "")) { <add> bot.say(text1).then(function(){ <add> return bot.say(text2) }).then(function(){ <add> return bot.say(text3) }).then(function(){ <add> return bot.say(text4) }).then(function(){ <add> return bot.say(text5); }); <add> } <add> else if ((text4) && (text4 != "")) { <add> bot.say(text1).then(function(){ <add> return bot.say(text2) }).then(function(){ <add> return bot.say(text3) }).then(function(){ <add> return bot.say(text4); }); <add> } <add> else if ((text3) && (text3 != "")) { <add> bot.say(text1).then(function(){ <add> return bot.say(text2) }).then(function(){ <add> return bot.say(text3); }); <add> } <add> else if ((text2) && (text2 != "")) { <add> bot.say(text1).then(function(){ <add> return bot.say(text2); }); <add> } <add> else if ((text1) && (text1 != "")) { <add> bot.say(text1); <add> } <add> <add> } <add> <add> } <add>
Java
bsd-3-clause
db35f2eb7bd24b1c662c63e98b89a3b55483a5df
0
markles/GeoGit,annacarol/GeoGig,annacarol/GeoGig,boundlessgeo/GeoGig,annacarol/GeoGig,markles/GeoGit,boundlessgeo/GeoGig,markles/GeoGit,markles/GeoGit,boundlessgeo/GeoGig,markles/GeoGit
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the GNU GPL 2.0 license, available at the root * application directory. */ package org.geogit.rest.repository; import static org.geogit.rest.repository.RESTUtils.getGeogit; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map.Entry; import java.util.UUID; import org.geogit.api.GeoGIT; import org.geogit.api.NodeRef; import org.geogit.api.ObjectId; import org.geogit.api.RevCommit; import org.geogit.api.RevFeature; import org.geogit.api.RevFeatureBuilder; import org.geogit.api.RevFeatureType; import org.geogit.api.RevObject; import org.geogit.api.RevTree; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.storage.FieldType; import org.geogit.web.api.CommandSpecException; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.geometry.jts.WKTReader2; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.PropertyDescriptor; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Resource; import org.restlet.resource.StringRepresentation; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.io.Closeables; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * */ public class MergeFeatureResource extends Resource { @Override public boolean allowPost() { return true; } private Optional<NodeRef> parseID(ObjectId commitId, String path, GeoGIT geogit) { Optional<RevObject> object = geogit.command(RevObjectParse.class).setObjectId(commitId) .call(); RevCommit commit = null; if (object.isPresent() && object.get() instanceof RevCommit) { commit = (RevCommit) object.get(); } else { throw new CommandSpecException("Couldn't resolve id: " + commitId.toString() + " to a commit"); } object = geogit.command(RevObjectParse.class).setObjectId(commit.getTreeId()).call(); if (object.isPresent()) { RevTree tree = (RevTree) object.get(); return geogit.command(FindTreeChild.class).setParent(tree).setChildPath(path).call(); } else { throw new CommandSpecException("Couldn't resolve commit's treeId"); } } public void post(Representation entity) { InputStream input = null; try { input = getRequest().getEntity().getStream(); final GeoGIT ggit = getGeogit(getRequest()).get(); final Reader body = new InputStreamReader(input); final JsonParser parser = new JsonParser(); final JsonElement conflictJson = parser.parse(body); if (conflictJson.isJsonObject()) { final JsonObject conflict = conflictJson.getAsJsonObject(); String featureId = null; RevFeature ourFeature = null; RevFeatureType ourFeatureType = null; RevFeature theirFeature = null; RevFeatureType theirFeatureType = null; JsonObject merges = null; if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) { featureId = conflict.get("path").getAsJsonPrimitive().getAsString(); } Preconditions.checkState(featureId != null); if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) { String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString(); Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit); if (ourNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(ourNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); ourFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class) .setObjectId(ourNode.get().getMetadataId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); ourFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) { String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString(); Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit); if (theirNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(theirNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); theirFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class) .setObjectId(theirNode.get().getMetadataId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); theirFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("merges") && conflict.get("merges").isJsonObject()) { merges = conflict.get("merges").getAsJsonObject(); } Preconditions.checkState(merges != null); Preconditions.checkState(ourFeatureType != null || theirFeatureType != null); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type())); ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType : ourFeatureType).sortedDescriptors(); for (Entry<String, JsonElement> entry : merges.entrySet()) { int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors); if (descriptorIndex != -1 && entry.getValue().isJsonObject()) { PropertyDescriptor descriptor = descriptors.get(descriptorIndex); JsonObject attributeObject = entry.getValue().getAsJsonObject(); if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive() && attributeObject.get("ours").getAsBoolean()) { featureBuilder.set(descriptor.getName(), ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive() && attributeObject.get("theirs").getAsBoolean()) { featureBuilder.set(descriptor.getName(), theirFeature == null ? null : theirFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) { JsonPrimitive primitive = attributeObject.get("value") .getAsJsonPrimitive(); if (primitive.isString()) { try { Object object = valueFromString( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsString()); featureBuilder.set(descriptor.getName(), object); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isNumber()) { try { Object value = valueFromNumber( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsNumber()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isBoolean()) { try { Object value = valueFromBoolean( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsBoolean()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isJsonNull()) { featureBuilder.set(descriptor.getName(), null); } else { throw new Exception("Unsupported JSON type for attribute value (" + entry.getKey() + ")"); } } } } SimpleFeature feature = featureBuilder .buildFeature(NodeRef.nodeFromPath(featureId)); RevFeature revFeature = RevFeatureBuilder.build(feature); ggit.getRepository().stagingDatabase().put(revFeature); getResponse().setEntity( new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN)); } } catch (Exception e) { throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e); } finally { if (input != null) Closeables.closeQuietly(input); } } private Object valueFromNumber(FieldType type, Number value) throws Exception { switch (type) { case NULL: return null; case BOOLEAN: return new Boolean(value.doubleValue() != 0); case BYTE: return new Byte(value.byteValue()); case SHORT: return new Short(value.shortValue()); case INTEGER: return new Integer(value.intValue()); case LONG: return new Long(value.longValue()); case FLOAT: return new Float(value.floatValue()); case DOUBLE: return new Double(value.doubleValue()); case STRING: return value.toString(); case BOOLEAN_ARRAY: boolean boolArray[] = { value.doubleValue() != 0 }; return boolArray; case BYTE_ARRAY: byte byteArray[] = { value.byteValue() }; return byteArray; case SHORT_ARRAY: short shortArray[] = { value.shortValue() }; return shortArray; case INTEGER_ARRAY: int intArray[] = { value.intValue() }; return intArray; case LONG_ARRAY: long longArray[] = { value.longValue() }; return longArray; case FLOAT_ARRAY: float floatArray[] = { value.floatValue() }; return floatArray; case DOUBLE_ARRAY: double doubleArray[] = { value.doubleValue() }; return doubleArray; case STRING_ARRAY: String stringArray[] = { value.toString() }; return stringArray; case DATETIME: return new Date(value.longValue()); case DATE: return new java.sql.Date(value.longValue()); case TIME: return new java.sql.Time(value.longValue()); case TIMESTAMP: return new java.sql.Timestamp(value.longValue()); case POINT: case LINESTRING: case POLYGON: case MULTIPOINT: case MULTILINESTRING: case MULTIPOLYGON: case GEOMETRYCOLLECTION: case GEOMETRY: case UUID: case BIG_INTEGER: case BIG_DECIMAL: default: break; } throw new IOException(); } private Object valueFromBoolean(FieldType type, boolean value) throws Exception { switch (type) { case NULL: return null; case BOOLEAN: return new Boolean(value); case BYTE: return new Byte((byte) (value ? 1 : 0)); case SHORT: return new Short((short) (value ? 1 : 0)); case INTEGER: return new Integer((int) (value ? 1 : 0)); case LONG: return new Long((long) (value ? 1 : 0)); case FLOAT: return new Float((float) (value ? 1 : 0)); case DOUBLE: return new Double((double) (value ? 1 : 0)); case STRING: return Boolean.toString(value); case BOOLEAN_ARRAY: boolean boolArray[] = { value }; return boolArray; case BYTE_ARRAY: byte byteArray[] = { (byte) (value ? 1 : 0) }; return byteArray; case SHORT_ARRAY: short shortArray[] = { (short) (value ? 1 : 0) }; return shortArray; case INTEGER_ARRAY: int intArray[] = { (int) (value ? 1 : 0) }; return intArray; case LONG_ARRAY: long longArray[] = { (long) (value ? 1 : 0) }; return longArray; case FLOAT_ARRAY: float floatArray[] = { (float) (value ? 1 : 0) }; return floatArray; case DOUBLE_ARRAY: double doubleArray[] = { (double) (value ? 1 : 0) }; return doubleArray; case STRING_ARRAY: String stringArray[] = { Boolean.toString(value) }; return stringArray; case POINT: case LINESTRING: case POLYGON: case MULTIPOINT: case MULTILINESTRING: case MULTIPOLYGON: case GEOMETRYCOLLECTION: case GEOMETRY: case UUID: case BIG_INTEGER: case BIG_DECIMAL: case DATETIME: case DATE: case TIME: case TIMESTAMP: default: break; } throw new IOException(); } private Object valueFromString(FieldType type, String value) throws Exception { Geometry geom; switch (type) { case NULL: return null; case BOOLEAN: return new Boolean(value); case BYTE: return new Byte(value); case SHORT: return new Short(value); case INTEGER: return new Integer(value); case LONG: return new Long(value); case FLOAT: return new Float(value); case DOUBLE: return new Double(value); case STRING: return value; case BOOLEAN_ARRAY: boolean boolArray[] = { Boolean.parseBoolean(value) }; return boolArray; case BYTE_ARRAY: byte byteArray[] = { Byte.parseByte(value) }; return byteArray; case SHORT_ARRAY: short shortArray[] = { Short.parseShort(value) }; return shortArray; case INTEGER_ARRAY: int intArray[] = { Integer.parseInt(value) }; return intArray; case LONG_ARRAY: long longArray[] = { Long.parseLong(value) }; return longArray; case FLOAT_ARRAY: float floatArray[] = { Float.parseFloat(value) }; return floatArray; case DOUBLE_ARRAY: double doubleArray[] = { Double.parseDouble(value) }; return doubleArray; case STRING_ARRAY: String stringArray[] = { value }; return stringArray; case UUID: return UUID.fromString(value); case BIG_INTEGER: return new BigInteger(value); case BIG_DECIMAL: return new BigDecimal(value); case DATETIME: return new SimpleDateFormat().parse(value); case DATE: return java.sql.Date.valueOf(value); case TIME: return java.sql.Time.valueOf(value); case TIMESTAMP: return new java.sql.Timestamp(new SimpleDateFormat().parse(value).getTime()); case POINT: geom = new WKTReader2().read(value); if (geom instanceof Point) { return (Point) geom; } break; case LINESTRING: geom = new WKTReader2().read(value); if (geom instanceof LineString) { return (LineString) geom; } break; case POLYGON: geom = new WKTReader2().read(value); if (geom instanceof Polygon) { return (Polygon) geom; } break; case MULTIPOINT: geom = new WKTReader2().read(value); if (geom instanceof MultiPoint) { return (MultiPoint) geom; } break; case MULTILINESTRING: geom = new WKTReader2().read(value); if (geom instanceof MultiLineString) { return (MultiLineString) geom; } break; case MULTIPOLYGON: geom = new WKTReader2().read(value); if (geom instanceof MultiPolygon) { return (MultiPolygon) geom; } break; case GEOMETRYCOLLECTION: geom = new WKTReader2().read(value); if (geom instanceof GeometryCollection) { return (GeometryCollection) geom; } break; case GEOMETRY: return new WKTReader2().read(value); default: break; } throw new IOException(); } private int getDescriptorIndex(String key, ImmutableList<PropertyDescriptor> properties) { for (int i = 0; i < properties.size(); i++) { PropertyDescriptor prop = properties.get(i); if (prop.getName().toString().equals(key)) { return i; } } return -1; } }
src/web/api/src/main/java/org/geogit/rest/repository/MergeFeatureResource.java
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the GNU GPL 2.0 license, available at the root * application directory. */ package org.geogit.rest.repository; import static org.geogit.rest.repository.RESTUtils.getGeogit; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map.Entry; import java.util.UUID; import org.geogit.api.GeoGIT; import org.geogit.api.NodeRef; import org.geogit.api.ObjectId; import org.geogit.api.RevCommit; import org.geogit.api.RevFeature; import org.geogit.api.RevFeatureBuilder; import org.geogit.api.RevFeatureType; import org.geogit.api.RevObject; import org.geogit.api.RevTree; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.storage.FieldType; import org.geogit.web.api.CommandSpecException; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.geometry.jts.WKTReader2; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.PropertyDescriptor; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.resource.Resource; import org.restlet.resource.StringRepresentation; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.io.Closeables; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.MultiLineString; import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * */ public class MergeFeatureResource extends Resource { @Override public boolean allowPost() { return true; } private Optional<NodeRef> parseID(ObjectId commitId, String path, GeoGIT geogit) { Optional<RevObject> object = geogit.command(RevObjectParse.class).setObjectId(commitId) .call(); RevCommit commit = null; if (object.isPresent() && object.get() instanceof RevCommit) { commit = (RevCommit) object.get(); } else { throw new CommandSpecException("Couldn't resolve id: " + commitId.toString() + " to a commit"); } object = geogit.command(RevObjectParse.class).setObjectId(commit.getTreeId()).call(); if (object.isPresent()) { RevTree tree = (RevTree) object.get(); return geogit.command(FindTreeChild.class).setParent(tree).setChildPath(path).call(); } else { throw new CommandSpecException("Couldn't resolve commit's treeId"); } } public void post(Representation entity) { InputStream input = null; try { input = getRequest().getEntity().getStream(); final GeoGIT ggit = getGeogit(getRequest()).get(); final Reader body = new InputStreamReader(input); final JsonParser parser = new JsonParser(); final JsonElement conflictJson = parser.parse(body); if (conflictJson.isJsonObject()) { final JsonObject conflict = conflictJson.getAsJsonObject(); String featureId = null; RevFeature ourFeature = null; RevFeatureType ourFeatureType = null; RevFeature theirFeature = null; RevFeatureType theirFeatureType = null; JsonObject merges = null; if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) { featureId = conflict.get("path").getAsJsonPrimitive().getAsString(); } Preconditions.checkState(featureId != null); if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) { String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString(); Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit); if (ourNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(ourNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); ourFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class) .setObjectId(ourNode.get().getMetadataId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); ourFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) { String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString(); Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit); if (theirNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(theirNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); theirFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class) .setObjectId(theirNode.get().getMetadataId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); theirFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("merges") && conflict.get("merges").isJsonObject()) { merges = conflict.get("merges").getAsJsonObject(); } Preconditions.checkState(merges != null); Preconditions.checkState(ourFeatureType != null || theirFeatureType != null); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type())); ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType : ourFeatureType).sortedDescriptors(); for (Entry<String, JsonElement> entry : merges.entrySet()) { int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors); if (descriptorIndex != -1 && entry.getValue().isJsonObject()) { PropertyDescriptor descriptor = descriptors.get(descriptorIndex); JsonObject attributeObject = entry.getValue().getAsJsonObject(); if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive() && attributeObject.get("ours").getAsBoolean()) { featureBuilder.set(descriptor.getName(), ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive() && attributeObject.get("theirs").getAsBoolean()) { featureBuilder.set(descriptor.getName(), theirFeature == null ? null : theirFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) { JsonPrimitive primitive = attributeObject.get("value") .getAsJsonPrimitive(); if (primitive.isString()) { try { Object object = valueFromString( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsString()); featureBuilder.set(descriptor.getName(), object); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isNumber()) { try { Object value = valueFromNumber( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsNumber()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isBoolean()) { try { Object value = valueFromBoolean( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsBoolean()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isJsonNull()) { featureBuilder.set(descriptor.getName(), null); } else { throw new Exception("Unsupported JSON type for attribute value (" + entry.getKey() + ")"); } } } } SimpleFeature feature = featureBuilder .buildFeature(NodeRef.nodeFromPath(featureId)); RevFeature revFeature = RevFeatureBuilder.build(feature); ggit.getRepository().stagingDatabase().put(revFeature); getResponse().setEntity( new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN)); } } catch (Exception e) { throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e); } finally { if (input != null) Closeables.closeQuietly(input); } } private Object valueFromNumber(FieldType type, Number value) throws Exception { switch (type) { case NULL: return null; case BOOLEAN: return new Boolean(value.doubleValue() != 0); case BYTE: return new Byte(value.byteValue()); case SHORT: return new Short(value.shortValue()); case INTEGER: return new Integer(value.intValue()); case LONG: return new Long(value.longValue()); case FLOAT: return new Float(value.floatValue()); case DOUBLE: return new Double(value.doubleValue()); case STRING: return value.toString(); case BOOLEAN_ARRAY: boolean boolArray[] = { value.doubleValue() != 0 }; return boolArray; case BYTE_ARRAY: byte byteArray[] = { value.byteValue() }; return byteArray; case SHORT_ARRAY: short shortArray[] = { value.shortValue() }; return shortArray; case INTEGER_ARRAY: int intArray[] = { value.intValue() }; return intArray; case LONG_ARRAY: long longArray[] = { value.longValue() }; return longArray; case FLOAT_ARRAY: float floatArray[] = { value.floatValue() }; return floatArray; case DOUBLE_ARRAY: double doubleArray[] = { value.doubleValue() }; return doubleArray; case STRING_ARRAY: String stringArray[] = { value.toString() }; return stringArray; case DATETIME: return new Date(value.longValue()); case DATE: return new java.sql.Date(value.longValue()); case TIME: return new java.sql.Time(value.longValue()); case TIMESTAMP: return new java.sql.Timestamp(value.longValue()); case POINT: case LINESTRING: case POLYGON: case MULTIPOINT: case MULTILINESTRING: case MULTIPOLYGON: case GEOMETRYCOLLECTION: case GEOMETRY: case UUID: case BIG_INTEGER: case BIG_DECIMAL: default: break; } throw new IOException(); } private Object valueFromBoolean(FieldType type, boolean value) throws Exception { switch (type) { case NULL: return null; case BOOLEAN: return new Boolean(value); case BYTE: return new Byte((byte) (value ? 1 : 0)); case SHORT: return new Short((short) (value ? 1 : 0)); case INTEGER: return new Integer((int) (value ? 1 : 0)); case LONG: return new Long((long) (value ? 1 : 0)); case FLOAT: return new Float((float) (value ? 1 : 0)); case DOUBLE: return new Double((double) (value ? 1 : 0)); case STRING: return Boolean.toString(value); case BOOLEAN_ARRAY: boolean boolArray[] = { value }; return boolArray; case BYTE_ARRAY: byte byteArray[] = { (byte) (value ? 1 : 0) }; return byteArray; case SHORT_ARRAY: short shortArray[] = { (short) (value ? 1 : 0) }; return shortArray; case INTEGER_ARRAY: int intArray[] = { (int) (value ? 1 : 0) }; return intArray; case LONG_ARRAY: long longArray[] = { (long) (value ? 1 : 0) }; return longArray; case FLOAT_ARRAY: float floatArray[] = { (float) (value ? 1 : 0) }; return floatArray; case DOUBLE_ARRAY: double doubleArray[] = { (double) (value ? 1 : 0) }; return doubleArray; case STRING_ARRAY: String stringArray[] = { Boolean.toString(value) }; return stringArray; case POINT: case LINESTRING: case POLYGON: case MULTIPOINT: case MULTILINESTRING: case MULTIPOLYGON: case GEOMETRYCOLLECTION: case GEOMETRY: case UUID: case BIG_INTEGER: case BIG_DECIMAL: case DATETIME: case DATE: case TIME: case TIMESTAMP: default: break; } throw new IOException(); } private Object valueFromString(FieldType type, String value) throws Exception { Geometry geom; switch (type) { case NULL: return null; case BOOLEAN: return new Boolean(value); case BYTE: return new Byte(value); case SHORT: return new Short(value); case INTEGER: return new Integer(value); case LONG: return new Long(value); case FLOAT: return new Float(value); case DOUBLE: return new Double(value); case STRING: return value; case BOOLEAN_ARRAY: boolean boolArray[] = { Boolean.parseBoolean(value) }; return boolArray; case BYTE_ARRAY: byte byteArray[] = { Byte.parseByte(value) }; return byteArray; case SHORT_ARRAY: short shortArray[] = { Short.parseShort(value) }; return shortArray; case INTEGER_ARRAY: int intArray[] = { Integer.parseInt(value) }; return intArray; case LONG_ARRAY: long longArray[] = { Long.parseLong(value) }; return longArray; case FLOAT_ARRAY: float floatArray[] = { Float.parseFloat(value) }; return floatArray; case DOUBLE_ARRAY: double doubleArray[] = { Double.parseDouble(value) }; return doubleArray; case STRING_ARRAY: String stringArray[] = { value }; return stringArray; case UUID: return UUID.fromString(value); case BIG_INTEGER: return new BigInteger(value); case BIG_DECIMAL: return new BigDecimal(value); case DATETIME: return new SimpleDateFormat().parse(value); case DATE: return java.sql.Date.valueOf(value); case TIME: return java.sql.Time.valueOf(value); case TIMESTAMP: return java.sql.Timestamp.valueOf(value); case POINT: geom = new WKTReader2().read(value); if (geom instanceof Point) { return (Point) geom; } break; case LINESTRING: geom = new WKTReader2().read(value); if (geom instanceof LineString) { return (LineString) geom; } break; case POLYGON: geom = new WKTReader2().read(value); if (geom instanceof Polygon) { return (Polygon) geom; } break; case MULTIPOINT: geom = new WKTReader2().read(value); if (geom instanceof MultiPoint) { return (MultiPoint) geom; } break; case MULTILINESTRING: geom = new WKTReader2().read(value); if (geom instanceof MultiLineString) { return (MultiLineString) geom; } break; case MULTIPOLYGON: geom = new WKTReader2().read(value); if (geom instanceof MultiPolygon) { return (MultiPolygon) geom; } break; case GEOMETRYCOLLECTION: geom = new WKTReader2().read(value); if (geom instanceof GeometryCollection) { return (GeometryCollection) geom; } break; case GEOMETRY: return new WKTReader2().read(value); default: break; } throw new IOException(); } private int getDescriptorIndex(String key, ImmutableList<PropertyDescriptor> properties) { for (int i = 0; i < properties.size(); i++) { PropertyDescriptor prop = properties.get(i); if (prop.getName().toString().equals(key)) { return i; } } return -1; } }
Made the parsing of timestamps more flexible.
src/web/api/src/main/java/org/geogit/rest/repository/MergeFeatureResource.java
Made the parsing of timestamps more flexible.
<ide><path>rc/web/api/src/main/java/org/geogit/rest/repository/MergeFeatureResource.java <ide> case TIME: <ide> return java.sql.Time.valueOf(value); <ide> case TIMESTAMP: <del> return java.sql.Timestamp.valueOf(value); <add> return new java.sql.Timestamp(new SimpleDateFormat().parse(value).getTime()); <ide> case POINT: <ide> geom = new WKTReader2().read(value); <ide> if (geom instanceof Point) {
Java
mpl-2.0
2edebd7063dcd0fa4d9cc88b75f73d477a122778
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
/* * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package org.helioviewer.jhv.opengl.text; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.image.*; import com.jogamp.opengl.*; import com.jogamp.opengl.util.texture.*; import com.jogamp.opengl.util.texture.awt.*; import org.helioviewer.jhv.math.Transform; /** Provides the ability to render into an OpenGL {@link com.jogamp.opengl.util.texture.Texture Texture} using the Java 2D APIs. This renderer class uses an internal Java 2D image (of unspecified type) for its backing store and flushes portions of that image to an OpenGL texture on demand. The resulting OpenGL texture can then be mapped on to a polygon for display. */ class JhvTextureRenderer { // For now, we supply only a BufferedImage back-end for this // renderer. In theory we could use the Java 2D/JOGL bridge to fully // accelerate the rendering paths, but there are restrictions on // what work can be done where; for example, Graphics2D-related work // must not be done on the Queue Flusher Thread, but JOGL's // OpenGL-related work must be. This implies that the user's code // would need to be split up into multiple callbacks run from the // appropriate threads, which would be somewhat unfortunate. // The backing store itself private BufferedImage image; private Texture texture; private final AWTTextureData textureData; private Rectangle dirtyRegion; private final int width; private final int height; /** Creates a new renderer with backing store of the specified width and height. @param width the width of the texture to render into @param height the height of the texture to render into */ JhvTextureRenderer(int _width, int _height) { width = _width; height = _height; int internalFormat = GL2.GL_RGBA; // force for high version OpenGL int imageType = BufferedImage.TYPE_INT_ARGB_PRE; image = new BufferedImage(width, height, imageType); // Always reallocate the TextureData associated with this // BufferedImage; it's just a reference to the contents but we // need it in order to update sub-regions of the underlying // texture final GL2 gl = (GL2) GLContext.getCurrentGL(); textureData = new AWTTextureData(gl.getGLProfile(), internalFormat, 0, true, image); texture = TextureIO.newTexture(textureData); texture.setTexParameteri(gl, GL2.GL_TEXTURE_BASE_LEVEL, 0); texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAX_LEVEL, 15); texture.setTexParameteri(gl, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR_MIPMAP_LINEAR); texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE); texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_EDGE); } public int getWidth() { return width; } public int getHeight() { return height; } /** Creates a {@link java.awt.Graphics2D Graphics2D} instance for rendering to the backing store of this renderer. The returned object should be disposed of using the normal {@link java.awt.Graphics#dispose() Graphics.dispose()} method once it is no longer being used. @return a new {@link java.awt.Graphics2D Graphics2D} object for rendering into the backing store of this renderer */ public Graphics2D createGraphics() { return image.createGraphics(); } /** Returns the underlying Java 2D {@link java.awt.Image Image} being rendered into. */ public Image getImage() { return image; } /** Marks the given region of the TextureRenderer as dirty. This region, and any previously set dirty regions, will be automatically synchronized with the underlying Texture during the next {@link #getTexture getTexture} operation, at which point the dirty region will be cleared. It is not necessary for an OpenGL context to be current when this method is called. @param x the x coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param y the y coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param width the width of the region to update @param height the height of the region to update */ public void markDirty(final int x, final int y, final int width, final int height) { final Rectangle curRegion = new Rectangle(x, y, width, height); if (dirtyRegion == null) { dirtyRegion = curRegion; } else { dirtyRegion.add(curRegion); } } /** Returns the underlying OpenGL Texture object associated with this renderer, synchronizing any dirty regions of the TextureRenderer with the underlying OpenGL texture. @throws GLException If an OpenGL context is not current when this method is called */ public Texture getTexture() throws GLException { if (dirtyRegion != null) { sync(dirtyRegion.x, dirtyRegion.y, dirtyRegion.width, dirtyRegion.height); dirtyRegion = null; } return texture; } /** Disposes all resources associated with this renderer. It is not valid to use this renderer after calling this method. @throws GLException If an OpenGL context is not current when this method is called */ public void dispose() throws GLException { if (texture != null) { texture.destroy(GLContext.getCurrentGL()); texture = null; } if (image != null) { image.flush(); image = null; } } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen, if the application intends to draw them as a flat overlay on to the screen. Pushes OpenGL state bits (GL_ENABLE_BIT, GL_DEPTH_BUFFER_BIT and GL_TRANSFORM_BIT); disables the depth test, back-face culling, and lighting; enables the texture in this renderer; and sets up the viewing matrices for orthographic rendering where the coordinates go from (0, 0) at the lower left to (width, height) at the upper right. Equivalent to beginOrthoRendering(width, height, true). {@link #endOrthoRendering} must be used in conjunction with this method to restore all OpenGL states. @param width the width of the current on-screen OpenGL drawable @param height the height of the current on-screen OpenGL drawable @throws GLException If an OpenGL context is not current when this method is called */ public void beginOrthoRendering(final int width, final int height) throws GLException { beginRendering(true, width, height); } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen as 2D quads in 3D space. Pushes OpenGL state (GL_ENABLE_BIT); disables lighting; and enables the texture in this renderer. Unlike {@link #beginOrthoRendering beginOrthoRendering}, does not modify the depth test, back-face culling, lighting, or the modelview or projection matrices. {@link #end3DRendering} must be used in conjunction with this method to restore all OpenGL states. @throws GLException If an OpenGL context is not current when this method is called */ public void begin3DRendering() throws GLException { beginRendering(false, 0, 0); } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen, if the application intends to draw them as a flat overlay on to the screen. Must be used if {@link #beginOrthoRendering} is used to set up the rendering stage for this overlay. @throws GLException If an OpenGL context is not current when this method is called */ public void endOrthoRendering() throws GLException { endRendering(true); } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen as 2D quads in 3D space. Must be used if {@link #begin3DRendering} is used to set up the rendering stage for this overlay. @throws GLException If an OpenGL context is not current when this method is called */ public void end3DRendering() throws GLException { endRendering(false); } //---------------------------------------------------------------------- // Internals only below this point // private void beginRendering(final boolean ortho, final int width, final int height) { final GL2 gl = (GL2) GLContext.getCurrentGL(); if (ortho) { gl.glDisable(GL2.GL_DEPTH_TEST); Transform.pushProjection(); Transform.setOrthoProjection(0, width, 0, height, -1, 1); Transform.pushView(); Transform.setIdentityView(); } getTexture().bind(gl); } private void endRendering(final boolean ortho) { final GL2 gl = (GL2) GLContext.getCurrentGL(); if (ortho) { gl.glEnable(GL2.GL_DEPTH_TEST); Transform.popView(); Transform.popProjection(); } } /** Synchronizes the specified region of the backing store down to the underlying OpenGL texture. If {@link #markDirty markDirty} is used instead to indicate the regions that are out of sync, this method does not need to be called. @param x the x coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param y the y coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param width the width of the region to update @param height the height of the region to update @throws GLException If an OpenGL context is not current when this method is called */ private void sync(final int x, final int y, final int width, final int height) throws GLException { // Update specified region. // NOTE that because BufferedImage-based TextureDatas now don't // do anything to their contents, the coordinate systems for // OpenGL and Java 2D actually line up correctly for // updateSubImage calls, so we don't need to do any argument // conversion here (i.e., flipping the Y coordinate). final GL2 gl = (GL2) GLContext.getCurrentGL(); texture.updateSubImage(gl, textureData, 0, x, y, x, y, width, height); gl.glGenerateMipmap(GL2.GL_TEXTURE_2D); } }
src/org/helioviewer/jhv/opengl/text/JhvTextureRenderer.java
/* * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package org.helioviewer.jhv.opengl.text; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.image.*; import com.jogamp.opengl.*; import com.jogamp.opengl.util.texture.*; import com.jogamp.opengl.util.texture.awt.*; import org.helioviewer.jhv.math.Transform; /** Provides the ability to render into an OpenGL {@link com.jogamp.opengl.util.texture.Texture Texture} using the Java 2D APIs. This renderer class uses an internal Java 2D image (of unspecified type) for its backing store and flushes portions of that image to an OpenGL texture on demand. The resulting OpenGL texture can then be mapped on to a polygon for display. */ class JhvTextureRenderer { // For now, we supply only a BufferedImage back-end for this // renderer. In theory we could use the Java 2D/JOGL bridge to fully // accelerate the rendering paths, but there are restrictions on // what work can be done where; for example, Graphics2D-related work // must not be done on the Queue Flusher Thread, but JOGL's // OpenGL-related work must be. This implies that the user's code // would need to be split up into multiple callbacks run from the // appropriate threads, which would be somewhat unfortunate. // The backing store itself private BufferedImage image; private Texture texture; private final AWTTextureData textureData; private boolean mustReallocateTexture; private Rectangle dirtyRegion; private final int width; private final int height; /** Creates a new renderer with backing store of the specified width and height. @param width the width of the texture to render into @param height the height of the texture to render into */ JhvTextureRenderer(int _width, int _height) { width = _width; height = _height; int internalFormat = GL2.GL_RGBA; // force for high version OpenGL int imageType = BufferedImage.TYPE_INT_ARGB_PRE; image = new BufferedImage(width, height, imageType); // Always reallocate the TextureData associated with this // BufferedImage; it's just a reference to the contents but we // need it in order to update sub-regions of the underlying // texture final GL2 gl = (GL2) GLContext.getCurrentGL(); textureData = new AWTTextureData(gl.getGLProfile(), internalFormat, 0, true, image); // For now, always reallocate the underlying OpenGL texture when // the backing store size changes mustReallocateTexture = true; } public int getWidth() { return width; } public int getHeight() { return height; } /** Creates a {@link java.awt.Graphics2D Graphics2D} instance for rendering to the backing store of this renderer. The returned object should be disposed of using the normal {@link java.awt.Graphics#dispose() Graphics.dispose()} method once it is no longer being used. @return a new {@link java.awt.Graphics2D Graphics2D} object for rendering into the backing store of this renderer */ public Graphics2D createGraphics() { return image.createGraphics(); } /** Returns the underlying Java 2D {@link java.awt.Image Image} being rendered into. */ public Image getImage() { return image; } /** Marks the given region of the TextureRenderer as dirty. This region, and any previously set dirty regions, will be automatically synchronized with the underlying Texture during the next {@link #getTexture getTexture} operation, at which point the dirty region will be cleared. It is not necessary for an OpenGL context to be current when this method is called. @param x the x coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param y the y coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param width the width of the region to update @param height the height of the region to update */ public void markDirty(final int x, final int y, final int width, final int height) { final Rectangle curRegion = new Rectangle(x, y, width, height); if (dirtyRegion == null) { dirtyRegion = curRegion; } else { dirtyRegion.add(curRegion); } } /** Returns the underlying OpenGL Texture object associated with this renderer, synchronizing any dirty regions of the TextureRenderer with the underlying OpenGL texture. @throws GLException If an OpenGL context is not current when this method is called */ public Texture getTexture() throws GLException { if (dirtyRegion != null) { sync(dirtyRegion.x, dirtyRegion.y, dirtyRegion.width, dirtyRegion.height); dirtyRegion = null; } ensureTexture(); return texture; } /** Disposes all resources associated with this renderer. It is not valid to use this renderer after calling this method. @throws GLException If an OpenGL context is not current when this method is called */ public void dispose() throws GLException { if (texture != null) { texture.destroy(GLContext.getCurrentGL()); texture = null; } if (image != null) { image.flush(); image = null; } } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen, if the application intends to draw them as a flat overlay on to the screen. Pushes OpenGL state bits (GL_ENABLE_BIT, GL_DEPTH_BUFFER_BIT and GL_TRANSFORM_BIT); disables the depth test, back-face culling, and lighting; enables the texture in this renderer; and sets up the viewing matrices for orthographic rendering where the coordinates go from (0, 0) at the lower left to (width, height) at the upper right. Equivalent to beginOrthoRendering(width, height, true). {@link #endOrthoRendering} must be used in conjunction with this method to restore all OpenGL states. @param width the width of the current on-screen OpenGL drawable @param height the height of the current on-screen OpenGL drawable @throws GLException If an OpenGL context is not current when this method is called */ public void beginOrthoRendering(final int width, final int height) throws GLException { beginRendering(true, width, height); } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen as 2D quads in 3D space. Pushes OpenGL state (GL_ENABLE_BIT); disables lighting; and enables the texture in this renderer. Unlike {@link #beginOrthoRendering beginOrthoRendering}, does not modify the depth test, back-face culling, lighting, or the modelview or projection matrices. {@link #end3DRendering} must be used in conjunction with this method to restore all OpenGL states. @throws GLException If an OpenGL context is not current when this method is called */ public void begin3DRendering() throws GLException { beginRendering(false, 0, 0); } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen, if the application intends to draw them as a flat overlay on to the screen. Must be used if {@link #beginOrthoRendering} is used to set up the rendering stage for this overlay. @throws GLException If an OpenGL context is not current when this method is called */ public void endOrthoRendering() throws GLException { endRendering(true); } /** Convenience method which assists in rendering portions of the OpenGL texture to the screen as 2D quads in 3D space. Must be used if {@link #begin3DRendering} is used to set up the rendering stage for this overlay. @throws GLException If an OpenGL context is not current when this method is called */ public void end3DRendering() throws GLException { endRendering(false); } //---------------------------------------------------------------------- // Internals only below this point // private void beginRendering(final boolean ortho, final int width, final int height) { final GL2 gl = (GL2) GLContext.getCurrentGL(); if (ortho) { gl.glDisable(GL2.GL_DEPTH_TEST); Transform.pushProjection(); Transform.setOrthoProjection(0, width, 0, height, -1, 1); Transform.pushView(); Transform.setIdentityView(); } getTexture().bind(gl); } private void endRendering(final boolean ortho) { final GL2 gl = (GL2) GLContext.getCurrentGL(); if (ortho) { gl.glEnable(GL2.GL_DEPTH_TEST); Transform.popView(); Transform.popProjection(); } } /** Synchronizes the specified region of the backing store down to the underlying OpenGL texture. If {@link #markDirty markDirty} is used instead to indicate the regions that are out of sync, this method does not need to be called. @param x the x coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param y the y coordinate (in Java 2D coordinates -- relative to upper left) of the region to update @param width the width of the region to update @param height the height of the region to update @throws GLException If an OpenGL context is not current when this method is called */ private void sync(final int x, final int y, final int width, final int height) throws GLException { // Force allocation if necessary final boolean canSkipUpdate = ensureTexture(); if (!canSkipUpdate) { // Update specified region. // NOTE that because BufferedImage-based TextureDatas now don't // do anything to their contents, the coordinate systems for // OpenGL and Java 2D actually line up correctly for // updateSubImage calls, so we don't need to do any argument // conversion here (i.e., flipping the Y coordinate). final GL2 gl = (GL2) GLContext.getCurrentGL(); texture.updateSubImage(gl, textureData, 0, x, y, x, y, width, height); gl.glGenerateMipmap(GL2.GL_TEXTURE_2D); } } // Returns true if the texture was newly allocated, false if not private boolean ensureTexture() { if (mustReallocateTexture) { final GL2 gl = (GL2) GLContext.getCurrentGL(); if (texture != null) { texture.destroy(gl); texture = null; } mustReallocateTexture = false; } if (texture == null) { final GL2 gl = (GL2) GLContext.getCurrentGL(); texture = TextureIO.newTexture(textureData); texture.setTexParameteri(gl, GL2.GL_TEXTURE_BASE_LEVEL, 0); texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAX_LEVEL, 15); texture.setTexParameteri(gl, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR_MIPMAP_LINEAR); texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE); texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_EDGE); return true; } return false; } }
Reduce
src/org/helioviewer/jhv/opengl/text/JhvTextureRenderer.java
Reduce
<ide><path>rc/org/helioviewer/jhv/opengl/text/JhvTextureRenderer.java <ide> <ide> private Texture texture; <ide> private final AWTTextureData textureData; <del> private boolean mustReallocateTexture; <ide> private Rectangle dirtyRegion; <ide> <ide> private final int width; <ide> // texture <ide> final GL2 gl = (GL2) GLContext.getCurrentGL(); <ide> textureData = new AWTTextureData(gl.getGLProfile(), internalFormat, 0, true, image); <del> // For now, always reallocate the underlying OpenGL texture when <del> // the backing store size changes <del> mustReallocateTexture = true; <add> <add> texture = TextureIO.newTexture(textureData); <add> texture.setTexParameteri(gl, GL2.GL_TEXTURE_BASE_LEVEL, 0); <add> texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAX_LEVEL, 15); <add> texture.setTexParameteri(gl, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR_MIPMAP_LINEAR); <add> texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); <add> texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE); <add> texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_EDGE); <ide> } <ide> <ide> public int getWidth() { <ide> sync(dirtyRegion.x, dirtyRegion.y, dirtyRegion.width, dirtyRegion.height); <ide> dirtyRegion = null; <ide> } <del> <del> ensureTexture(); <ide> return texture; <ide> } <ide> <ide> @throws GLException If an OpenGL context is not current when this method is called <ide> */ <ide> private void sync(final int x, final int y, final int width, final int height) throws GLException { <del> // Force allocation if necessary <del> final boolean canSkipUpdate = ensureTexture(); <del> <del> if (!canSkipUpdate) { <del> // Update specified region. <del> // NOTE that because BufferedImage-based TextureDatas now don't <del> // do anything to their contents, the coordinate systems for <del> // OpenGL and Java 2D actually line up correctly for <del> // updateSubImage calls, so we don't need to do any argument <del> // conversion here (i.e., flipping the Y coordinate). <del> final GL2 gl = (GL2) GLContext.getCurrentGL(); <del> texture.updateSubImage(gl, textureData, 0, x, y, x, y, width, height); <del> gl.glGenerateMipmap(GL2.GL_TEXTURE_2D); <del> } <del> } <del> <del> // Returns true if the texture was newly allocated, false if not <del> private boolean ensureTexture() { <del> if (mustReallocateTexture) { <del> final GL2 gl = (GL2) GLContext.getCurrentGL(); <del> if (texture != null) { <del> texture.destroy(gl); <del> texture = null; <del> } <del> mustReallocateTexture = false; <del> } <del> <del> if (texture == null) { <del> final GL2 gl = (GL2) GLContext.getCurrentGL(); <del> texture = TextureIO.newTexture(textureData); <del> texture.setTexParameteri(gl, GL2.GL_TEXTURE_BASE_LEVEL, 0); <del> texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAX_LEVEL, 15); <del> texture.setTexParameteri(gl, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR_MIPMAP_LINEAR); <del> texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); <del> texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE); <del> texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_EDGE); <del> return true; <del> } <del> return false; <add> // Update specified region. <add> // NOTE that because BufferedImage-based TextureDatas now don't <add> // do anything to their contents, the coordinate systems for <add> // OpenGL and Java 2D actually line up correctly for <add> // updateSubImage calls, so we don't need to do any argument <add> // conversion here (i.e., flipping the Y coordinate). <add> final GL2 gl = (GL2) GLContext.getCurrentGL(); <add> texture.updateSubImage(gl, textureData, 0, x, y, x, y, width, height); <add> gl.glGenerateMipmap(GL2.GL_TEXTURE_2D); <ide> } <ide> <ide> }
Java
apache-2.0
d875c7c886da9c269bdbbaa64df21a77de03c2da
0
permazen/permazen,archiecobbs/jsimpledb,archiecobbs/jsimpledb,tempbottle/jsimpledb,tempbottle/jsimpledb,permazen/permazen,permazen/permazen,archiecobbs/jsimpledb,tempbottle/jsimpledb
/* * Copyright (C) 2011 Archie L. Cobbs. All rights reserved. * * $Id$ */ package org.dellroad.stuff.spring; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Autowire; /** * Indicates that the class is a candidate for configuration using the {@code ThreadConfigurableAspect} aspect. * * <p> * Works just like Spring's {@link org.springframework.beans.factory.annotation.Configurable @Configurable} annotation, * but whereas {@link org.springframework.beans.factory.annotation.Configurable @Configurable} autowires using a fixed * bean factory stored in a static variable, {@link ThreadConfigurable @ThreadConfigurable} allows the bean factory * that is used for autowiring beans to be changed on a per-thread basis, by invoking * {@link ThreadLocalBeanFactory#set ThreadLocalBeanFactory.set()} on the {@link ThreadLocalBeanFactory} * singleton instance (see {@link ThreadLocalBeanFactory#getInstance}). This allows the same * {@link ThreadConfigurable @ThreadConfigurable}-annotated beans to be instantiated and autowired by different * application contexts at the same time, where the application context chosen depends on the current thread. * </p> * * <p> * With {@link ThreadLocalBeanFactory} the configured bean factory is inherited by spawned child threads, * so typically this configuration need only be done once when starting new some process or operation, * even if that operation involves multiple threads. * </p> * * <p> * For example: * <blockquote><pre> * final BeanFactory otherBeanFactory = ... * Thread thread = new Thread() { * &#64;Override * public void run() { * ThreadLocalBeanFactory.getInstance().set(otherBeanFactory); * // now &#64;ThreadConfigurable beans will use "otherBeanFactory" for autowiring: * new SomeThreadConfigurableBean() ... * } * }; * </pre></blockquote> * * <p> * Note: to make this annotation behave like Spring's * {@link org.springframework.beans.factory.annotation.Configurable @Configurable} annotation, simply include the * {@link ThreadLocalBeanFactory} singleton instance in your bean factory: * <blockquote><pre> * &lt;bean class="org.dellroad.stuff.spring.ThreadLocalBeanFactory" factory-method="getInstance"/&gt; * </pre></blockquote> * This will set the containing bean factory as the default. This definition should be listed prior to any other * bean definitions that could result in {@link ThreadConfigurable @ThreadConfigurable}-annotated beans being * created during bean factory startup. * </p> * * <p> * Note: if a {@link ThreadConfigurable @ThreadConfigurable}-annotated bean is constructed and no bean factory * has been configured for the current thread, there is no default set either, then no configuration is performed * and a debug message is logged (to logger {@code org.dellroad.stuff.spring.ThreadConfigurableAspect}); this consistent * with the behavior of Spring's {@link org.springframework.beans.factory.annotation.Configurable @Configurable}. * </p> * * @see ThreadLocalBeanFactory */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Inherited public @interface ThreadConfigurable { /** * Configuration bean definition template name, if any. */ String value() default ""; /** * Whether and how to automatically autowire dependencies. */ Autowire autowire() default Autowire.NO; /** * Whether to enable dependency checking. */ boolean dependencyCheck() default false; /** * Whether to inject dependencies prior to constructor execution. */ boolean preConstruction() default false; }
src/java/org/dellroad/stuff/spring/ThreadConfigurable.java
/* * Copyright (C) 2011 Archie L. Cobbs. All rights reserved. * * $Id$ */ package org.dellroad.stuff.spring; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Autowire; /** * Indicates that the class is a candidate for configuration using the {@code ThreadConfigurableAspect} aspect. * * <p> * Works just like Spring's {@link org.springframework.beans.factory.annotation.Configurable @Configurable} annotation, * but whereas {@link org.springframework.beans.factory.annotation.Configurable @Configurable} autowires using a fixed * bean factory stored in a static variable, {@link ThreadConfigurable @ThreadConfigurable} allows the bean factory * that is used for autowiring beans to be changed on a per-thread basis, by invoking * {@link ThreadLocalBeanFactory#set ThreadLocalBeanFactory.set()} on the {@link ThreadLocalBeanFactory} * singleton instance (see {@link ThreadLocalBeanFactory#getInstance}). This allows the same * {@link ThreadConfigurable @ThreadConfigurable}-annotated beans to be instantiated and autowired by different * application contexts at the same time, where the application context chosen depends on the current thread. * </p> * * <p> * With {@link ThreadLocalBeanFactory} the configured bean factory is inherited by spawned child threads, * so typically this configuration need only be done once when starting new some process or operation, * even if that operation involves multiple threads. * </p> * * <p> * For example: * <blockquote><pre> * final BeanFactory otherBeanFactory = ... * Thread thread = new Thread() { * &#64;Override * public void run() { * ThreadLocalBeanFactory.getInstance().setBeanFactory(otherBeanFactory); * // now &#64;ThreadConfigurable beans will use "otherBeanFactory" for autowiring: * new SomeThreadConfigurableBean() ... * } * }; * </pre></blockquote> * * <p> * Note: to make this annotation behave like Spring's * {@link org.springframework.beans.factory.annotation.Configurable @Configurable} annotation, simply include the * {@link ThreadLocalBeanFactory} singleton instance in your bean factory: * <blockquote><pre> * &lt;bean class="org.dellroad.stuff.spring.ThreadLocalBeanFactory" factory-method="getInstance"/&gt; * </pre></blockquote> * This will set the containing bean factory as the default. This definition should be listed prior to any other * bean definitions that could result in {@link ThreadConfigurable @ThreadConfigurable}-annotated beans being * created during bean factory startup. * </p> * * <p> * Note: if a {@link ThreadConfigurable @ThreadConfigurable}-annotated bean is constructed and no bean factory * has been configured for the current thread, there is no default set either, then no configuration is performed * and a debug message is logged (to logger {@code org.dellroad.stuff.spring.ThreadConfigurableAspect}); this consistent * with the behavior of Spring's {@link org.springframework.beans.factory.annotation.Configurable @Configurable}. * </p> * * @see ThreadLocalBeanFactory */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Inherited public @interface ThreadConfigurable { /** * Configuration bean definition template name, if any. */ String value() default ""; /** * Whether and how to automatically autowire dependencies. */ Autowire autowire() default Autowire.NO; /** * Whether to enable dependency checking. */ boolean dependencyCheck() default false; /** * Whether to inject dependencies prior to constructor execution. */ boolean preConstruction() default false; }
Fix error in previous commit.
src/java/org/dellroad/stuff/spring/ThreadConfigurable.java
Fix error in previous commit.
<ide><path>rc/java/org/dellroad/stuff/spring/ThreadConfigurable.java <ide> * Thread thread = new Thread() { <ide> * &#64;Override <ide> * public void run() { <del> * ThreadLocalBeanFactory.getInstance().setBeanFactory(otherBeanFactory); <add> * ThreadLocalBeanFactory.getInstance().set(otherBeanFactory); <ide> * // now &#64;ThreadConfigurable beans will use "otherBeanFactory" for autowiring: <ide> * new SomeThreadConfigurableBean() ... <ide> * }
Java
lgpl-2.1
7cdea8b44e5377ba9d962d247718a9373e1a38b1
0
netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration
/*$Id$ * $Revision$ * $Date$ * $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * 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 dk.netarkivet.harvester.harvesting; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.exceptions.IllegalState; import dk.netarkivet.common.utils.FileUtils; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.common.utils.XmlUtils; import dk.netarkivet.harvester.HarvesterSettings; import dk.netarkivet.harvester.datamodel.HeritrixTemplate; import dk.netarkivet.harvester.harvesting.controller.DirectHeritrixController; import dk.netarkivet.harvester.harvesting.controller.HeritrixController; import dk.netarkivet.testutils.XmlAsserts; import dk.netarkivet.testutils.preconfigured.MoveTestFiles; import junit.framework.TestCase; import org.apache.commons.httpclient.URIException; import org.archive.crawler.datamodel.CandidateURI; import org.archive.crawler.datamodel.CrawlURI; import org.archive.crawler.event.CrawlStatusListener; import org.archive.crawler.framework.CrawlController; import org.archive.crawler.framework.Frontier; import org.archive.crawler.framework.FrontierMarker; import org.archive.crawler.framework.exceptions.EndedException; import org.archive.crawler.framework.exceptions.FatalConfigurationException; import org.archive.crawler.framework.exceptions.InitializationException; import org.archive.crawler.framework.exceptions.InvalidFrontierMarkerException; import org.archive.crawler.frontier.FrontierJournal; import org.archive.crawler.frontier.HostnameQueueAssignmentPolicy; import org.archive.crawler.settings.SettingsHandler; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.dom4j.Document; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Tests various aspects of launching Heritrix and Heritrix' capabilities. * Note that some of these tests require much heap space, so JVM parameter * -Xmx512M may be required. */ public class HeritrixLauncherTester extends TestCase { private MoveTestFiles mtf; private File dummyLuceneIndex; public HeritrixLauncherTester() { mtf = new MoveTestFiles (TestInfo.CRAWLDIR_ORIGINALS_DIR, TestInfo.WORKING_DIR); } public void setUp() throws IOException { mtf.setUp(); dummyLuceneIndex = mtf.newTmpDir(); // Uncommented to avoid reference to archive module from harvester module. // // FIXME This makes HeritrixLauncherTester#testSetupOrderFile fail, as it requires // this method to be run //dk.netarkivet.archive.indexserver.LuceneUtils.makeDummyIndex(dummyLuceneIndex); } public void tearDown() { mtf.tearDown(); } /** * Centralized place for tests to construct a HeritrixLauncher. * - Constructs the given crawlDir. * - Copies the given order.xml to the proper place in the given crawlDir. * - Copies the standard seeds.txt to the proper place in the given crawlDir. * - Constructs a HeritrixLauncher and returns it * @param origOrderXml original order.xml * @param indexDir * @return a HeritrixLauncher used by (most) tests. */ private HeritrixLauncher getHeritrixLauncher(File origOrderXml, File indexDir) { File origSeeds = TestInfo.SEEDS_FILE; File crawlDir = TestInfo.HERITRIX_TEMP_DIR; crawlDir.mkdirs(); File orderXml = new File(crawlDir, "order.xml"); File seedsTxt = new File(crawlDir, "seeds.txt"); FileUtils.copyFile(origOrderXml, orderXml); FileUtils.copyFile(origSeeds, seedsTxt); HeritrixFiles files = new HeritrixFiles(crawlDir, new JobInfoTestImpl(Long.parseLong(TestInfo.ARC_JOB_ID), Long.parseLong(TestInfo.ARC_HARVEST_ID))); // If deduplicationMode != NO_DEDUPLICATION // write the zipped index to the indexdir inside the crawldir if (orderXml.exists() && orderXml.length() > 0 && HeritrixTemplate.isDeduplicationEnabledInTemplate(XmlUtils.getXmlDoc(orderXml))) { assertNotNull("Must have a non-null index when deduplication is enabled", indexDir); files.setIndexDir(indexDir); assertTrue("Indexdir should exist now ", files.getIndexDir().isDirectory()); assertTrue("Indexdir should contain real contents now", files.getIndexDir().listFiles().length > 0); } return HeritrixLauncherFactory.getInstance(files); } /** * Check that all urls in the given array are listed in the crawl log. * Calls fail() at the first url that is not found or if the crawl log is not * found. * * @param urls An array of url strings * @throws IOException */ protected void assertAllUrlsInCrawlLog(String[] urls) throws IOException { String crawlLog = ""; crawlLog = FileUtils.readFile(TestInfo.HERITRIX_CRAWL_LOG_FILE); for (String s : Arrays.asList(urls)) { if (crawlLog.indexOf(s) == -1) { System.out.println("Crawl log: "); System.out.println(crawlLog); fail("URL " + s + " not found in crawl log"); } } } /** * Check that no urls in the given array are listed in the crawl log. * Calls fail() at the first url that is found or if the crawl log is not * found. * * @param urls An array of url strings * @throws IOException */ protected void assertNoUrlsInCrawlLog(String[] urls) throws IOException { String crawlLog = ""; crawlLog = FileUtils.readFile(TestInfo.HERITRIX_CRAWL_LOG_FILE); for (String s : Arrays.asList(urls)) { if (crawlLog.indexOf(s) != -1) { System.out.println("Crawl log: "); System.out.println(crawlLog); fail("URL " + s + " found in crawl log at " + crawlLog.indexOf( s)); } } } /** * Test that the launcher aborts given a non-existing order-file. */ public void testStartMissingOrderFile() { try { HeritrixLauncherFactory.getInstance( new HeritrixFiles(mtf.newTmpDir(), new JobInfoTestImpl(42L, 42L))); fail("Expected IOFailure"); } catch (ArgumentNotValid e) { // expected case } } /** * Test that the launcher aborts given a non-existing seeds-file. */ public void testStartMissingSeedsFile() { try { HeritrixFiles hf = new HeritrixFiles(TestInfo.WORKING_DIR, new JobInfoTestImpl(42L, 42L)); hf.getSeedsTxtFile().delete(); HeritrixLauncherFactory.getInstance(hf); fail("Expected FileNotFoundException"); } catch (ArgumentNotValid e) { // This is correct } } /** * Test that the launcher handles heritrix dying on a bad order file correctly. */ public void testStartBadOrderFile() { myTesterOfBadOrderfiles(TestInfo.BAD_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file missing the disk node correctly. */ public void testStartMissingDiskFieldOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_DISK_FIELD_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file * missing the arcs-path node correctly. */ /* public void testStartMissingARCsPathOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_ARCS_PATH_ORDER_FILE); } */ /** * Test that the launcher handles heritrix dying on a order file missing the seedsfile node correctly. */ public void testStartMissingSeedsfileOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_SEEDS_FILE_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file missing the seedsfile node correctly. */ /* public void testStartMissingPrefixOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_PREFIX_FIELD_ORDER_FILE); }*/ /** * This method is used to test various scenarios with bad order-files. * * @param orderfile */ private void myTesterOfBadOrderfiles(File orderfile) { HeritrixLauncher hl = getHeritrixLauncher(orderfile, null); try { hl.doCrawl(); fail("An exception should have been caught when launching with a bad order.xml file !"); } catch (IOFailure e) { // expected case since a searched node could not be found in the bad // XML-order-file! } catch (IllegalState e) { // expected case since a searched node could not be found in the bad // XML-order-file! } } /** * Test that the launcher handles an empty order file correctly. */ public void testStartEmptyFile() { HeritrixLauncher hl = getHeritrixLauncher(TestInfo.EMPTY_ORDER_FILE, null); try { hl.doCrawl(); fail("An exception should have been caught when launching with an empty order.xml file !"); } catch (IOFailure e) { // Expected case } } /** Test that starting a job does not throw an Exception. * Will fail if tests/dk/netarkivet/jmxremote.password has other rights * than -r------ * * FIXME Fails on Hudson * @throws NoSuchFieldException * @throws IllegalAccessException */ public void failingTestStartJob() throws NoSuchFieldException, IllegalAccessException { //HeritrixLauncher hl = getHeritrixLauncher(TestInfo.ORDER_FILE, null); //HeritrixLauncher hl = new HeritrixLauncher(); //HeritrixFiles files = // (HeritrixFiles) ReflectUtils.getPrivateField(hl.getClass(), // "files").get(hl); //ReflectUtils.getPrivateField(hl.getClass(), // "heritrixController").set(hl, new TestCrawlController(files)); Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$TestCrawlController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); hl.doCrawl(); Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * Test that the HostnameQueueAssignmentPolicy returns correct queue-names * for different URLs. * The HostnameQueueAssignmentPolicy is the default in heritrix * - our own DomainnameQueueAssignmentPolicy extends this one and expects * that it returns the right values */ public void testHostnameQueueAssignmentPolicy() { HostnameQueueAssignmentPolicy hqap = new HostnameQueueAssignmentPolicy(); UURI uri; CandidateURI cauri; try { /** * First test tests that www.netarkivet.dk goes into a queue called: www.netarkivet.dk */ uri = UURIFactory.getInstance("http://www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get host name from normal URL", hqap.getClassKey(new CrawlController(),cauri),"www.netarkivet.dk"); /** * Second test tests that foo.www.netarkivet.dk goes into a queue called: foo.www.netarkivet.dk */ uri = UURIFactory.getInstance("http://foo.www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get host name from non-www URL", hqap.getClassKey(new CrawlController(),cauri),"foo.www.netarkivet.dk"); /** * Third test tests that a https-URL goes into a queuename called * www.domainname#443 (default syntax) */ uri = UURIFactory.getInstance("https://www.netarkivet.dk/foo/bar.php"); cauri = new CandidateURI(uri); assertEquals("Should get port-extended host name from HTTPS URL", hqap.getClassKey(new CrawlController(),cauri),"www.netarkivet.dk#443"); } catch (URIException e) { fail("Should not throw exception on valid URI's"); } } /** * Test that the DomainnameQueueAssignmentPolicy returns correct queue-names for different URL's */ public void testDomainnameQueueAssignmentPolicy() { DomainnameQueueAssignmentPolicy dqap = new DomainnameQueueAssignmentPolicy(); UURI uri; CandidateURI cauri; try { /** * First test tests that www.netarkivet.dk goes into a queue called: netarkivet.dk */ uri = UURIFactory.getInstance("http://www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get base domain name from normal URL", dqap.getClassKey(new CrawlController(),cauri),"netarkivet.dk"); /** * Second test tests that foo.www.netarkivet.dk goes into a queue called: netarkivet.dk */ uri = UURIFactory.getInstance("http://foo.www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get base domain name from non-www URL", dqap.getClassKey(new CrawlController(),cauri),"netarkivet.dk"); /** * Third test tests that a https-URL goes into a queuename called domainname (default syntax) */ uri = UURIFactory.getInstance("https://www.netarkivet.dk/foo/bar.php"); cauri = new CandidateURI(uri); assertEquals("HTTPS should go into domains queue as well", "netarkivet.dk", dqap.getClassKey(new CrawlController(),cauri)); } catch (URIException e) { fail("Should not throw exception on valid URI's"); } } /** * Tests, that the Heritrix order files is setup correctly. * FIXME: Changed from " testSetupOrderFile()" * to FailingtestSetupOrderFile(), as it fails without dummyIndex * * @throws NoSuchFieldException * @throws IllegalAccessException */ public void FailingtestSetupOrderFile() throws NoSuchFieldException, IllegalAccessException { /** * Check the DeduplicationType.NO_DEDUPLICATION type of deduplication is setup correctly */ HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); hl.setupOrderfile(hl.getHeritrixFiles()); File orderFile = new File (TestInfo.HERITRIX_TEMP_DIR, "order.xml"); Document doc = XmlUtils.getXmlDoc(orderFile); /* check, that deduplicator is not enabled in the order */ assertFalse("Should not have deduplication enabled", HeritrixTemplate.isDeduplicationEnabledInTemplate(doc)); /** * Check the DeduplicationType.DEDUPLICATION_USING_THE_DEDUPLICATOR * type of deduplication is setup correctly */ hl = getHeritrixLauncher(TestInfo.DEDUP_ORDER_FILE, dummyLuceneIndex); hl.setupOrderfile(hl.getHeritrixFiles()); // check, that the deduplicator is present in the order doc = XmlUtils.getXmlDoc(orderFile); assertTrue("Should have deduplication enabled", HeritrixTemplate.isDeduplicationEnabledInTemplate(doc)); XmlAsserts.assertNodeWithXpath( doc, HeritrixTemplate.DEDUPLICATOR_XPATH); XmlAsserts.assertNodeWithXpath( doc, HeritrixTemplate.DEDUPLICATOR_INDEX_LOCATION_XPATH); XmlAsserts.assertNodeTextInXpath( "Should have set index to right directory", doc, HeritrixTemplate.DEDUPLICATOR_INDEX_LOCATION_XPATH, dummyLuceneIndex.getAbsolutePath()); } /** * Tests that HeritricLauncher will fail on an error in * HeritrixController.initialize(). * * FIXME Fails in Hudson */ public void failingTestFailOnInitialize() throws NoSuchFieldException, IllegalAccessException { Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$SucceedOnCleanupTestController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); try { hl.doCrawl(); fail("HeritrixLanucher should throw an exception when it fails to initialize"); } catch (IOFailure e) { assertTrue("Error message should be from initialiser", e.getMessage().contains("initialize")); //expected } Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * When the an exception is thrown in cleanup, any exceptions thrown in the * initialiser are lost. * * * FIXME Fails in Hudson */ public void failingTestFailOnCleanup() { Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$FailingTestController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); try { hl.doCrawl(); fail("HeritrixLanucher should throw an exception when it fails to initialize"); } catch (IOFailure e) { assertTrue("Error message should be from cleanup", e.getMessage().contains("cleanup")); //expected } Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * A failure to communicate with heritrix during the crawl should be logged * but not be in any way fatal to the crawl. * * * * FIXME Fails in Hudson */ public void failingTestFailDuringCrawl() { Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$FailDuringCrawlTestController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); hl.doCrawl(); Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * A test heritrixController which starts and stops a crawl cleanly but fails * during the crawl itself. */ public static class FailDuringCrawlTestController extends FailingTestController { private int isEndedCalls = 0; public FailDuringCrawlTestController(HeritrixFiles files) { super(files); } public void requestCrawlStop(String reason) { } public void initialize() { } public void requestCrawlStart() throws IOFailure { } public boolean atFinish() { return false; } public void beginCrawlStop() { } public void cleanup() { } public boolean crawlIsEnded() { if (isEndedCalls >= 3) { return true; } else { isEndedCalls++; throw new IOFailure("Failure in crawlIsEnded"); } } } /** * A Heritrix Controller which fails on every call. */ public static class FailingTestController implements HeritrixController { public FailingTestController(HeritrixFiles files) {}; public void initialize() { //TODO: implement method throw new IOFailure("Failed to initialize"); } public void requestCrawlStart() throws IOFailure { //TODO: implement method throw new IOFailure("Not implemented"); } public void beginCrawlStop() { //TODO: implement method throw new IOFailure("Not implemented"); } public void requestCrawlStop(String reason) { //TODO: implement method throw new IOFailure("Not implemented"); } public boolean atFinish() { //TODO: implement method throw new IOFailure("Not implemented"); } public boolean crawlIsEnded() { //TODO: implement method throw new IOFailure("Not implemented"); } public int getActiveToeCount() { //TODO: implement method throw new IOFailure("Not implemented"); } public long getQueuedUriCount() { //TODO: implement method throw new IOFailure("Not implemented"); } public int getCurrentProcessedKBPerSec() { //TODO: implement method throw new IOFailure("Not implemented"); } public String getProgressStats() { //TODO: implement method throw new IOFailure("Not implemented"); } public boolean isPaused() { //TODO: implement method throw new IOFailure("Not implemented"); } public void cleanup() { throw new IOFailure("cleanup failure"); } public String getHarvestInformation() { //TODO: implement method throw new IOFailure("Not implemented"); } } /** * A heritrix controller which fails on everything except cleanup */ public static class SucceedOnCleanupTestController extends FailingTestController { public SucceedOnCleanupTestController(HeritrixFiles files) {super(files);} public void cleanup(){return;} } /** A class that closely emulates CrawlController, except it never * starts Heritrix. */ public static class TestCrawlController extends DirectHeritrixController { private static final long serialVersionUID = 1L; /** * List of crawl status listeners. * * All iterations need to synchronize on this object if they're to avoid * concurrent modification exceptions. * See {@link java.util.Collections#synchronizedList(List)}. */ private List<CrawlStatusListener> listeners = new ArrayList<CrawlStatusListener>(); public TestCrawlController(HeritrixFiles files) { super(files); } /** * Register for CrawlStatus events. * * @param cl a class implementing the CrawlStatusListener interface * * @see CrawlStatusListener */ public void addCrawlStatusListener(CrawlStatusListener cl) { synchronized (this.listeners) { this.listeners.add(cl); } } /** * Operator requested crawl begin */ public void requestCrawlStart() { new Thread() { public void run() { for (CrawlStatusListener l : listeners) { l.crawlEnding("Fake over"); l.crawlEnded("Fake all over"); } } }.start(); } /** * Starting from nothing, set up CrawlController and associated * classes to be ready for a first crawl. * * @param sH * @throws InitializationException */ public void initialize(SettingsHandler sH) throws InitializationException { } public void requestCrawlStop(String test){ } public Frontier getFrontier(){ return new TestFrontier(); } /** * Dummy frontier used by TestCrawlController */ class TestFrontier implements Frontier { public void initialize(CrawlController crawlController) throws FatalConfigurationException, IOException {} public CrawlURI next() throws InterruptedException, EndedException {return null;} public boolean isEmpty() {return false;} public void schedule(CandidateURI candidateURI) {} public void finished(CrawlURI crawlURI) {} public long discoveredUriCount() {return 0;} public long queuedUriCount() {return 0;} public long finishedUriCount() {return 0;} public long succeededFetchCount() {return 0;} public long failedFetchCount() {return 0;} public long disregardedUriCount() {return 0;} public long totalBytesWritten() {return 0;} public String oneLineReport() {return null;} public String report() {return null;} public void importRecoverLog(String s, boolean b) throws IOException {} public FrontierMarker getInitialMarker(String s, boolean b) {return null;} public ArrayList getURIsList(FrontierMarker frontierMarker, int i, boolean b) throws InvalidFrontierMarkerException {return null;} public long deleteURIs(String s) {return 0;} public void deleted(CrawlURI crawlURI) {} public void considerIncluded(UURI uuri) {} public void kickUpdate() {} public void pause() {} public void unpause() {} public void terminate() {} public FrontierJournal getFrontierJournal() {return null;} public String getClassKey(CandidateURI candidateURI) {return null;} public void loadSeeds() {} public String[] getReports() {return new String[0];} //public void reportTo(String s, PrintWriter printWriter) throws IOException {} public void reportTo(String s, PrintWriter printWriter) {} public void reportTo(PrintWriter printWriter) throws IOException {} public void singleLineReportTo(PrintWriter printWriter) throws IOException {} public String singleLineReport() { return null;} public String singleLineLegend(){ return null; } public void start(){} public Frontier.FrontierGroup getGroup(CrawlURI crawlURI) { return null; } public float congestionRatio() { return 0.0f; } public long averageDepth() { return 0L; } public long deepestUri() { return 0L; } public long deleteURIs(String arg0, String arg1) { return 0L; } @Override public void finalTasks() { // TODO Auto-generated method stub } } }; }
tests/dk/netarkivet/harvester/harvesting/HeritrixLauncherTester.java
/*$Id$ * $Revision$ * $Date$ * $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * 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 dk.netarkivet.harvester.harvesting; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.exceptions.IllegalState; import dk.netarkivet.common.utils.FileUtils; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.common.utils.XmlUtils; import dk.netarkivet.harvester.HarvesterSettings; import dk.netarkivet.harvester.datamodel.HeritrixTemplate; import dk.netarkivet.harvester.harvesting.controller.DirectHeritrixController; import dk.netarkivet.harvester.harvesting.controller.HeritrixController; import dk.netarkivet.testutils.XmlAsserts; import dk.netarkivet.testutils.preconfigured.MoveTestFiles; import junit.framework.TestCase; import org.apache.commons.httpclient.URIException; import org.archive.crawler.datamodel.CandidateURI; import org.archive.crawler.datamodel.CrawlURI; import org.archive.crawler.event.CrawlStatusListener; import org.archive.crawler.framework.CrawlController; import org.archive.crawler.framework.Frontier; import org.archive.crawler.framework.FrontierMarker; import org.archive.crawler.framework.exceptions.EndedException; import org.archive.crawler.framework.exceptions.FatalConfigurationException; import org.archive.crawler.framework.exceptions.InitializationException; import org.archive.crawler.framework.exceptions.InvalidFrontierMarkerException; import org.archive.crawler.frontier.FrontierJournal; import org.archive.crawler.frontier.HostnameQueueAssignmentPolicy; import org.archive.crawler.settings.SettingsHandler; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.dom4j.Document; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Tests various aspects of launching Heritrix and Heritrix' capabilities. * Note that some of these tests require much heap space, so JVM parameter * -Xmx512M may be required. */ public class HeritrixLauncherTester extends TestCase { private MoveTestFiles mtf; private File dummyLuceneIndex; public HeritrixLauncherTester() { mtf = new MoveTestFiles (TestInfo.CRAWLDIR_ORIGINALS_DIR, TestInfo.WORKING_DIR); } public void setUp() throws IOException { mtf.setUp(); dummyLuceneIndex = mtf.newTmpDir(); // Uncommented to avoid reference to archive module from harvester module. // // FIXME This makes HeritrixLauncherTester#testSetupOrderFile fail, as it requires // this method to be run //dk.netarkivet.archive.indexserver.LuceneUtils.makeDummyIndex(dummyLuceneIndex); } public void tearDown() { mtf.tearDown(); } /** * Centralized place for tests to construct a HeritrixLauncher. * - Constructs the given crawlDir. * - Copies the given order.xml to the proper place in the given crawlDir. * - Copies the standard seeds.txt to the proper place in the given crawlDir. * - Constructs a HeritrixLauncher and returns it * @param origOrderXml original order.xml * @param indexDir * @return a HeritrixLauncher used by (most) tests. */ private HeritrixLauncher getHeritrixLauncher(File origOrderXml, File indexDir) { File origSeeds = TestInfo.SEEDS_FILE; File crawlDir = TestInfo.HERITRIX_TEMP_DIR; crawlDir.mkdirs(); File orderXml = new File(crawlDir, "order.xml"); File seedsTxt = new File(crawlDir, "seeds.txt"); FileUtils.copyFile(origOrderXml, orderXml); FileUtils.copyFile(origSeeds, seedsTxt); HeritrixFiles files = new HeritrixFiles(crawlDir, new JobInfoTestImpl(Long.parseLong(TestInfo.ARC_JOB_ID), Long.parseLong(TestInfo.ARC_HARVEST_ID))); // If deduplicationMode != NO_DEDUPLICATION // write the zipped index to the indexdir inside the crawldir if (orderXml.exists() && orderXml.length() > 0 && HeritrixTemplate.isDeduplicationEnabledInTemplate(XmlUtils.getXmlDoc(orderXml))) { assertNotNull("Must have a non-null index when deduplication is enabled", indexDir); files.setIndexDir(indexDir); assertTrue("Indexdir should exist now ", files.getIndexDir().isDirectory()); assertTrue("Indexdir should contain real contents now", files.getIndexDir().listFiles().length > 0); } return HeritrixLauncherFactory.getInstance(files); } /** * Check that all urls in the given array are listed in the crawl log. * Calls fail() at the first url that is not found or if the crawl log is not * found. * * @param urls An array of url strings * @throws IOException */ protected void assertAllUrlsInCrawlLog(String[] urls) throws IOException { String crawlLog = ""; crawlLog = FileUtils.readFile(TestInfo.HERITRIX_CRAWL_LOG_FILE); for (String s : Arrays.asList(urls)) { if (crawlLog.indexOf(s) == -1) { System.out.println("Crawl log: "); System.out.println(crawlLog); fail("URL " + s + " not found in crawl log"); } } } /** * Check that no urls in the given array are listed in the crawl log. * Calls fail() at the first url that is found or if the crawl log is not * found. * * @param urls An array of url strings * @throws IOException */ protected void assertNoUrlsInCrawlLog(String[] urls) throws IOException { String crawlLog = ""; crawlLog = FileUtils.readFile(TestInfo.HERITRIX_CRAWL_LOG_FILE); for (String s : Arrays.asList(urls)) { if (crawlLog.indexOf(s) != -1) { System.out.println("Crawl log: "); System.out.println(crawlLog); fail("URL " + s + " found in crawl log at " + crawlLog.indexOf( s)); } } } /** * Test that the launcher aborts given a non-existing order-file. */ public void testStartMissingOrderFile() { try { HeritrixLauncherFactory.getInstance( new HeritrixFiles(mtf.newTmpDir(), new JobInfoTestImpl(42L, 42L))); fail("Expected IOFailure"); } catch (ArgumentNotValid e) { // expected case } } /** * Test that the launcher aborts given a non-existing seeds-file. */ public void testStartMissingSeedsFile() { try { HeritrixFiles hf = new HeritrixFiles(TestInfo.WORKING_DIR, new JobInfoTestImpl(42L, 42L)); hf.getSeedsTxtFile().delete(); HeritrixLauncherFactory.getInstance(hf); fail("Expected FileNotFoundException"); } catch (ArgumentNotValid e) { // This is correct } } /** * Test that the launcher handles heritrix dying on a bad order file correctly. */ public void testStartBadOrderFile() { myTesterOfBadOrderfiles(TestInfo.BAD_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file missing the disk node correctly. */ public void testStartMissingDiskFieldOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_DISK_FIELD_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file missing the arcs-path node correctly. */ public void testStartMissingARCsPathOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_ARCS_PATH_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file missing the seedsfile node correctly. */ public void testStartMissingSeedsfileOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_SEEDS_FILE_ORDER_FILE); } /** * Test that the launcher handles heritrix dying on a order file missing the seedsfile node correctly. */ public void testStartMissingPrefixOrderFile() { myTesterOfBadOrderfiles(TestInfo.MISSING_PREFIX_FIELD_ORDER_FILE); } /** * This method is used to test various scenarios with bad order-files. * * @param orderfile */ private void myTesterOfBadOrderfiles(File orderfile) { HeritrixLauncher hl = getHeritrixLauncher(orderfile, null); try { hl.doCrawl(); fail("An exception should have been caught when launching with a bad order.xml file !"); } catch (IOFailure e) { // expected case since a searched node could not be found in the bad // XML-order-file! } catch (IllegalState e) { // expected case since a searched node could not be found in the bad // XML-order-file! } } /** * Test that the launcher handles an empty order file correctly. */ public void testStartEmptyFile() { HeritrixLauncher hl = getHeritrixLauncher(TestInfo.EMPTY_ORDER_FILE, null); try { hl.doCrawl(); fail("An exception should have been caught when launching with an empty order.xml file !"); } catch (IOFailure e) { // Expected case } } /** Test that starting a job does not throw an Exception. * Will fail if tests/dk/netarkivet/jmxremote.password has other rights * than -r------ * * FIXME Fails on Hudson * @throws NoSuchFieldException * @throws IllegalAccessException */ public void failingTestStartJob() throws NoSuchFieldException, IllegalAccessException { //HeritrixLauncher hl = getHeritrixLauncher(TestInfo.ORDER_FILE, null); //HeritrixLauncher hl = new HeritrixLauncher(); //HeritrixFiles files = // (HeritrixFiles) ReflectUtils.getPrivateField(hl.getClass(), // "files").get(hl); //ReflectUtils.getPrivateField(hl.getClass(), // "heritrixController").set(hl, new TestCrawlController(files)); Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$TestCrawlController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); hl.doCrawl(); Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * Test that the HostnameQueueAssignmentPolicy returns correct queue-names * for different URLs. * The HostnameQueueAssignmentPolicy is the default in heritrix * - our own DomainnameQueueAssignmentPolicy extends this one and expects * that it returns the right values */ public void testHostnameQueueAssignmentPolicy() { HostnameQueueAssignmentPolicy hqap = new HostnameQueueAssignmentPolicy(); UURI uri; CandidateURI cauri; try { /** * First test tests that www.netarkivet.dk goes into a queue called: www.netarkivet.dk */ uri = UURIFactory.getInstance("http://www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get host name from normal URL", hqap.getClassKey(new CrawlController(),cauri),"www.netarkivet.dk"); /** * Second test tests that foo.www.netarkivet.dk goes into a queue called: foo.www.netarkivet.dk */ uri = UURIFactory.getInstance("http://foo.www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get host name from non-www URL", hqap.getClassKey(new CrawlController(),cauri),"foo.www.netarkivet.dk"); /** * Third test tests that a https-URL goes into a queuename called * www.domainname#443 (default syntax) */ uri = UURIFactory.getInstance("https://www.netarkivet.dk/foo/bar.php"); cauri = new CandidateURI(uri); assertEquals("Should get port-extended host name from HTTPS URL", hqap.getClassKey(new CrawlController(),cauri),"www.netarkivet.dk#443"); } catch (URIException e) { fail("Should not throw exception on valid URI's"); } } /** * Test that the DomainnameQueueAssignmentPolicy returns correct queue-names for different URL's */ public void testDomainnameQueueAssignmentPolicy() { DomainnameQueueAssignmentPolicy dqap = new DomainnameQueueAssignmentPolicy(); UURI uri; CandidateURI cauri; try { /** * First test tests that www.netarkivet.dk goes into a queue called: netarkivet.dk */ uri = UURIFactory.getInstance("http://www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get base domain name from normal URL", dqap.getClassKey(new CrawlController(),cauri),"netarkivet.dk"); /** * Second test tests that foo.www.netarkivet.dk goes into a queue called: netarkivet.dk */ uri = UURIFactory.getInstance("http://foo.www.netarkivet.dk/foo/bar.cgi"); cauri = new CandidateURI(uri); assertEquals("Should get base domain name from non-www URL", dqap.getClassKey(new CrawlController(),cauri),"netarkivet.dk"); /** * Third test tests that a https-URL goes into a queuename called domainname (default syntax) */ uri = UURIFactory.getInstance("https://www.netarkivet.dk/foo/bar.php"); cauri = new CandidateURI(uri); assertEquals("HTTPS should go into domains queue as well", "netarkivet.dk", dqap.getClassKey(new CrawlController(),cauri)); } catch (URIException e) { fail("Should not throw exception on valid URI's"); } } /** * Tests, that the Heritrix order files is setup correctly. * FIXME: Changed from " testSetupOrderFile()" * to FailingtestSetupOrderFile(), as it fails without dummyIndex * * @throws NoSuchFieldException * @throws IllegalAccessException */ public void FailingtestSetupOrderFile() throws NoSuchFieldException, IllegalAccessException { /** * Check the DeduplicationType.NO_DEDUPLICATION type of deduplication is setup correctly */ HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); hl.setupOrderfile(hl.getHeritrixFiles()); File orderFile = new File (TestInfo.HERITRIX_TEMP_DIR, "order.xml"); Document doc = XmlUtils.getXmlDoc(orderFile); /* check, that deduplicator is not enabled in the order */ assertFalse("Should not have deduplication enabled", HeritrixTemplate.isDeduplicationEnabledInTemplate(doc)); /** * Check the DeduplicationType.DEDUPLICATION_USING_THE_DEDUPLICATOR * type of deduplication is setup correctly */ hl = getHeritrixLauncher(TestInfo.DEDUP_ORDER_FILE, dummyLuceneIndex); hl.setupOrderfile(hl.getHeritrixFiles()); // check, that the deduplicator is present in the order doc = XmlUtils.getXmlDoc(orderFile); assertTrue("Should have deduplication enabled", HeritrixTemplate.isDeduplicationEnabledInTemplate(doc)); XmlAsserts.assertNodeWithXpath( doc, HeritrixTemplate.DEDUPLICATOR_XPATH); XmlAsserts.assertNodeWithXpath( doc, HeritrixTemplate.DEDUPLICATOR_INDEX_LOCATION_XPATH); XmlAsserts.assertNodeTextInXpath( "Should have set index to right directory", doc, HeritrixTemplate.DEDUPLICATOR_INDEX_LOCATION_XPATH, dummyLuceneIndex.getAbsolutePath()); } /** * Tests that HeritricLauncher will fail on an error in * HeritrixController.initialize(). * * FIXME Fails in Hudson */ public void failingTestFailOnInitialize() throws NoSuchFieldException, IllegalAccessException { Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$SucceedOnCleanupTestController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); try { hl.doCrawl(); fail("HeritrixLanucher should throw an exception when it fails to initialize"); } catch (IOFailure e) { assertTrue("Error message should be from initialiser", e.getMessage().contains("initialize")); //expected } Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * When the an exception is thrown in cleanup, any exceptions thrown in the * initialiser are lost. * * * FIXME Fails in Hudson */ public void failingTestFailOnCleanup() { Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$FailingTestController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); try { hl.doCrawl(); fail("HeritrixLanucher should throw an exception when it fails to initialize"); } catch (IOFailure e) { assertTrue("Error message should be from cleanup", e.getMessage().contains("cleanup")); //expected } Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * A failure to communicate with heritrix during the crawl should be logged * but not be in any way fatal to the crawl. * * * * FIXME Fails in Hudson */ public void failingTestFailDuringCrawl() { Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.HeritrixLauncherTester$FailDuringCrawlTestController"); HeritrixLauncher hl = getHeritrixLauncher( TestInfo.ORDER_FILE_WITH_DEDUPLICATION_DISABLED, null); hl.doCrawl(); Settings.set(HarvesterSettings.HERITRIX_CONTROLLER_CLASS, "dk.netarkivet.harvester.harvesting.JMXHeritrixController"); } /** * A test heritrixController which starts and stops a crawl cleanly but fails * during the crawl itself. */ public static class FailDuringCrawlTestController extends FailingTestController { private int isEndedCalls = 0; public FailDuringCrawlTestController(HeritrixFiles files) { super(files); } public void requestCrawlStop(String reason) { } public void initialize() { } public void requestCrawlStart() throws IOFailure { } public boolean atFinish() { return false; } public void beginCrawlStop() { } public void cleanup() { } public boolean crawlIsEnded() { if (isEndedCalls >= 3) { return true; } else { isEndedCalls++; throw new IOFailure("Failure in crawlIsEnded"); } } } /** * A Heritrix Controller which fails on every call. */ public static class FailingTestController implements HeritrixController { public FailingTestController(HeritrixFiles files) {}; public void initialize() { //TODO: implement method throw new IOFailure("Failed to initialize"); } public void requestCrawlStart() throws IOFailure { //TODO: implement method throw new IOFailure("Not implemented"); } public void beginCrawlStop() { //TODO: implement method throw new IOFailure("Not implemented"); } public void requestCrawlStop(String reason) { //TODO: implement method throw new IOFailure("Not implemented"); } public boolean atFinish() { //TODO: implement method throw new IOFailure("Not implemented"); } public boolean crawlIsEnded() { //TODO: implement method throw new IOFailure("Not implemented"); } public int getActiveToeCount() { //TODO: implement method throw new IOFailure("Not implemented"); } public long getQueuedUriCount() { //TODO: implement method throw new IOFailure("Not implemented"); } public int getCurrentProcessedKBPerSec() { //TODO: implement method throw new IOFailure("Not implemented"); } public String getProgressStats() { //TODO: implement method throw new IOFailure("Not implemented"); } public boolean isPaused() { //TODO: implement method throw new IOFailure("Not implemented"); } public void cleanup() { throw new IOFailure("cleanup failure"); } public String getHarvestInformation() { //TODO: implement method throw new IOFailure("Not implemented"); } } /** * A heritrix controller which fails on everything except cleanup */ public static class SucceedOnCleanupTestController extends FailingTestController { public SucceedOnCleanupTestController(HeritrixFiles files) {super(files);} public void cleanup(){return;} } /** A class that closely emulates CrawlController, except it never * starts Heritrix. */ public static class TestCrawlController extends DirectHeritrixController { private static final long serialVersionUID = 1L; /** * List of crawl status listeners. * * All iterations need to synchronize on this object if they're to avoid * concurrent modification exceptions. * See {@link java.util.Collections#synchronizedList(List)}. */ private List<CrawlStatusListener> listeners = new ArrayList<CrawlStatusListener>(); public TestCrawlController(HeritrixFiles files) { super(files); } /** * Register for CrawlStatus events. * * @param cl a class implementing the CrawlStatusListener interface * * @see CrawlStatusListener */ public void addCrawlStatusListener(CrawlStatusListener cl) { synchronized (this.listeners) { this.listeners.add(cl); } } /** * Operator requested crawl begin */ public void requestCrawlStart() { new Thread() { public void run() { for (CrawlStatusListener l : listeners) { l.crawlEnding("Fake over"); l.crawlEnded("Fake all over"); } } }.start(); } /** * Starting from nothing, set up CrawlController and associated * classes to be ready for a first crawl. * * @param sH * @throws InitializationException */ public void initialize(SettingsHandler sH) throws InitializationException { } public void requestCrawlStop(String test){ } public Frontier getFrontier(){ return new TestFrontier(); } /** * Dummy frontier used by TestCrawlController */ class TestFrontier implements Frontier { public void initialize(CrawlController crawlController) throws FatalConfigurationException, IOException {} public CrawlURI next() throws InterruptedException, EndedException {return null;} public boolean isEmpty() {return false;} public void schedule(CandidateURI candidateURI) {} public void finished(CrawlURI crawlURI) {} public long discoveredUriCount() {return 0;} public long queuedUriCount() {return 0;} public long finishedUriCount() {return 0;} public long succeededFetchCount() {return 0;} public long failedFetchCount() {return 0;} public long disregardedUriCount() {return 0;} public long totalBytesWritten() {return 0;} public String oneLineReport() {return null;} public String report() {return null;} public void importRecoverLog(String s, boolean b) throws IOException {} public FrontierMarker getInitialMarker(String s, boolean b) {return null;} public ArrayList getURIsList(FrontierMarker frontierMarker, int i, boolean b) throws InvalidFrontierMarkerException {return null;} public long deleteURIs(String s) {return 0;} public void deleted(CrawlURI crawlURI) {} public void considerIncluded(UURI uuri) {} public void kickUpdate() {} public void pause() {} public void unpause() {} public void terminate() {} public FrontierJournal getFrontierJournal() {return null;} public String getClassKey(CandidateURI candidateURI) {return null;} public void loadSeeds() {} public String[] getReports() {return new String[0];} //public void reportTo(String s, PrintWriter printWriter) throws IOException {} public void reportTo(String s, PrintWriter printWriter) {} public void reportTo(PrintWriter printWriter) throws IOException {} public void singleLineReportTo(PrintWriter printWriter) throws IOException {} public String singleLineReport() { return null;} public String singleLineLegend(){ return null; } public void start(){} public Frontier.FrontierGroup getGroup(CrawlURI crawlURI) { return null; } public float congestionRatio() { return 0.0f; } public long averageDepth() { return 0L; } public long deepestUri() { return 0L; } public long deleteURIs(String arg0, String arg1) { return 0L; } @Override public void finalTasks() { // TODO Auto-generated method stub } } }; }
Uncommented two unittests which test stuff, that is now done in theJob class.
tests/dk/netarkivet/harvester/harvesting/HeritrixLauncherTester.java
Uncommented two unittests which test stuff, that is now done in theJob class.
<ide><path>ests/dk/netarkivet/harvester/harvesting/HeritrixLauncherTester.java <ide> } <ide> <ide> /** <del> * Test that the launcher handles heritrix dying on a order file missing the arcs-path node correctly. <del> */ <add> * Test that the launcher handles heritrix dying on a order file <add> * missing the arcs-path node correctly. <add> */ <add> /* <ide> public void testStartMissingARCsPathOrderFile() { <ide> myTesterOfBadOrderfiles(TestInfo.MISSING_ARCS_PATH_ORDER_FILE); <ide> } <add> */ <ide> <ide> /** <ide> * Test that the launcher handles heritrix dying on a order file missing the seedsfile node correctly. <ide> /** <ide> * Test that the launcher handles heritrix dying on a order file missing the seedsfile node correctly. <ide> */ <add> /* <ide> public void testStartMissingPrefixOrderFile() { <ide> myTesterOfBadOrderfiles(TestInfo.MISSING_PREFIX_FIELD_ORDER_FILE); <del> } <add> }*/ <ide> <ide> /** <ide> * This method is used to test various scenarios with bad order-files.
Java
apache-2.0
066c8fb0a2f2287e11487b788819869035f96f33
0
AlejandroVera/ProjectTwitter,AlejandroVera/ProjectTwitter
package servidor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import excepcionesComunes.TwitterException; import servidor.db.Conexion; import interfacesComunes.Message; import interfacesComunes.Place; import servidor.TwitterImpl; import servidor.TwitterImpl.KEntityType; import servidor.TwitterImpl.TweetEntity; import interfacesComunes.Twitter; import interfacesComunes.User; public class MessageImpl implements Message{ private int id; private int inReplyToMessageId; //-1 si no es respuesta private String text; private Conexion con; //Constructor para no respuesta MessageImpl(int id, String text, Conexion con){ this.id=id; this.inReplyToMessageId=-1; this.text=text; this.con=con; } MessageImpl(int id, int reply, String text, Conexion con){ this.id=id; this.inReplyToMessageId=reply; this.text=text; this.con=con; } public Date getCreatedAt(){ ResultSet res = con.query("SELECT fecha FROM mensajes WHERE id ="+id + "LIMIT 1"); try { if (res.next()){ Date date= new Date(res.getInt(1)*1000); return date; } } catch (SQLException e) { ServerCommon.TwitterWarning(e, "Error al obtener la fecha"); e.printStackTrace(); } return null; } public int getId() { return id; } public String getLocation() { int id_user=getSender().getId(); ResultSet res = con.query("SELECT location FROM users WHERE id ="+id_user +"LIMIT 1"); try { if (res.next()){ String location = res.getString(1); return location; } } catch (SQLException e) { ServerCommon.TwitterWarning(e, "Error al obtener la location"); e.printStackTrace(); } return null; } public List<String> getMentions() { List<String> menciones = new ArrayList<String>(); String mencion = new String(); if (text.contains("@")){ for (int i=0; i<text.length();i++){ if (text.charAt(i) =='@'){ i++; while (text.charAt(i) !=' '){ mencion=mencion+text.charAt(i); i++; } menciones.add(mencion); } } } return menciones; } /*Lo dejo para Place*/ public Place getPlace() { // TODO Auto-generated method stub return null; } public String getText() { return text; } public List<TweetEntity> getTweetEntities(KEntityType type) { List<TwitterImpl.TweetEntity> entities=new ArrayList<TwitterImpl.TweetEntity>(); int inicio; Pattern p=null; Matcher m=null; if(type==KEntityType.urls){ p=Pattern.compile("((^|\\s)[a-zA-Z0-9]+)(\\.[a-zA-Z0-9]+)+"); } else if(type==KEntityType.hashtags){ p=Pattern.compile("(^|\\s)#[a-zA-Z0-9]+"); } else if(type==KEntityType.user_mentions){ p=Pattern.compile("(^|\\s)@[a-zA-Z0-9]+"); } m= p.matcher(this.text); while(m.find()){ if(this.text.substring(m.start(),m.end()).charAt(0)==' '){ inicio=m.start()+1; } else{ inicio=m.start(); } entities.add(new TwitterImpl.TweetEntity(type,inicio,m.end())); } return entities; } public User getUser() { ResultSet res = con.query("SELECT id_autor FROM mensajes WHERE id ="+id+"LIMIT 1"); try{ if (res.next()){ int id_autor = res.getInt(1); return UserImpl(id_autor); } } catch (SQLException e) { ServerCommon.TwitterWarning(e, "Error al obtener la Autor"); e.printStackTrace(); } return null; } public String getDisplayText() { return text; } @Override public User getRecipient() { ResultSet res = con.query("SELECT id_receptor FROM mensajes WHERE id ="+id+"LIMIT 1"); try{ if (res.next()){ int id_receptor = res.getInt(1); return UserImpl(id_receptor); } } catch (SQLException e) { ServerCommon.TwitterWarning(e, "Error al obtener el receptor"); e.printStackTrace(); } return null; } @Override public User getSender() { User user = getUser(); return user; } }
src/servidor/MessageImpl.java
package servidor; import java.sql.ResultSet; import java.util.Date; import java.util.List; import excepcionesComunes.TwitterException; import servidor.db.Conexion; import interfacesComunes.Message; import interfacesComunes.Place; import interfacesComunes.Twitter; import interfacesComunes.Twitter.KEntityType; import interfacesComunes.Twitter.TweetEntity; import interfacesComunes.User; public class MessageImpl implements Message{ private int id; private int inReplyToMessageId; //-1 si no es respuesta private String text; private Conexion con; //Constructor para no respuesta MessageImpl(int id, String text, Conexion con){ this.id=id; this.inReplyToMessageId=-1; this.text=text; this.con=con; } MessageImpl(int id, int reply, String text, Conexion con){ this.id=id; this.inReplyToMessageId=reply; this.text=text; this.con=con; } @Override public Date getCreatedAt() throws TwitterException{ ResultSet res = con.query("SELECT fecha FROM mensajes WHERE id ="+id); if (res.next()){ Date date = res.getDate(id); } else throw new TwitterException ("Error al obtener la fecha"); return null; } @Override public int getId() { return id; } @Override public String getLocation() { int id_user=getSender().getId(); ResultSet res = con.query("SELECT location FROM users WHERE id ="+id_user); if (res.next()){ String location = res.toString(); } else throw new TwitterException ("Error al obtener la location"); return null; } @Override public List<String> getMentions() { List<String> menciones; String mencion; if (text.contains("@")){ for (int i=0; i<text.length();i++){ if (text.charAt(i) =='@'){ i++; while (text.charAt(i) !=' '){ mencion=mencion+text.charAt(i); i++; } menciones.add(mencion); } } } return menciones; } /*Lo dejo para Place*/ public Place getPlace() { // TODO Auto-generated method stub return null; } @Override public String getText() { return text; } //No lo veo utilidad, porque pone en la API que ni siquiera tiene soporte con Twitter public List<TweetEntity> getTweetEntities(Twitter.KEntityType type) { return null; } @Override public User getUser() { ResultSet res = con.query("SELECT id_autor FROM mensajes WHERE id ="+id); if (res.next()){ int id_autor = Integer.parseInt( res.toString()); return UserImpl(id_autor); } else throw new TwitterException ("Error al obtener el autor del mensaje"); return null; } @Override public String getDisplayText() { return text; } @Override public User getRecipient() { ResultSet res = con.query("SELECT id_receptor FROM mensajes WHERE id ="+id); if (res.next()){ int id_receptor = Integer.parseInt( res.toString()); return UserImpl(id_receptor); } else throw new TwitterException ("Error al obtener el autor del mensaje"); return null; } @Override public User getSender() { User user = getUser(); return user; } }
MessageImpl arreglado.
src/servidor/MessageImpl.java
MessageImpl arreglado.
<ide><path>rc/servidor/MessageImpl.java <ide> package servidor; <ide> <ide> import java.sql.ResultSet; <add>import java.sql.SQLException; <add>import java.util.ArrayList; <ide> import java.util.Date; <ide> import java.util.List; <del> <add>import java.util.regex.Matcher; <add>import java.util.regex.Pattern; <ide> import excepcionesComunes.TwitterException; <ide> <ide> import servidor.db.Conexion; <ide> <ide> import interfacesComunes.Message; <ide> import interfacesComunes.Place; <add> <add>import servidor.TwitterImpl; <add>import servidor.TwitterImpl.KEntityType; <add>import servidor.TwitterImpl.TweetEntity; <add> <ide> import interfacesComunes.Twitter; <del>import interfacesComunes.Twitter.KEntityType; <del>import interfacesComunes.Twitter.TweetEntity; <add> <add> <ide> import interfacesComunes.User; <ide> <ide> public class MessageImpl implements Message{ <ide> this.con=con; <ide> } <ide> <del> @Override <del> public Date getCreatedAt() throws TwitterException{ <del> ResultSet res = con.query("SELECT fecha FROM mensajes WHERE id ="+id); <del> if (res.next()){ <del> Date date = res.getDate(id); <add> <add> public Date getCreatedAt(){ <add> ResultSet res = con.query("SELECT fecha FROM mensajes WHERE id ="+id + "LIMIT 1"); <add> try { <add> if (res.next()){ <add> Date date= new Date(res.getInt(1)*1000); <add> return date; <add> } <add> } catch (SQLException e) { <add> ServerCommon.TwitterWarning(e, "Error al obtener la fecha"); <add> e.printStackTrace(); <ide> } <del> else throw new TwitterException ("Error al obtener la fecha"); <add> <ide> <ide> return null; <ide> } <ide> <del> @Override <add> <ide> public int getId() { <ide> return id; <ide> } <ide> <del> @Override <add> <ide> public String getLocation() { <ide> int id_user=getSender().getId(); <del> ResultSet res = con.query("SELECT location FROM users WHERE id ="+id_user); <del> if (res.next()){ <del> String location = res.toString(); <add> ResultSet res = con.query("SELECT location FROM users WHERE id ="+id_user +"LIMIT 1"); <add> try { <add> if (res.next()){ <add> String location = res.getString(1); <add> return location; <add> } <add> } catch (SQLException e) { <add> ServerCommon.TwitterWarning(e, "Error al obtener la location"); <add> e.printStackTrace(); <ide> } <del> else throw new TwitterException ("Error al obtener la location"); <ide> <ide> return null; <ide> } <ide> <ide> <del> @Override <add> <ide> public List<String> getMentions() { <ide> <del> List<String> menciones; <del> String mencion; <add> List<String> menciones = new ArrayList<String>(); <add> String mencion = new String(); <ide> <ide> if (text.contains("@")){ <ide> for (int i=0; i<text.length();i++){ <ide> return null; <ide> } <ide> <del> @Override <add> <ide> public String getText() { <ide> return text; <ide> } <ide> <del> //No lo veo utilidad, porque pone en la API que ni siquiera tiene soporte con Twitter <del> public List<TweetEntity> getTweetEntities(Twitter.KEntityType type) { <add> <add> public List<TweetEntity> getTweetEntities(KEntityType type) { <ide> <add> List<TwitterImpl.TweetEntity> entities=new ArrayList<TwitterImpl.TweetEntity>(); <add> int inicio; <add> Pattern p=null; <add> Matcher m=null; <add> if(type==KEntityType.urls){ <add> p=Pattern.compile("((^|\\s)[a-zA-Z0-9]+)(\\.[a-zA-Z0-9]+)+"); <add> } <add> else if(type==KEntityType.hashtags){ <add> p=Pattern.compile("(^|\\s)#[a-zA-Z0-9]+"); <add> } <add> else if(type==KEntityType.user_mentions){ <add> p=Pattern.compile("(^|\\s)@[a-zA-Z0-9]+"); <add> } <add> m= p.matcher(this.text); <add> while(m.find()){ <add> if(this.text.substring(m.start(),m.end()).charAt(0)==' '){ <add> inicio=m.start()+1; <add> } <add> else{ <add> inicio=m.start(); <add> } <add> entities.add(new TwitterImpl.TweetEntity(type,inicio,m.end())); <add> } <add> return entities; <add> } <add> <add> <add> <add> <add> public User getUser() { <add> ResultSet res = con.query("SELECT id_autor FROM mensajes WHERE id ="+id+"LIMIT 1"); <add> try{ <add> if (res.next()){ <add> int id_autor = res.getInt(1); <add> return UserImpl(id_autor); <add> } <add> } catch (SQLException e) { <add> ServerCommon.TwitterWarning(e, "Error al obtener la Autor"); <add> e.printStackTrace(); <add> } <ide> return null; <ide> } <ide> <del> @Override <del> public User getUser() { <del> ResultSet res = con.query("SELECT id_autor FROM mensajes WHERE id ="+id); <del> if (res.next()){ <del> int id_autor = Integer.parseInt( res.toString()); <del> return UserImpl(id_autor); <del> } <del> else throw new TwitterException ("Error al obtener el autor del mensaje"); <del> <del> return null; <del> } <del> <del> @Override <add> <ide> public String getDisplayText() { <ide> return text; <ide> } <ide> <ide> @Override <ide> public User getRecipient() { <del> ResultSet res = con.query("SELECT id_receptor FROM mensajes WHERE id ="+id); <del> if (res.next()){ <del> int id_receptor = Integer.parseInt( res.toString()); <del> return UserImpl(id_receptor); <add> ResultSet res = con.query("SELECT id_receptor FROM mensajes WHERE id ="+id+"LIMIT 1"); <add> try{ <add> if (res.next()){ <add> int id_receptor = res.getInt(1); <add> return UserImpl(id_receptor); <add> } <add> } catch (SQLException e) { <add> ServerCommon.TwitterWarning(e, "Error al obtener el receptor"); <add> e.printStackTrace(); <ide> } <del> else throw new TwitterException ("Error al obtener el autor del mensaje"); <ide> <ide> return null; <ide> } <ide> } <ide> <ide> } <add>
Java
mit
1c4236a60c7be4198437c5c03b6d9cb0dc0bba69
0
rmatil/uzh-ds
package assignment2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.TextInputFormat; import org.apache.hadoop.mapred.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class WordCount extends Configured implements Tool { private static final String INPUT_FILE = "/user/ds2013/data/plot_summaries.txt"; private static final String STOP_WORDS_FILE = "/user/ds2013/stop_words/english_stop_list.txt"; public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); private static Set<String> stopWords = new HashSet<String>(); // stopWords read from the english_stop_list.txt-file public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { // text processing and reading of the stop words String line = value.toString(); // get line line = line.toLowerCase().replace(",", "").replace(".", "").replace("-", " ").replace("\"", ""); StringTokenizer itr = new StringTokenizer(line); // get each word ("token") of this line while (itr.hasMoreTokens()) { String tmp = itr.nextToken(); if (!isStopWord(tmp) && !isMovieNumber(tmp)) { word.set(tmp); // Set to contain the contents of a string. output.collect(word, one); // Adds a key/value pair to the output } } } public void configure(JobConf pJob) { // read stop words at startup readStopWords(); } private static boolean isMovieNumber(String pWord) { Pattern p = Pattern.compile("^[0-9]+"); // at the beginning of the word, one or more than one, numbers Matcher m = p.matcher(pWord); if (m.find()) { return true; } return false; } private static boolean isStopWord(String pWord) { if (stopWords.contains(pWord)) { return true; // is a stop word } return false; } private static void readStopWords() { BufferedReader bufferedReader = null; try { // IOException FileSystem fs = FileSystem.get(new Configuration()); // Returns the configured filesystem implementation. Path infile = new Path(STOP_WORDS_FILE); // open file with stop words in it // IOException bufferedReader = new BufferedReader(new InputStreamReader(fs.open(infile))); // creates a Buffered Reader of an InputStream of an FSDataInputStream at the indicated Path. // go through the whole stop words file // readLine() returns null if end of input stream is reached String tmpLine = null; while ((tmpLine = bufferedReader.readLine()) != null) { StringTokenizer itr = new StringTokenizer(tmpLine); // go through the whole line while (itr.hasMoreTokens()) { stopWords.add(itr.nextToken()); // add word to stopWords set } } // IOException - If an I/O error occurs bufferedReader.close(); // close input stream } catch (IOException e) { e.printStackTrace(); } } } /* * Reducer */ public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int sum = 0; while (values.hasNext()) { sum += values.next().get(); } output.collect(new Text(""), new IntWritable(sum)); } } public static void main(String[] pArgs) throws Exception { int res = ToolRunner.run(new Configuration(), new WordCount(), pArgs); } @Override public int run(String[] pArgs) throws Exception { // overwrite output path FileSystem fs = FileSystem.get(new Configuration()); fs.delete(new Path(pArgs[0]), true); Configuration config = new Configuration(); JobConf conf = new JobConf(config, WordCount.class); conf.setJobName("wordcount"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setCombinerClass(Reduce.class); conf.setReducerClass(Reduce.class); conf.setMapperClass(Map.class); conf.setCombinerClass(Reduce.class); conf.setReducerClass(Reduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(INPUT_FILE)); FileOutputFormat.setOutputPath(conf, new Path(pArgs[0])); JobClient.runJob(conf); return 0; } }
ex-02/src/assignment2/WordCount.java
package assignment2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.TextInputFormat; import org.apache.hadoop.mapred.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class WordCount extends Configured implements Tool { private static final String INPUT_FILE = "/user/ds2013/data/plot_summaries.txt"; private static final String STOP_WORDS_FILE = "/user/ds2013/stop_words/english_stop_list.txt"; public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); private static Set<String> stopWords = new HashSet<String>(); // stopWords read from the english_stop_list.txt-file public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { // text processing and reading of the stop words String line = value.toString(); // get line line.toLowerCase().replace(",", "").replace(".", "").replace("-", " ").replace("\"", ""); StringTokenizer itr = new StringTokenizer(line); // get each word ("token") of this line while (itr.hasMoreTokens()) { String tmp = itr.nextToken(); if (!isStopWord(tmp) && !isMovieNumber(tmp)) { word.set(tmp); // Set to contain the contents of a string. output.collect(word, one); // Adds a key/value pair to the output } } } public void configure(JobConf pJob) { // read stop words at startup readStopWords(); } private static boolean isMovieNumber(String pWord) { Pattern p = Pattern.compile("^[0-9]+"); // at the beginning of the word, one or more than one, numbers Matcher m = p.matcher(pWord); if (m.find()) { return true; } return false; } private static boolean isStopWord(String pWord) { if (stopWords.contains(pWord)) { return true; // is a stop word } return false; } private static void readStopWords() { BufferedReader bufferedReader = null; try { // IOException FileSystem fs = FileSystem.get(new Configuration()); // Returns the configured filesystem implementation. Path infile = new Path(STOP_WORDS_FILE); // open file with stop words in it // IOException bufferedReader = new BufferedReader(new InputStreamReader(fs.open(infile))); // creates a Buffered Reader of an InputStream of an FSDataInputStream at the indicated Path. // go through the whole stop words file // readLine() returns null if end of input stream is reached String tmpLine = null; while ((tmpLine = bufferedReader.readLine()) != null) { StringTokenizer itr = new StringTokenizer(tmpLine); // go through the whole line while (itr.hasMoreTokens()) { stopWords.add(itr.nextToken()); // add word to stopWords set } } // IOException - If an I/O error occurs bufferedReader.close(); // close input stream } catch (IOException e) { e.printStackTrace(); } } } /* * Reducer */ public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int sum = 0; while (values.hasNext()) { sum += values.next().get(); } output.collect(new Text(""), new IntWritable(sum)); } } public static void main(String[] pArgs) throws Exception { int res = ToolRunner.run(new Configuration(), new WordCount(), pArgs); } @Override public int run(String[] pArgs) throws Exception { // overwrite output path FileSystem fs = FileSystem.get(new Configuration()); fs.delete(new Path(pArgs[0]), true); Configuration config = new Configuration(); JobConf conf = new JobConf(config, WordCount.class); conf.setJobName("wordcount"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setCombinerClass(Reduce.class); conf.setReducerClass(Reduce.class); conf.setMapperClass(Map.class); conf.setCombinerClass(Reduce.class); conf.setReducerClass(Reduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(INPUT_FILE)); FileOutputFormat.setOutputPath(conf, new Path(pArgs[0])); JobClient.runJob(conf); return 0; } }
Adds string replacing
ex-02/src/assignment2/WordCount.java
Adds string replacing
<ide><path>x-02/src/assignment2/WordCount.java <ide> <ide> // text processing and reading of the stop words <ide> String line = value.toString(); // get line <del> line.toLowerCase().replace(",", "").replace(".", "").replace("-", " ").replace("\"", ""); <add> line = line.toLowerCase().replace(",", "").replace(".", "").replace("-", " ").replace("\"", ""); <ide> <ide> StringTokenizer itr = new StringTokenizer(line); // get each word ("token") of this line <ide>
JavaScript
bsd-2-clause
51ea092f246e871a17b2dce1fdb13e5480350e44
0
cyber-dojo/web,cyber-dojo/web,cyber-dojo/web,cyber-dojo/web
/*global jQuery,cyberDojo*/ 'use strict'; var cyberDojo = (function(cd, $) { //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Filenames //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - let theCurrentFilename = ''; let theLastNonOutputFilename = ''; let theLastOutputFilename = 'stdout'; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Load a named file //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadFile = (filename) => { fileDiv(cd.currentFilename()).hide(); fileDiv(filename).show(); selectFileInFileList(filename); cd.focusSyntaxHighlightEditor(filename); theCurrentFilename = filename; if (cd.isOutputFile(filename)) { theLastOutputFilename = filename; } else { theLastNonOutputFilename = filename; } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadTestOutputFiles = (colour, stdout, stderr, status) => { cd.fileChange('stdout', { content: stdout }); cd.fileChange('stderr', { content: stderr }); cd.fileChange('status', { content: status }); if (colour === 'timed_out') { cd.loadFile('status'); // timed-out: status == '137' } else if (stdout.length > stderr.length) { cd.loadFile('stdout'); } else { cd.loadFile('stderr'); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.currentFilename = () => theCurrentFilename; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.eachFilename = (f) => cd.filenames().forEach(f); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.filenames = () => { // Gets the kata/edit page filenames. The review/show // page/dialog collects filenames in its own way. const filenames = []; const prefix = 'file_content_for_'; $(`textarea[id^=${prefix}]`).each(function(_) { const id = $(this).attr('id'); const filename = id.substr(prefix.length, id.length - prefix.length); filenames.push(filename); }); return filenames; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.sortedFilenames = (filenames) => { // Controls the order of files in the filename-list // Used in two places // 1. kata/edit page to help show filename-list // 2. review/show page/dialog to help show filename-list const output = ['stdout','stderr','status']; return [].concat(hiFilenames(filenames), output, loFilenames(filenames)); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Filename hot-key navigation //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // See app/assets/javascripts/cyber-dojo_codemirror.js // See app/views/shared/_hotkeys.html.erb // Alt-J ==> loadNextFile() // Alt-K ==> loadPreviousFile() // Alt-O ==> toggleOutputFile() cd.loadNextFile = () => { const hi = hiFilenames(cd.filenames()); const index = $.inArray(cd.currentFilename(), hi); if (index === -1) { const next = 0; cd.loadFile(hi[next]); } else { const next = (index + 1) % hi.length; cd.loadFile(hi[next]); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadPreviousFile = () => { const hi = hiFilenames(cd.filenames()); const index = $.inArray(cd.currentFilename(), hi); if (index === 0 || index === -1) { const previous = hi.length - 1; cd.loadFile(hi[previous]); } else { const previous = index - 1; cd.loadFile(hi[previous]); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.toggleOutputFile = () => { if (cd.isOutputFile(cd.currentFilename())) { cd.loadFile(theLastNonOutputFilename); } else { cd.loadFile(theLastOutputFilename); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // new-file, rename-file, delete-file //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // See app/views/kata/_file_new_rename_delete.html.erb // See app/views/kata/_files.html.erb // See app/views/kata/_run_tests.js.erb cd.fileChange = (filename, file) => { cd.fileDelete(filename); cd.fileCreate(filename, file); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.fileCreate = (filename, file) => { const newFile = makeNewFile(filename, file); $('#visible-files-container').append(newFile); rebuildFilenameList(); cd.switchEditorToCodeMirror(filename); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.fileDelete = (filename) => { fileDiv(filename).remove(); rebuildFilenameList(); theLastNonOutputFilename = testFilename(); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.fileRename = (oldFilename, newFilename) => { // This should restore the caret/cursor/selection // but it currently does not. See // https://github.com/cyber-dojo/web/issues/51 const content = fileContent(oldFilename); cd.fileDelete(oldFilename); cd.fileCreate(newFilename, { content:content }); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Helpers //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.editorRefocus = () => { cd.loadFile(cd.currentFilename()); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadTestFile = () => { cd.loadFile(testFilename()); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.radioEntrySwitch = (previous, current) => { // Used in test-page, setup-pages, and history/diff-dialog // See app/assets/stylesheets/wide-list-item.scss if (previous !== undefined) { previous.removeClass('selected'); } current.addClass('selected'); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const testFilename = () => { // When starting and in filename-list navigation // when the current file is deleted, try to // select a test file. const filenames = cd.filenames(); for (let i = 0; i < filenames.length; i++) { // split into dir names and filename const parts = filenames[i].toLowerCase().split('/'); // careful to return the whole dirs+filename // and with the original case const filename = parts[parts.length - 1]; if (filename.search('test') !== -1) { return filenames[i]; } if (filename.search('spec') !== -1) { return filenames[i]; } } return filenames[0]; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const fileContent = (filename) => { cd.saveCodeFromIndividualSyntaxHighlightEditor(filename); return jqElement(`file_content_for_${filename}`).val(); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const jqElement = (name) => { return $(`[id="${name}"]`); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const fileDiv = (filename) => { return jqElement(`${filename}_div`); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const makeNewFile = (filename, file) => { const div = $('<div>', { 'class': 'filename_div', id: `${filename}_div` }); const text = $('<textarea>', { 'class': 'file_content', 'spellcheck': 'false', 'data-filename': filename, name: `file_content[${filename}]`, id: `file_content_for_${filename}` //wrap: 'off' }); // For some reason, setting wrap cannot be done as per the // commented out line above... when you create a new file in // FireFox 17.0.1 it still wraps at the textarea width. // So instead I do it like this, which works in FireFox?! text.attr('wrap', 'off'); text.val(file['content']); div.append(text); return div; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const setRenameAndDeleteButtons = (filename) => { const fileOps = $('#file-operations'); const renameFile = fileOps.find('#rename'); const deleteFile = fileOps.find('#delete'); const disable = (node) => node.prop('disabled', true ); const enable = (node) => node.prop('disabled', false); if (cantBeRenamedOrDeleted(filename)) { disable(renameFile); disable(deleteFile); } else { enable(renameFile); enable(deleteFile); } }; const cantBeRenamedOrDeleted = (filename) => { return cd.isOutputFile(filename) || filename == 'cyber-dojo.sh'; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const rebuildFilenameList = () => { const filenameList = $('#filename-list'); filenameList.empty(); $.each(cd.sortedFilenames(cd.filenames()), (_, filename) => { filenameList.append(makeFileListEntry(filename)); }); }; const makeFileListEntry = (filename) => { const div = $('<div>', { 'class': 'filename', id: `radio_${filename}`, text: filename }); if (cd.inArray(filename, cd.highlightFilenames())) { div.addClass('highlight'); } div.click(() => { cd.loadFile(filename); }); return div; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const selectFileInFileList = (filename) => { // Can't do $('radio_' + filename) because filename // could contain characters that aren't strictly legal // characters in a dom node id so I do this instead... const node = $(`[id="radio_${filename}"]`); const previousFilename = cd.currentFilename(); const previous = $(`[id="radio_${previousFilename}"]`); cd.radioEntrySwitch(previous, node); setRenameAndDeleteButtons(filename); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const highlightSorter = (lhs,rhs) => { const lit = cd.highlightFilenames(); const lhsLit = lit.includes(lhs); const rhsLit = lit.includes(rhs); if (lhsLit && !rhsLit) { return -1; } else if (!lhsLit && rhsLit) { return +1; } else if (lhs < rhs) { return -1; } else if (lhs > rhs) { return +1; } else { return 0; } }; const hiFilenames = (filenames) => { // Controls which filenames appear at the // top of the filename-list, above 'output' // Used in three places. // 1. kata/edit page to help show filename list // 2. kata/edit page in alt-j alt-k hotkeys // 3. review/show page/dialog to help show filename list let hi = []; const lit = cd.highlightFilenames(); $.each(filenames, (_, filename) => { if (isSourceFile(filename) || lit.includes(filename)) { hi.push(filename); } }); hi.sort(highlightSorter); hi = hi.filter(filename => !cd.isOutputFile(filename)); return hi; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const loFilenames = (filenames) => { // Controls which filenames appear at the // bottom of the filename list, below 'output' // Used in three places. // 1. kata/edit page to help show filename-list // 2. kata/edit page in Alt-j Alt-k hotkeys // 3. review/show page/dialog to help show filename-list let lo = []; const lit = cd.highlightFilenames(); $.each(filenames, (_, filename) => { if (!isSourceFile(filename) && !lit.includes(filename)) { lo.push(filename); } }); lo.sort(); lo = lo.filter(filename => !cd.isOutputFile(filename)); return lo; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.isOutputFile = (filename) => { if (filename === 'stdout') return true; if (filename === 'stderr') return true; if (filename === 'status') return true; return false; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const isSourceFile = (filename) => { let match = false; $.each(cd.extensionFilenames(), (_, extension) => { // Shell test frameworks (eg shunit2) use .sh as their // filename extension but we don't want cyber-dojo.sh // in the hiFilenames() above output in the filename-list. if (filename.endsWith(extension) && filename !== 'cyber-dojo.sh') { match = true; } }); return match; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return cd; })(cyberDojo || {}, jQuery);
app/assets/javascripts/cyber-dojo_files.js
/*global jQuery,cyberDojo*/ 'use strict'; var cyberDojo = (function(cd, $) { //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Filenames //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - let theCurrentFilename = ''; let theLastNonOutputFilename = ''; let theLastOutputFilename = 'stdout'; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Load a named file //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadFile = (filename) => { fileDiv(cd.currentFilename()).hide(); fileDiv(filename).show(); selectFileInFileList(filename); cd.focusSyntaxHighlightEditor(filename); theCurrentFilename = filename; if (cd.isOutputFile(filename)) { theLastOutputFilename = filename; } else { theLastNonOutputFilename = filename; } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadTestOutputFiles = (colour, stdout, stderr, status) => { cd.fileChange('stdout', { content: stdout }); cd.fileChange('stderr', { content: stderr }); cd.fileChange('status', { content: status }); if (colour === 'timed_out') { cd.loadFile('status'); // timed-out: status == '137' } else if (stdout.length > stderr.length) { cd.loadFile('stdout'); } else { cd.loadFile('stderr'); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.currentFilename = () => theCurrentFilename; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.eachFilename = (f) => cd.filenames().forEach(f); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.filenames = () => { // Gets the kata/edit page filenames. The review/show // page/dialog collects filenames in its own way. const filenames = []; const prefix = 'file_content_for_'; $(`textarea[id^=${prefix}]`).each(function(_) { const id = $(this).attr('id'); const filename = id.substr(prefix.length, id.length - prefix.length); filenames.push(filename); }); return filenames; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.sortedFilenames = (filenames) => { // Controls the order of files in the filename-list // Used in two places // 1. kata/edit page to help show filename-list // 2. review/show page/dialog to help show filename-list const output = ['stdout','stderr','status']; return [].concat(hiFilenames(filenames), output, loFilenames(filenames)); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Filename hot-key navigation //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // See app/assets/javascripts/cyber-dojo_codemirror.js // See app/views/shared/_hotkeys.html.erb // Alt-J ==> loadNextFile() // Alt-K ==> loadPreviousFile() // Alt-O ==> toggleOutputFile() cd.loadNextFile = () => { const hi = hiFilenames(cd.filenames()); const index = $.inArray(cd.currentFilename(), hi); if (index === -1) { const next = 0; cd.loadFile(hi[next]); } else { const next = (index + 1) % hi.length; cd.loadFile(hi[next]); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadPreviousFile = () => { const hi = hiFilenames(cd.filenames()); const index = $.inArray(cd.currentFilename(), hi); if (index === 0 || index === -1) { const previous = hi.length - 1; cd.loadFile(hi[previous]); } else { const previous = index - 1; cd.loadFile(hi[previous]); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.toggleOutputFile = () => { if (cd.isOutputFile(cd.currentFilename())) { cd.loadFile(theLastNonOutputFilename); } else { cd.loadFile(theLastOutputFilename); } }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // new-file, rename-file, delete-file //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // See app/views/kata/_file_new_rename_delete.html.erb // See app/views/kata/_files.html.erb // See app/views/kata/_run_tests.js.erb cd.fileChange = (filename, file) => { cd.fileDelete(filename); cd.fileCreate(filename, file); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.fileCreate = (filename, file) => { const newFile = makeNewFile(filename, file); $('#visible-files-container').append(newFile); rebuildFilenameList(); cd.switchEditorToCodeMirror(filename); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.fileDelete = (filename) => { fileDiv(filename).remove(); rebuildFilenameList(); theLastNonOutputFilename = testFilename(); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.fileRename = (oldFilename, newFilename) => { // This should restore the caret/cursor/selection // but it currently does not. See // https://github.com/cyber-dojo/web/issues/51 const content = fileContent(oldFilename); cd.fileDelete(oldFilename); cd.fileCreate(newFilename, { content:content }); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Helpers //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.editorRefocus = () => { cd.loadFile(cd.currentFilename()); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.loadTestFile = () => { cd.loadFile(testFilename()); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.radioEntrySwitch = (previous, current) => { // Used in test-page, setup-pages, and history/diff-dialog // See app/assets/stylesheets/wide-list-item.scss if (previous !== undefined) { previous.removeClass('selected'); } current.addClass('selected'); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const testFilename = () => { // When starting and in filename-list navigation // when the current file is deleted, try to // select a test file. const filenames = cd.filenames(); for (let i = 0; i < filenames.length; i++) { // split into dir names and filename const parts = filenames[i].toLowerCase().split('/'); // careful to return the whole dirs+filename // and with the original case const filename = parts[parts.length - 1]; if (filename.search('test') !== -1) { return filenames[i]; } if (filename.search('spec') !== -1) { return filenames[i]; } } return filenames[0]; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const fileContent = (filename) => { cd.saveCodeFromIndividualSyntaxHighlightEditor(filename); return jqElement(`file_content_for_${filename}`).val(); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const jqElement = (name) => { return $(`[id="${name}"]`); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const fileDiv = (filename) => { return jqElement(`${filename}_div`); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const makeNewFile = (filename, file) => { const div = $('<div>', { 'class': 'filename_div', id: `${filename}_div` }); const text = $('<textarea>', { 'class': 'file_content', 'spellcheck': 'false', 'data-filename': filename, name: `file_content[${filename}]`, id: `file_content_for_${filename}` //wrap: 'off' }); // For some reason, setting wrap cannot be done as per the // commented out line above... when you create a new file in // FireFox 17.0.1 it still wraps at the textarea width. // So instead I do it like this, which works in FireFox?! text.attr('wrap', 'off'); text.val(file['content']); div.append(text); return div; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const setRenameAndDeleteButtons = (filename) => { const fileOps = $('#file-operations'); const renameFile = fileOps.find('#rename'); const deleteFile = fileOps.find('#delete'); const disable = (node) => node.prop('disabled', true ); const enable = (node) => node.prop('disabled', false); if (cantBeRenamedOrDeleted(filename)) { disable(renameFile); disable(deleteFile); } else { enable(renameFile); enable(deleteFile); } }; const cantBeRenamedOrDeleted = (filename) => { return cd.isOutputFile(filename) || filename == 'cyber-dojo.sh'; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const rebuildFilenameList = () => { const filenameList = $('#filename-list'); filenameList.empty(); $.each(cd.sortedFilenames(cd.filenames()), (_, filename) => { filenameList.append(makeFileListEntry(filename)); }); }; const makeFileListEntry = (filename) => { const div = $('<div>', { 'class': 'filename', id: `radio_${filename}`, text: filename }); if (cd.inArray(filename, cd.highlightFilenames())) { div.addClass('highlight'); } div.click(() => { cd.loadFile(filename); }); return div; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const selectFileInFileList = (filename) => { // Can't do $('radio_' + filename) because filename // could contain characters that aren't strictly legal // characters in a dom node id so I do this instead... const node = $(`[id="radio_${filename}"]`); const previousFilename = cd.currentFilename(); const previous = $(`[id="radio_${previousFilename}"]`); cd.radioEntrySwitch(previous, node); setRenameAndDeleteButtons(filename); }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const highlightSorter = (lhs,rhs) => { const lit = cd.highlightFilenames(); const lhsLit = lit.includes(lhs); const rhsLit = lit.includes(rhs); if (lhsLit && !rhsLit) { return -1; } else if (!lhsLit && rhsLit) { return +1; } else if (lhs < rhs) { return -1; } else if (lhs > rhs) { return +1; } else { return 0; } }; const hiFilenames = (filenames) => { // Controls which filenames appear at the // top of the filename-list, above 'output' // Used in three places. // 1. kata/edit page to help show filename list // 2. kata/edit page in alt-j alt-k hotkeys // 3. review/show page/dialog to help show filename list let hi = []; $.each(filenames, (_, filename) => { if (isSourceFile(filename)) { hi.push(filename); } }); hi.sort(highlightSorter); hi = hi.filter(filename => !cd.isOutputFile(filename)); return hi; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const loFilenames = (filenames) => { // Controls which filenames appear at the // bottom of the filename list, below 'output' // Used in three places. // 1. kata/edit page to help show filename-list // 2. kata/edit page in Alt-j Alt-k hotkeys // 3. review/show page/dialog to help show filename-list let lo = []; $.each(filenames, (_, filename) => { if (!isSourceFile(filename)) { lo.push(filename); } }); lo.sort(); lo = lo.filter(filename => !cd.isOutputFile(filename)); return lo; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cd.isOutputFile = (filename) => { if (filename === 'stdout') return true; if (filename === 'stderr') return true; if (filename === 'status') return true; return false; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const isSourceFile = (filename) => { let match = false; $.each(cd.extensionFilenames(), (_, extension) => { // Shell test frameworks (eg shunit2) use .sh as their // filename extension but we don't want cyber-dojo.sh // in the hiFilenames() above output in the filename-list. if (filename.endsWith(extension) && filename !== 'cyber-dojo.sh') { match = true; } }); return match; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - return cd; })(cyberDojo || {}, jQuery);
Ensure highlight_filenames appear in the top section of the filenames
app/assets/javascripts/cyber-dojo_files.js
Ensure highlight_filenames appear in the top section of the filenames
<ide><path>pp/assets/javascripts/cyber-dojo_files.js <ide> // 2. kata/edit page in alt-j alt-k hotkeys <ide> // 3. review/show page/dialog to help show filename list <ide> let hi = []; <add> const lit = cd.highlightFilenames(); <ide> $.each(filenames, (_, filename) => { <del> if (isSourceFile(filename)) { <add> if (isSourceFile(filename) || lit.includes(filename)) { <ide> hi.push(filename); <ide> } <ide> }); <ide> // 2. kata/edit page in Alt-j Alt-k hotkeys <ide> // 3. review/show page/dialog to help show filename-list <ide> let lo = []; <add> const lit = cd.highlightFilenames(); <ide> $.each(filenames, (_, filename) => { <del> if (!isSourceFile(filename)) { <add> if (!isSourceFile(filename) && !lit.includes(filename)) { <ide> lo.push(filename); <ide> } <ide> });
Java
mit
5a513478377a90f193da7f5888029ca3abd72ce6
0
sideshowcecil/myx-monitor,sideshowcecil/myx-monitor
package at.ac.tuwien.dsg.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; /** * An extension to the {@link ExecutorService} interface that allow to * execute tasks on specific {@link Thread}s using identifiers. */ public interface IdentifiableExecutorService extends ExecutorService { /** * Executes the given command at some time in the future. The command may * execute in a new thread, in a pooled thread, or in the calling thread, * at the discretion of the {@code Executor} implementation. This method * guarantees that a {@link Runnable} with the same identifier is always * executed by the same {@link Thread}. * * @param command * the runnable task * @param identifier * the identifier * @throws RejectedExecutionException * if this task cannot be accepted for execution * @throws NullPointerException * if command is null */ public void execute(Runnable command, int identifier); }
myx-monitor/src/main/java/at/ac/tuwien/dsg/concurrent/IdentifiableExecutorService.java
package at.ac.tuwien.dsg.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; /** * An extension to the {@link ExecutorService} interface that allow to execute * tasks on specific {@link Thread}s using identifiers. * * @author bernd.rathmanner * */ public interface IdentifiableExecutorService extends ExecutorService { /** * Executes the given command at some time in the future. The command may * execute in a new thread, in a pooled thread, or in the calling thread, at * the discretion of the {@code Executor} implementation. * * @param command * the runnable task * @param identifier * the identifier * @throws RejectedExecutionException * if this task cannot be accepted for execution * @throws NullPointerException * if command is null */ public void execute(Runnable command, int identifier); }
updates the javadoc of IdentifiableExecutorService
myx-monitor/src/main/java/at/ac/tuwien/dsg/concurrent/IdentifiableExecutorService.java
updates the javadoc of IdentifiableExecutorService
<ide><path>yx-monitor/src/main/java/at/ac/tuwien/dsg/concurrent/IdentifiableExecutorService.java <ide> import java.util.concurrent.RejectedExecutionException; <ide> <ide> /** <del> * An extension to the {@link ExecutorService} interface that allow to execute <del> * tasks on specific {@link Thread}s using identifiers. <del> * <del> * @author bernd.rathmanner <del> * <add> * An extension to the {@link ExecutorService} interface that allow to <add> * execute tasks on specific {@link Thread}s using identifiers. <ide> */ <ide> public interface IdentifiableExecutorService extends ExecutorService { <ide> /** <ide> * Executes the given command at some time in the future. The command may <del> * execute in a new thread, in a pooled thread, or in the calling thread, at <del> * the discretion of the {@code Executor} implementation. <add> * execute in a new thread, in a pooled thread, or in the calling thread, <add> * at the discretion of the {@code Executor} implementation. This method <add> * guarantees that a {@link Runnable} with the same identifier is always <add> * executed by the same {@link Thread}. <ide> * <ide> * @param command <ide> * the runnable task
Java
mpl-2.0
d225f2b95c887041007bd5c12739253ddc5d5717
0
opensensorhub/osh-android
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to 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/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.android; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import org.sensorhub.android.comm.BluetoothCommProvider; import org.sensorhub.api.common.SensorHubException; import org.sensorhub.api.module.IModuleConfigRepository; import org.sensorhub.api.sensor.ISensorDataInterface; import org.sensorhub.impl.client.sost.SOSTClient; import org.sensorhub.impl.client.sost.SOSTClient.StreamInfo; import org.sensorhub.impl.client.sost.SOSTClientConfig; import org.sensorhub.impl.comm.BluetoothConfig; import org.sensorhub.impl.module.InMemoryConfigDb; import org.sensorhub.impl.sensor.android.AndroidSensorsConfig; import org.sensorhub.impl.sensor.trupulse.TruPulseConfig; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.preference.PreferenceManager; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.TextView; public class MainActivity extends Activity implements SurfaceHolder.Callback { TextView textArea; SensorHubService boundService; IModuleConfigRepository sensorhubConfig; Timer statusTimer; Handler displayHandler; StringBuilder displayText = new StringBuilder(); SurfaceHolder camPreviewSurfaceHolder; private ServiceConnection sConn = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { boundService = ((SensorHubService.LocalBinder) service).getService(); boundService.startSensorHub(sensorhubConfig); startStatusDisplay(); } public void onServiceDisconnected(ComponentName className) { boundService = null; } }; @SuppressLint("HandlerLeak") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textArea = (TextView) findViewById(R.id.text); SurfaceView camPreview = (SurfaceView) findViewById(R.id.textureView1); camPreview.getHolder().addCallback(this); displayHandler = new Handler() { public void handleMessage(Message msg) { textArea.setText(Html.fromHtml(displayText.toString())); } }; } protected void updateConfig(SharedPreferences prefs) { sensorhubConfig.close(); AndroidSensorsConfig sensorsConfig = new AndroidSensorsConfig(); sensorsConfig.id = "ANDROID_SENSORS"; sensorsConfig.name = "Android Sensors"; sensorsConfig.enabled = true; sensorsConfig.activateAccelerometer = prefs.getBoolean("accel_enabled", false); sensorsConfig.activateGyrometer = prefs.getBoolean("gyro_enabled", false); sensorsConfig.activateMagnetometer = prefs.getBoolean("mag_enabled", false); sensorsConfig.activateOrientationQuat = prefs.getBoolean("orient_quat_enabled", false); sensorsConfig.activateOrientationEuler = prefs.getBoolean("orient_euler_enabled", false); sensorsConfig.activateGpsLocation = prefs.getBoolean("gps_enabled", false); sensorsConfig.activateNetworkLocation = prefs.getBoolean("netloc_enabled", false); sensorsConfig.activateBackCamera = prefs.getBoolean("cam_enabled", false); sensorsConfig.androidContext = this.getApplicationContext(); sensorsConfig.camPreviewSurfaceHolder = this.camPreviewSurfaceHolder; sensorhubConfig.add(sensorsConfig); SOSTClientConfig sosConfig1 = new SOSTClientConfig(); sosConfig1.id = "SOST_CLIENT1"; sosConfig1.name = "SOS-T Client for Android Sensors"; sosConfig1.enabled = true; sosConfig1.sensorID = sensorsConfig.id; sosConfig1.sosEndpointUrl = prefs.getString("sos_uri", ""); sosConfig1.usePersistentConnection = true; sensorhubConfig.add(sosConfig1); TruPulseConfig trupulseConfig = new TruPulseConfig(); trupulseConfig.id = "TruPulse"; trupulseConfig.name = "TruPulse Ranger"; trupulseConfig.enabled = true; BluetoothConfig btConf = new BluetoothConfig(); btConf.providerClass = BluetoothCommProvider.class.getCanonicalName(); btConf.deviceName = "TP360RB.*"; trupulseConfig.commSettings = btConf; sensorhubConfig.add(trupulseConfig); SOSTClientConfig sosConfig2 = new SOSTClientConfig(); sosConfig2.id = "SOST_CLIENT1"; sosConfig2.name = "SOS-T Client for TruPulse Sensor"; sosConfig2.enabled = true; sosConfig2.sensorID = trupulseConfig.id; sosConfig2.sosEndpointUrl = prefs.getString("sos_uri", ""); sosConfig2.usePersistentConnection = true; sensorhubConfig.add(sosConfig2); } protected SOSTClient getSosClient() { if (boundService.getSensorHub() == null) return null; try { return (SOSTClient) boundService.getSensorHub().getModuleRegistry().getModuleById("SOST_CLIENT1"); } catch (SensorHubException e) { return null; } } protected void startStatusDisplay() { statusTimer = new Timer(); statusTimer.scheduleAtFixedRate(new TimerTask() { public void run() { displayText.setLength(0); if (boundService == null || boundService.getSensorHub() == null) { displayText.append("Waiting for SensorHub service to start..."); } else if (getSosClient() == null || !getSosClient().isConnected()) { displayText.append("<font color='red'><b>Cannot connect to SOS-T</b></font><br/>"); displayText.append("Please check your settings..."); } else { Map<ISensorDataInterface, StreamInfo> dataStreams = getSosClient().getDataStreams(); if (dataStreams.size() > 0) displayText.append("<p>Registered with SOS-T</p><p>"); long now = System.currentTimeMillis(); for (Entry<ISensorDataInterface, StreamInfo> stream : dataStreams.entrySet()) { displayText.append("<b>" + stream.getKey().getName() + " : </b>"); if (now - stream.getValue().lastEventTime > 2000) displayText.append("<font color='red'>NOK</font>"); else displayText.append("<font color='green'>OK</font>"); if (stream.getValue().errorCount > 0) { displayText.append("<font color='red'> ("); displayText.append(stream.getValue().errorCount); displayText.append(")</font>"); } displayText.append("<br/>"); } displayText.append("</p>"); } displayHandler.obtainMessage(1).sendToTarget(); } }, 0, 1000L); } protected void stopStatusDisplay() { if (statusTimer != null) statusTimer.cancel(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { startActivity(new Intent(this, UserSettingsActivity.class)); return true; } else if (id == R.id.action_restart) { if (boundService != null) { boundService.stopSensorHub(); updateConfig(PreferenceManager.getDefaultSharedPreferences(this)); boundService.startSensorHub(sensorhubConfig); } return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { startStatusDisplay(); super.onResume(); } @Override protected void onPause() { stopStatusDisplay(); super.onPause(); } @Override protected void onDestroy() { Context context = this.getApplicationContext(); context.stopService(new Intent(context, SensorHubService.class)); super.onDestroy(); } @Override public void surfaceCreated(SurfaceHolder holder) { this.camPreviewSurfaceHolder = holder; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); /*SharedPreferences.Editor editor = prefs.edit(); editor.clear(); editor.commit(); PreferenceManager.setDefaultValues(this, R.xml.pref_general, true);*/ // update config from user settings sensorhubConfig = new InMemoryConfigDb(); updateConfig(prefs); // start SensorHub service Context context = this.getApplicationContext(); Intent intent = new Intent(context, SensorHubService.class); //context.startService(intent); context.bindService(intent, sConn, Context.BIND_AUTO_CREATE); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }
sensorhub-android-app/src/org/sensorhub/android/MainActivity.java
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to 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/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package org.sensorhub.android; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import org.sensorhub.android.comm.BluetoothCommProvider; import org.sensorhub.api.common.SensorHubException; import org.sensorhub.api.module.IModuleConfigRepository; import org.sensorhub.api.sensor.ISensorDataInterface; import org.sensorhub.impl.client.sost.SOSTClient; import org.sensorhub.impl.client.sost.SOSTClient.StreamInfo; import org.sensorhub.impl.client.sost.SOSTClientConfig; import org.sensorhub.impl.comm.BluetoothConfig; import org.sensorhub.impl.module.InMemoryConfigDb; import org.sensorhub.impl.sensor.android.AndroidSensorsConfig; import org.sensorhub.impl.sensor.trupulse.TruPulseConfig; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.preference.PreferenceManager; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.TextView; public class MainActivity extends Activity implements SurfaceHolder.Callback { TextView textArea; SensorHubService boundService; IModuleConfigRepository sensorhubConfig; Timer statusTimer; Handler displayHandler; StringBuilder displayText = new StringBuilder(); SurfaceHolder camPreviewSurfaceHolder; private ServiceConnection sConn = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { boundService = ((SensorHubService.LocalBinder) service).getService(); boundService.startSensorHub(sensorhubConfig); startStatusDisplay(); } public void onServiceDisconnected(ComponentName className) { boundService = null; } }; @SuppressLint("HandlerLeak") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textArea = (TextView) findViewById(R.id.text); SurfaceView camPreview = (SurfaceView) findViewById(R.id.textureView1); camPreview.getHolder().addCallback(this); displayHandler = new Handler() { public void handleMessage(Message msg) { textArea.setText(Html.fromHtml(displayText.toString())); } }; } protected void updateConfig(SharedPreferences prefs) { sensorhubConfig.close(); AndroidSensorsConfig sensorsConfig = new AndroidSensorsConfig(); sensorsConfig.id = "ANDROID_SENSORS"; sensorsConfig.name = "Android Sensors"; sensorsConfig.enabled = true; sensorsConfig.activateAccelerometer = prefs.getBoolean("accel_enabled", false); sensorsConfig.activateGyrometer = prefs.getBoolean("gyro_enabled", false); sensorsConfig.activateMagnetometer = prefs.getBoolean("mag_enabled", false); sensorsConfig.activateOrientationQuat = prefs.getBoolean("orient_quat_enabled", false); sensorsConfig.activateOrientationEuler = prefs.getBoolean("orient_euler_enabled", false); sensorsConfig.activateGpsLocation = prefs.getBoolean("gps_enabled", false); sensorsConfig.activateNetworkLocation = prefs.getBoolean("netloc_enabled", false); sensorsConfig.activateBackCamera = prefs.getBoolean("cam_enabled", false); sensorsConfig.androidContext = this.getApplicationContext(); sensorsConfig.camPreviewSurfaceHolder = this.camPreviewSurfaceHolder; sensorhubConfig.add(sensorsConfig); SOSTClientConfig sosConfig1 = new SOSTClientConfig(); sosConfig1.id = "SOST_CLIENT1"; sosConfig1.name = "SOS-T Client for Android Sensors"; sosConfig1.enabled = true; sosConfig1.sensorID = sensorsConfig.id; sosConfig1.sosEndpointUrl = prefs.getString("sos_uri", ""); sosConfig1.usePersistentConnection = true; sensorhubConfig.add(sosConfig1); TruPulseConfig trupulseConfig = new TruPulseConfig(); trupulseConfig.id = "TruPulse"; trupulseConfig.name = "TruPulse Ranger"; trupulseConfig.enabled = true; BluetoothConfig btConf = new BluetoothConfig(); btConf.providerClass = BluetoothCommProvider.class.getCanonicalName(); btConf.deviceName = "TP360RB.*"; trupulseConfig.commSettings = btConf; sensorhubConfig.add(trupulseConfig); SOSTClientConfig sosConfig2 = new SOSTClientConfig(); sosConfig2.id = "SOST_CLIENT1"; sosConfig2.name = "SOS-T Client for TruPulse Sensor"; sosConfig2.enabled = true; sosConfig2.sensorID = trupulseConfig.id; sosConfig2.sosEndpointUrl = prefs.getString("sos_uri", ""); sosConfig2.usePersistentConnection = true; sensorhubConfig.add(sosConfig2); } protected SOSTClient getSosClient() { if (boundService.getSensorHub() == null) return null; try { return (SOSTClient) boundService.getSensorHub().getModuleRegistry().getModuleById("SOST_CLIENT"); } catch (SensorHubException e) { return null; } } protected void startStatusDisplay() { statusTimer = new Timer(); statusTimer.scheduleAtFixedRate(new TimerTask() { public void run() { displayText.setLength(0); if (boundService == null || boundService.getSensorHub() == null) { displayText.append("Waiting for SensorHub service to start..."); } else if (getSosClient() == null || !getSosClient().isConnected()) { displayText.append("<font color='red'><b>Cannot connect to SOS-T</b></font><br/>"); displayText.append("Please check your settings..."); } else { Map<ISensorDataInterface, StreamInfo> dataStreams = getSosClient().getDataStreams(); if (dataStreams.size() > 0) displayText.append("<p>Registered with SOS-T</p><p>"); long now = System.currentTimeMillis(); for (Entry<ISensorDataInterface, StreamInfo> stream : dataStreams.entrySet()) { displayText.append("<b>" + stream.getKey().getName() + " : </b>"); if (now - stream.getValue().lastEventTime > 2000) displayText.append("<font color='red'>NOK</font>"); else displayText.append("<font color='green'>OK</font>"); if (stream.getValue().errorCount > 0) { displayText.append("<font color='red'> ("); displayText.append(stream.getValue().errorCount); displayText.append(")</font>"); } displayText.append("<br/>"); } displayText.append("</p>"); } displayHandler.obtainMessage(1).sendToTarget(); } }, 0, 1000L); } protected void stopStatusDisplay() { if (statusTimer != null) statusTimer.cancel(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { startActivity(new Intent(this, UserSettingsActivity.class)); return true; } else if (id == R.id.action_restart) { if (boundService != null) { boundService.stopSensorHub(); updateConfig(PreferenceManager.getDefaultSharedPreferences(this)); boundService.startSensorHub(sensorhubConfig); } return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { startStatusDisplay(); super.onResume(); } @Override protected void onPause() { stopStatusDisplay(); super.onPause(); } @Override protected void onDestroy() { Context context = this.getApplicationContext(); context.stopService(new Intent(context, SensorHubService.class)); super.onDestroy(); } @Override public void surfaceCreated(SurfaceHolder holder) { this.camPreviewSurfaceHolder = holder; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); /*SharedPreferences.Editor editor = prefs.edit(); editor.clear(); editor.commit(); PreferenceManager.setDefaultValues(this, R.xml.pref_general, true);*/ // update config from user settings sensorhubConfig = new InMemoryConfigDb(); updateConfig(prefs); // start SensorHub service Context context = this.getApplicationContext(); Intent intent = new Intent(context, SensorHubService.class); //context.startService(intent); context.bindService(intent, sConn, Context.BIND_AUTO_CREATE); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }
Bug fix for Android App
sensorhub-android-app/src/org/sensorhub/android/MainActivity.java
Bug fix for Android App
<ide><path>ensorhub-android-app/src/org/sensorhub/android/MainActivity.java <ide> <ide> try <ide> { <del> return (SOSTClient) boundService.getSensorHub().getModuleRegistry().getModuleById("SOST_CLIENT"); <add> return (SOSTClient) boundService.getSensorHub().getModuleRegistry().getModuleById("SOST_CLIENT1"); <ide> } <ide> catch (SensorHubException e) <ide> {
Java
apache-2.0
e6516fe8055b9728f36ea5d92ab702e70e5484b7
0
lorensen/VTKExamples,lorensen/VTKExamples,lorensen/VTKExamples,lorensen/VTKExamples,lorensen/VTKExamples,lorensen/VTKExamples,lorensen/VTKExamples
import vtk.vtkActor; import vtk.vtkNamedColors; import vtk.vtkNativeLibrary; import vtk.vtkPolyDataMapper; import vtk.vtkRenderWindow; import vtk.vtkRenderWindowInteractor; import vtk.vtkRenderer; import vtk.vtkPlatonicSolidSource; import vtk.vtkPolyDataNormals; import vtk.vtkTextProperty; import vtk.vtkCubeAxesActor2D; import vtk.vtkLODActor; import vtk.vtkOutlineFilter; public class CubeAxesActor2D { // ----------------------------------------------------------------- // Load VTK library and print which library was not properly loaded static { if (!vtkNativeLibrary.LoadAllNativeLibraries()) { for (vtkNativeLibrary lib : vtkNativeLibrary.values()) { if (!lib.IsLoaded()) { System.out.println(lib.GetLibraryName() + " not loaded"); } } } vtkNativeLibrary.DisableOutputWindow(null); } // ----------------------------------------------------------------- public static void main(String s[]) { vtkNamedColors colors = new vtkNamedColors(); //For icosahedron_actor Color double icosahedronActorColor[] = new double[4]; //For outline actor Color double outlineActorColor[] = new double[4]; //Renderer Background Color double Bgcolor[] = new double[4]; colors.GetColor("Magenta", icosahedronActorColor); colors.GetColor("Black", outlineActorColor); colors.GetColor("DarkSlateBlue", Bgcolor); vtkPlatonicSolidSource icosahedron = new vtkPlatonicSolidSource(); icosahedron.SetSolidTypeToIcosahedron(); // Create a vtkPolyDataNormals filter to calculate the normals of the data set. vtkPolyDataNormals normals = new vtkPolyDataNormals(); normals.SetInputConnection(icosahedron.GetOutputPort()); // Set up the associated mapper and actor. vtkPolyDataMapper icosahedron_mapper = new vtkPolyDataMapper(); icosahedron_mapper.SetInputConnection(normals.GetOutputPort()); icosahedron_mapper.ScalarVisibilityOff(); vtkLODActor icosahedron_actor = new vtkLODActor(); icosahedron_actor.SetMapper(icosahedron_mapper); icosahedron_actor.GetProperty().SetColor(icosahedronActorColor); // Create a vtkOutlineFilter to draw the bounding box of the data set. // Also create the associated mapper and actor. vtkOutlineFilter outline = new vtkOutlineFilter(); outline.SetInputConnection(normals.GetOutputPort()); vtkPolyDataMapper map_outline = new vtkPolyDataMapper(); map_outline.SetInputConnection(outline.GetOutputPort()); vtkActor outline_actor = new vtkActor(); outline_actor.SetMapper(map_outline); outline_actor.GetProperty().SetColor(outlineActorColor); // Create the Renderers. Assign them the appropriate viewport // coordinates, active camera, and light. vtkRenderer ren = new vtkRenderer(); ren.SetViewport(0.0, 0.0, 0.5, 1.0); vtkRenderer ren2 = new vtkRenderer(); ren2.SetViewport(0.5, 0.0, 1.0, 1.0);; ren2.SetActiveCamera(ren.GetActiveCamera()); vtkRenderWindow renWin = new vtkRenderWindow(); renWin.AddRenderer(ren); renWin.AddRenderer(ren2); renWin.SetWindowName("VTK - Cube Axes"); renWin.SetSize(600, 300); vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); // Visualise ren.AddViewProp(icosahedron_actor); ren.AddViewProp(outline_actor); ren2.AddViewProp(icosahedron_actor); ren2.AddViewProp(outline_actor); ren.SetBackground(Bgcolor); ren2.SetBackground(Bgcolor); // Create a text property for both cube axes vtkTextProperty tprop = new vtkTextProperty(); tprop.SetColor(1, 1, 1); tprop.ShadowOn(); tprop.SetFontSize(20); // Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to // draw the axes. Add the actor to the renderer. vtkCubeAxesActor2D axes = new vtkCubeAxesActor2D(); axes.SetInputConnection(normals.GetOutputPort()); axes.SetCamera(ren.GetActiveCamera()); axes.SetLabelFormat("%6.4g"); axes.SetFlyModeToOuterEdges(); axes.SetAxisTitleTextProperty(tprop); axes.SetAxisLabelTextProperty(tprop); ren.AddViewProp(axes); // Create a vtkCubeAxesActor2D. Use the closest vertex to the camera to // determine where to draw the axes. Add the actor to the renderer. vtkCubeAxesActor2D axes2 = new vtkCubeAxesActor2D(); axes2.SetViewProp(icosahedron_actor); axes2.SetCamera(ren2.GetActiveCamera()); axes2.SetLabelFormat("%6.4g"); axes2.SetFlyModeToClosestTriad(); axes2.ScalingOff(); axes2.SetAxisTitleTextProperty(tprop); axes2.SetAxisLabelTextProperty(tprop); ren2.AddViewProp(axes2); ren.ResetCamera(); renWin.Render(); iren.Initialize(); iren.Start(); } }
src/Java/Visualization/CubeAxesActor2D.java
import vtk.vtkActor; import vtk.vtkNamedColors; import vtk.vtkNativeLibrary; import vtk.vtkPolyDataMapper; import vtk.vtkRenderWindow; import vtk.vtkRenderWindowInteractor; import vtk.vtkRenderer; import vtk.vtkPlatonicSolidSource; import vtk.vtkPolyDataNormals; import vtk.vtkTextProperty; import vtk.vtkCubeAxesActor2D; import vtk.vtkLODActor; import vtk.vtkOutlineFilter; public class CubeAxesActor2D { // ----------------------------------------------------------------- // Load VTK library and print which library was not properly loaded static { if (!vtkNativeLibrary.LoadAllNativeLibraries()) { for (vtkNativeLibrary lib : vtkNativeLibrary.values()) { if (!lib.IsLoaded()) { System.out.println(lib.GetLibraryName() + " not loaded"); } } } vtkNativeLibrary.DisableOutputWindow(null); } // ----------------------------------------------------------------- public static void main(String s[]) { vtkNamedColors colors = new vtkNamedColors(); //For icosahedron_actor Color double icosahedronActorColor[] = new double[4]; //For outline actor Color double outlineActorColor[] = new double[4]; //Renderer Background Color double Bgcolor[] = new double[4]; colors.GetColor("Magenta", icosahedronActorColor); colors.GetColor("Black", outlineActorColor); colors.GetColor("DarkSlateBlue", Bgcolor); vtkPlatonicSolidSource icosahedron = new vtkPlatonicSolidSource(); icosahedron.SetSolidTypeToIcosahedron(); // Create a vtkPolyDataNormals filter to calculate the normals of the data set. vtkPolyDataNormals normals = new vtkPolyDataNormals(); normals.SetInputConnection(icosahedron.GetOutputPort()); // Set up the associated mapper and actor. vtkPolyDataMapper icosahedron_mapper = new vtkPolyDataMapper(); icosahedron_mapper.SetInputConnection(normals.GetOutputPort()); icosahedron_mapper.ScalarVisibilityOff(); vtkLODActor icosahedron_actor = new vtkLODActor(); icosahedron_actor.SetMapper(icosahedron_mapper); icosahedron_actor.GetProperty().SetColor(icosahedronActorColor); // Create a vtkOutlineFilter to draw the bounding box of the data set. // Also create the associated mapper and actor. vtkOutlineFilter outline = new vtkOutlineFilter(); outline.SetInputConnection(normals.GetOutputPort()); vtkPolyDataMapper map_outline = new vtkPolyDataMapper(); map_outline.SetInputConnection(outline.GetOutputPort()); vtkActor outline_actor = new vtkActor(); outline_actor.SetMapper(map_outline); outline_actor.GetProperty().SetColor(outlineActorColor); // Create the Renderers. Assign them the appropriate viewport // coordinates, active camera, and light. vtkRenderer ren = new vtkRenderer(); ren.SetViewport(0, 0, 0.5, 1.0); vtkRenderer ren2 = new vtkRenderer(); ren2.SetViewport(0.5, 0,1.0, 1.0);; ren2.SetActiveCamera(ren.GetActiveCamera()); vtkRenderWindow renWin = new vtkRenderWindow(); renWin.AddRenderer(ren); renWin.AddRenderer(ren2); renWin.SetWindowName("VTK - Cube Axes"); renWin.SetSize(600, 300); vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); // Visualise ren.AddViewProp(icosahedron_actor); ren.AddViewProp(outline_actor); ren2.AddViewProp(icosahedron_actor); ren2.AddViewProp(outline_actor); ren.SetBackground(Bgcolor); ren2.SetBackground(Bgcolor); // Create a text property for both cube axes vtkTextProperty tprop = new vtkTextProperty(); tprop.SetColor(1, 1, 1); tprop.ShadowOn(); tprop.SetFontSize(20); // Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to // draw the axes. Add the actor to the renderer. vtkCubeAxesActor2D axes = new vtkCubeAxesActor2D(); axes.SetInputConnection(normals.GetOutputPort()); axes.SetCamera(ren.GetActiveCamera()); axes.SetLabelFormat("%6.4g"); axes.SetFlyModeToOuterEdges(); axes.SetAxisTitleTextProperty(tprop); axes.SetAxisLabelTextProperty(tprop); ren.AddViewProp(axes); // Create a vtkCubeAxesActor2D. Use the closest vertex to the camera to // determine where to draw the axes. Add the actor to the renderer. vtkCubeAxesActor2D axes2 = new vtkCubeAxesActor2D(); axes2.SetViewProp(icosahedron_actor); axes2.SetCamera(ren2.GetActiveCamera()); axes2.SetLabelFormat("%6.4g"); axes2.SetFlyModeToClosestTriad(); axes2.ScalingOff(); axes2.SetAxisTitleTextProperty(tprop); axes2.SetAxisLabelTextProperty(tprop); ren2.AddViewProp(axes2); ren.ResetCamera(); renWin.Render(); iren.Initialize(); iren.Start(); } }
Update CubeAxesActor2D.java
src/Java/Visualization/CubeAxesActor2D.java
Update CubeAxesActor2D.java
<ide><path>rc/Java/Visualization/CubeAxesActor2D.java <ide> // coordinates, active camera, and light. <ide> <ide> vtkRenderer ren = new vtkRenderer(); <del> ren.SetViewport(0, 0, 0.5, 1.0); <add> ren.SetViewport(0.0, 0.0, 0.5, 1.0); <ide> <ide> vtkRenderer ren2 = new vtkRenderer(); <del> ren2.SetViewport(0.5, 0,1.0, 1.0);; <add> ren2.SetViewport(0.5, 0.0, 1.0, 1.0);; <ide> ren2.SetActiveCamera(ren.GetActiveCamera()); <ide> <ide> vtkRenderWindow renWin = new vtkRenderWindow();
Java
apache-2.0
f8a13eb5e1a7abda67fe4119173025f650fd98fe
0
google/error-prone,cushon/error-prone,cushon/error-prone,cushon/error-prone,google/error-prone,cushon/error-prone
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.inject.dagger; import static com.google.errorprone.BugPattern.Category.DAGGER; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.isBindingDeclarationMethod; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.isStatic; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor; import static com.sun.source.tree.Tree.Kind.CLASS; import static com.sun.source.tree.Tree.Kind.METHOD; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.ProvidesFix; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** @author [email protected] (Gregory Kick) */ @BugPattern( name = "PrivateConstructorForNoninstantiableModule", summary = "Add a private constructor to modules that will not be instantiated by Dagger.", explanation = "Modules that contain abstract binding methods (@Binds, @Multibinds) or only static" + " @Provides methods will not be instantiated by Dagger when they are included in a" + " component. Adding a private constructor clearly conveys that the module will not be" + " used as an instance.", category = DAGGER, severity = SUGGESTION, providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION ) public class PrivateConstructorForNoninstantiableModule extends BugChecker implements ClassTreeMatcher { private static final Predicate<Tree> IS_CONSTRUCTOR = new Predicate<Tree>() { @Override public boolean apply(Tree tree) { return getSymbol(tree).isConstructor(); } }; @Override public Description matchClass(ClassTree classTree, VisitorState state) { if (!DaggerAnnotations.isAnyModule().matches(classTree, state)) { return NO_MATCH; } // if a module is declared as an interface, skip it if (!classTree.getKind().equals(CLASS)) { return NO_MATCH; } FluentIterable<? extends Tree> nonSyntheticMembers = FluentIterable.from(classTree.getMembers()) .filter( Predicates.not( new Predicate<Tree>() { @Override public boolean apply(Tree tree) { return tree.getKind().equals(METHOD) && isGeneratedConstructor((MethodTree) tree); } })); // ignore empty modules if (nonSyntheticMembers.isEmpty()) { return NO_MATCH; } if (nonSyntheticMembers.anyMatch(IS_CONSTRUCTOR)) { return NO_MATCH; } boolean hasBindingDeclarationMethods = nonSyntheticMembers.anyMatch(matcherAsPredicate(isBindingDeclarationMethod(), state)); if (hasBindingDeclarationMethods) { return describeMatch(classTree, addPrivateConstructor(classTree, state)); } boolean allStaticMembers = nonSyntheticMembers.allMatch(matcherAsPredicate(isStatic(), state)); if (allStaticMembers) { return describeMatch(classTree, addPrivateConstructor(classTree, state)); } return NO_MATCH; } private Fix addPrivateConstructor(ClassTree classTree, VisitorState state) { return SuggestedFixes.addMembers( classTree, state, "private " + classTree.getSimpleName() + "() {}"); } private static <T extends Tree> Predicate<T> matcherAsPredicate( final Matcher<? super T> matcher, final VisitorState state) { return new Predicate<T>() { @Override public boolean apply(T t) { return matcher.matches(t, state); } }; } }
core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/PrivateConstructorForNoninstantiableModule.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.inject.dagger; import static com.google.errorprone.BugPattern.Category.DAGGER; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.isBindingDeclarationMethod; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.isStatic; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor; import static com.sun.source.tree.Tree.Kind.CLASS; import static com.sun.source.tree.Tree.Kind.METHOD; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.ProvidesFix; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** @author [email protected] (Gregory Kick) */ @BugPattern( name = "PrivateConstructorForNoninstantiableModuleTest", summary = "Add a private constructor to modules that will not be instantiated by Dagger.", explanation = "Modules that contain abstract binding methods (@Binds, @Multibinds) or only static" + " @Provides methods will not be instantiated by Dagger when they are included in a" + " component. Adding a private constructor clearly conveys that the module will not be" + " used as an instance.", category = DAGGER, severity = SUGGESTION, providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION ) public class PrivateConstructorForNoninstantiableModule extends BugChecker implements ClassTreeMatcher { private static final Predicate<Tree> IS_CONSTRUCTOR = new Predicate<Tree>() { @Override public boolean apply(Tree tree) { return getSymbol(tree).isConstructor(); } }; @Override public Description matchClass(ClassTree classTree, VisitorState state) { if (!DaggerAnnotations.isAnyModule().matches(classTree, state)) { return NO_MATCH; } // if a module is declared as an interface, skip it if (!classTree.getKind().equals(CLASS)) { return NO_MATCH; } FluentIterable<? extends Tree> nonSyntheticMembers = FluentIterable.from(classTree.getMembers()) .filter( Predicates.not( new Predicate<Tree>() { @Override public boolean apply(Tree tree) { return tree.getKind().equals(METHOD) && isGeneratedConstructor((MethodTree) tree); } })); // ignore empty modules if (nonSyntheticMembers.isEmpty()) { return NO_MATCH; } if (nonSyntheticMembers.anyMatch(IS_CONSTRUCTOR)) { return NO_MATCH; } boolean hasBindingDeclarationMethods = nonSyntheticMembers.anyMatch(matcherAsPredicate(isBindingDeclarationMethod(), state)); if (hasBindingDeclarationMethods) { return describeMatch(classTree, addPrivateConstructor(classTree, state)); } boolean allStaticMembers = nonSyntheticMembers.allMatch(matcherAsPredicate(isStatic(), state)); if (allStaticMembers) { return describeMatch(classTree, addPrivateConstructor(classTree, state)); } return NO_MATCH; } private Fix addPrivateConstructor(ClassTree classTree, VisitorState state) { return SuggestedFixes.addMembers( classTree, state, "private " + classTree.getSimpleName() + "() {}"); } private static <T extends Tree> Predicate<T> matcherAsPredicate( final Matcher<? super T> matcher, final VisitorState state) { return new Predicate<T>() { @Override public boolean apply(T t) { return matcher.matches(t, state); } }; } }
Remove "Test" from PrivateConstructorForNoninstantiableModule's bug checker name RELNOTES: n/a ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=190825107
core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/PrivateConstructorForNoninstantiableModule.java
Remove "Test" from PrivateConstructorForNoninstantiableModule's bug checker name
<ide><path>ore/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/PrivateConstructorForNoninstantiableModule.java <ide> <ide> /** @author [email protected] (Gregory Kick) */ <ide> @BugPattern( <del> name = "PrivateConstructorForNoninstantiableModuleTest", <add> name = "PrivateConstructorForNoninstantiableModule", <ide> summary = "Add a private constructor to modules that will not be instantiated by Dagger.", <ide> explanation = <ide> "Modules that contain abstract binding methods (@Binds, @Multibinds) or only static"
JavaScript
mit
6c44363eecfd56787d953963142cdbe4255244c1
0
arschmitz/uglymongrel-jquery-mobile,arschmitz/jquery-mobile,hinaloe/jqm-demo-ja,hinaloe/jqm-demo-ja,arschmitz/uglymongrel-jquery-mobile,hinaloe/jqm-demo-ja,arschmitz/jquery-mobile,arschmitz/uglymongrel-jquery-mobile,arschmitz/jquery-mobile
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Links options present in the widget to be filtered to the input //>>label: Filterable-widgetlink //>>group: Widgets define( [ "jquery", "./filterable" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { // Create a function that will replace the _setOptions function of a widget, // and will pass the options on to the input of the filterable. var replaceSetOptions = function( self, orig ) { return function( options ) { orig.call( this, options ); self._syncTextInputOptions( options ); }; }, rDividerListItem = /(^|\s)ui-li-divider(\s|$)/, origDefaultFilterCallback = $.mobile.filterable.prototype.options.filterCallback; // Override the default filter callback with one that does not hide list dividers $.mobile.filterable.prototype.options.filterCallback = function( index, searchValue ) { return !this.className.match( rDividerListItem ) && origDefaultFilterCallback.call( this, index, searchValue ); }; $.widget( "mobile.filterable", $.mobile.filterable, { _create: function() { var idx, widgetName, elem = this.element, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ], createHandlers = {}; this._super(); $.extend( this, { _widget: null }); for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widgetName = recognizedWidgets[ idx ]; if ( $.mobile[ widgetName ] ) { if ( this._setWidget( elem.data( "mobile-" + widgetName ) ) ) { break; } else { createHandlers[ widgetName + "create" ] = "_handleCreate"; } } } if ( !this._widget ) { this._on( elem, createHandlers ); } }, _handleCreate: function( evt ) { this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); }, _setWidget: function( widget ) { if ( !this._widget && widget ) { this._widget = widget; this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); } if ( !!this._widget ) { this._syncTextInputOptions( this._widget.options ); } return !!this._widget; }, _isSearchInternal: function() { return ( this._search && this._search.jqmData( "ui-filterable-" + this.uuid + "-internal" ) ); }, _setInput: function( selector ) { if ( !selector ) { if ( this._isSearchInternal() ) { // Ignore the call to set a new input if the selector goes to falsy and // the current textinput is already of the internally generated variety. return; } else { selector = $( "<input " + "data-" + $.mobile.ns + "type='search' " + "placeholder='" + this.options.filterPlaceholder + "'></input>" ) .jqmData( "ui-filterable-" + this.uuid + "-internal", true ); $( "<form class='ui-filterable'></form>" ) .append( selector ) .insertBefore( this.element ); if ( $.mobile.textinput ) { selector.textinput(); } } } this._super( selector ); }, _destroy: function() { if ( this._isSearchInternal() ) { this._search.remove(); } }, _syncTextInputOptions: function( options ) { var idx, textinputOptions = {}; // We only sync options if the filterable's textinput is of the internally // generated variety, rather than one specified by the user. if ( this._isSearchInternal() && $.mobile.textinput ) { // Apply only the options understood by textinput for ( idx in $.mobile.textinput.prototype.options ) { if ( options[ idx ] !== undefined ) { textinputOptions[ idx ] = options[ idx ]; } } this._search.textinput( "option", textinputOptions ); } } }); })( jQuery ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
js/widgets/filterable.backcompat.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Links options present in the widget to be filtered to the input //>>label: Filterable-widgetlink //>>group: Widgets define( [ "jquery", "./filterable" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { // Create a function that will replace the _setOptions function of a widget, // and will pass the options on to the input of the filterable. var replaceSetOptions = function( self, orig ) { return function( options ) { orig.call( this, options ); self._syncTextInputOptions( options ); }; }, rDividerListItem = /(^|\s)ui-li-divider(\s|$)/, origDefaultFilterCallback = $.mobile.filterable.prototype.options.filterCallback; // Override the default filter callback with one that does not hide list dividers $.mobile.filterable.prototype.options.filterCallback = function( index, searchValue ) { return !this.className.match( rDividerListItem ) && origDefaultFilterCallback.call( this, index, searchValue ); }; $.widget( "mobile.filterable", $.mobile.filterable, { _handleCreate: function( evt ) { this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); }, _setWidget: function( widget ) { if ( !this._widget && widget ) { this._widget = widget; this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); } if ( !!this._widget ) { this._syncTextInputOptions( this._widget.options ); } return !!this._widget; }, _create: function() { var idx, widgetName, elem = this.element, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ], createHandlers = {}; this._super(); $.extend( this, { _widget: null }); for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widgetName = recognizedWidgets[ idx ]; if ( $.mobile[ widgetName ] ) { if ( this._setWidget( elem.data( "mobile-" + widgetName ) ) ) { break; } else { createHandlers[ widgetName + "create" ] = "_handleCreate"; } } } if ( !this._widget ) { this._on( elem, createHandlers ); } }, _isSearchInternal: function() { return ( this._search && this._search.jqmData( "ui-filterable-" + this.uuid + "-internal" ) ); }, _setInput: function( selector ) { if ( !selector ) { if ( this._isSearchInternal() ) { // Ignore the call to set a new input if the selector goes to falsy and // the current textinput is already of the internally generated variety. return; } else { selector = $( "<input " + "data-" + $.mobile.ns + "type='search' " + "placeholder='" + this.options.filterPlaceholder + "'></input>" ) .jqmData( "ui-filterable-" + this.uuid + "-internal", true ); $( "<form class='ui-filterable'></form>" ) .append( selector ) .insertBefore( this.element ); if ( $.mobile.textinput ) { selector.textinput(); } } } this._super( selector ); }, _destroy: function() { if ( this._isSearchInternal() ) { this._search.remove(); } }, _syncTextInputOptions: function( options ) { var idx, textinputOptions = {}; // We only sync options if the filterable's textinput is of the internally // generated variety, rather than one specified by the user. if ( this._isSearchInternal() && $.mobile.textinput ) { // Apply only the options understood by textinput for ( idx in $.mobile.textinput.prototype.options ) { if ( options[ idx ] !== undefined ) { textinputOptions[ idx ] = options[ idx ]; } } this._search.textinput( "option", textinputOptions ); } } }); })( jQuery ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
Filterable backcompat: Moving _create() method to the top.
js/widgets/filterable.backcompat.js
Filterable backcompat: Moving _create() method to the top.
<ide><path>s/widgets/filterable.backcompat.js <ide> }; <ide> <ide> $.widget( "mobile.filterable", $.mobile.filterable, { <del> _handleCreate: function( evt ) { <del> this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); <del> }, <del> <del> _setWidget: function( widget ) { <del> if ( !this._widget && widget ) { <del> this._widget = widget; <del> this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); <del> } <del> <del> if ( !!this._widget ) { <del> this._syncTextInputOptions( this._widget.options ); <del> } <del> <del> return !!this._widget; <del> }, <ide> <ide> _create: function() { <ide> var idx, widgetName, <ide> if ( !this._widget ) { <ide> this._on( elem, createHandlers ); <ide> } <add> }, <add> <add> _handleCreate: function( evt ) { <add> this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); <add> }, <add> <add> _setWidget: function( widget ) { <add> if ( !this._widget && widget ) { <add> this._widget = widget; <add> this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); <add> } <add> <add> if ( !!this._widget ) { <add> this._syncTextInputOptions( this._widget.options ); <add> } <add> <add> return !!this._widget; <ide> }, <ide> <ide> _isSearchInternal: function() {
Java
mit
a996ee770326f3447fa4df756eaecaeb511642eb
0
nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server
package fi.nls.oskari.control.view.modifier.bundle; import fi.mml.map.mapwindow.util.OskariLayerWorker; import fi.nls.oskari.analysis.AnalysisHelper; import fi.nls.oskari.annotation.OskariViewModifier; import fi.nls.oskari.domain.User; import fi.nls.oskari.domain.map.MyPlaceCategory; import fi.nls.oskari.domain.map.OskariLayer; import fi.nls.oskari.domain.map.analysis.Analysis; import fi.nls.oskari.domain.map.userlayer.UserLayer; import fi.nls.oskari.domain.map.view.ViewTypes; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.map.analysis.domain.AnalysisLayer; import fi.nls.oskari.map.analysis.service.AnalysisDbService; import fi.nls.oskari.map.analysis.service.AnalysisDbServiceMybatisImpl; import fi.nls.oskari.map.layer.OskariLayerService; import fi.nls.oskari.myplaces.MyPlacesService; import fi.nls.oskari.service.OskariComponentManager; import fi.nls.oskari.util.ConversionHelper; import fi.nls.oskari.util.JSONHelper; import fi.nls.oskari.view.modifier.ModifierException; import fi.nls.oskari.view.modifier.ModifierParams; import fi.nls.oskari.view.modifier.ViewModifier; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.oskari.map.userlayer.service.UserLayerDataService; import org.oskari.map.userlayer.service.UserLayerDbService; import org.oskari.permissions.PermissionService; import org.oskari.permissions.model.PermissionType; import org.oskari.service.util.ServiceFactory; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; @OskariViewModifier("mapfull") public class MapfullHandler extends BundleHandler { private static final Logger LOGGER = LogFactory.getLogger(MapfullHandler.class); private static PermissionService permissionsService; // FIXME: default srs is hardcoded into frontend if srs is not defined in mapOptions!! public static final String DEFAULT_MAP_SRS = "EPSG:3067"; private static final String KEY_LAYERS = "layers"; private static final String KEY_SEL_LAYERS = "selectedLayers"; private static final String KEY_ID = "id"; private static final String KEY_FORCE_PROXY = "forceProxy"; private static final String KEY_MAP_OPTIONS = "mapOptions"; private static final String KEY_PROJ_DEFS = "projectionDefs"; private static final String KEY_SRS = "srsName"; private static final String KEY_PLUGINS = "plugins"; public static final String KEY_CONFIG = "config"; private static final String KEY_BASELAYERS = "baseLayers"; private static final String KEY_CENTER_MAP_AUTOMATICALLY = "centerMapAutomatically"; private static final String PREFIX_MYPLACES = "myplaces_"; private static final String PREFIX_ANALYSIS = "analysis_"; private static final String PREFIX_USERLAYERS = "userlayer_"; private static final Set<String> BUNDLES_HANDLING_MYPLACES_LAYERS = ConversionHelper.asSet(ViewModifier.BUNDLE_MYPLACES2, ViewModifier.BUNDLE_MYPLACES3); private static final String PLUGIN_LAYERSELECTION = "Oskari.mapframework.bundle.mapmodule.plugin.LayerSelectionPlugin"; private static final String PLUGIN_GEOLOCATION = "Oskari.mapframework.bundle.mapmodule.plugin.GeoLocationPlugin"; public static final String PLUGIN_WFSVECTORLAYER = "Oskari.wfsvector.WfsVectorLayerPlugin"; private static final String PLUGIN_MYLOCATION = "Oskari.mapframework.bundle.mapmodule.plugin.MyLocationPlugin"; public static final String EPSG_PROJ4_FORMATS = "epsg_proj4_formats.json"; private static MyPlacesService myPlaceService = null; private static final AnalysisDbService analysisService = new AnalysisDbServiceMybatisImpl(); private static UserLayerDbService userLayerService; private static final UserLayerDataService userLayerDataService = new UserLayerDataService(); private static OskariLayerService mapLayerService; private static JSONObject epsgMap = null; private HashMap<String, PluginHandler> pluginHandlers = null; public void init() { myPlaceService = OskariComponentManager.getComponentOfType(MyPlacesService.class); userLayerService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); mapLayerService = OskariComponentManager.getComponentOfType(OskariLayerService.class); // to prevent mocking issues in JUnit tests.... permissionsService = ServiceFactory.getPermissionsService(); // OskariComponentManager.getComponentOfType(PermissionService.class); epsgInit(); svgInit(); pluginHandlers = new HashMap<>(); registerPluginHandler(LogoPluginHandler.PLUGIN_NAME, new LogoPluginHandler()); registerPluginHandler(WfsLayerPluginHandler.PLUGIN_NAME, new WfsLayerPluginHandler()); registerPluginHandler(MyPlacesLayerPluginHandler.PLUGIN_NAME, new MyPlacesLayerPluginHandler()); registerPluginHandler(UserLayerPluginHandler.PLUGIN_NAME, new UserLayerPluginHandler()); } public void registerPluginHandler (String pluginId, PluginHandler handler) { pluginHandlers.put(pluginId, handler); } public boolean modifyBundle(final ModifierParams params) throws ModifierException { final JSONObject mapfullConfig = getBundleConfig(params.getConfig()); final JSONObject mapfullState = getBundleState(params.getConfig()); if (mapfullConfig == null) { return false; } // Any layer referenced in state.selectedLayers array NEEDS to // be in conf.layers otherwise it cant be added to map on startup final JSONArray mfConfigLayers = JSONHelper.getEmptyIfNull(mapfullConfig.optJSONArray(KEY_LAYERS)); final JSONArray mfStateLayers = JSONHelper.getEmptyIfNull(mapfullState.optJSONArray(KEY_SEL_LAYERS)); copySelectedLayersToConfigLayers(mfConfigLayers, mfStateLayers); final Set<String> bundleIds = getBundleIds(params.getStartupSequence()); final boolean useDirectURLForMyplaces = false; final String mapSRS = getSRSFromMapConfig(mapfullConfig); final boolean forceProxy = mapfullConfig.optBoolean(KEY_FORCE_PROXY, false); final JSONArray fullConfigLayers = getFullLayerConfig(mfConfigLayers, params.getUser(), params.getLocale().getLanguage(), params.getViewId(), params.getViewType(), bundleIds, useDirectURLForMyplaces, params.isModifyURLs(), mapSRS, forceProxy, JSONHelper.getJSONArray(mapfullConfig, KEY_PLUGINS)); setProjDefsForMapConfig(mapfullConfig, mapSRS); // overwrite layers try { mapfullConfig.put(KEY_LAYERS, fullConfigLayers); } catch (Exception e) { LOGGER.error(e, "Unable to overwrite layers"); } // dummyfix: because migration tool added layer selection to all migrated maps // remove it from old published maps if only one layer is selected if (params.isOldPublishedMap()) { this.killLayerSelectionPlugin(mapfullConfig); } if (params.isLocationModified()) { LOGGER.info("locationModifiedByParams -> disabling GeoLocationPlugin"); removePlugin(PLUGIN_GEOLOCATION, mapfullConfig); removeMyLocationPluginAutoCenter(mapfullConfig); } pluginHandlers.entrySet().stream().forEach(entry -> { JSONObject pluginJSON = getPlugin(entry.getKey(), mapfullConfig); if (pluginJSON != null) { entry.getValue().modifyPlugin(pluginJSON, params, mapSRS); } }); return false; } public static JSONArray getFullLayerConfig(final JSONArray layersArray, final User user, final String lang, final long viewID, final String viewType, final Set<String> bundleIds, final boolean useDirectURLForMyplaces, final String mapSRS) { return getFullLayerConfig(layersArray, user, lang, viewID, viewType, bundleIds, useDirectURLForMyplaces, false, mapSRS); } public static JSONArray getFullLayerConfig(final JSONArray layersArray, final User user, final String lang, final long viewID, final String viewType, final Set<String> bundleIds, final boolean useDirectURLForMyplaces, final boolean modifyURLs, final String mapSRS) { return getFullLayerConfig( layersArray, user, lang, viewID, viewType, bundleIds, useDirectURLForMyplaces, modifyURLs, mapSRS, false, null); } /** * Detect projection that will be used for view that is being loaded * <p/> * { * "mapOptions" : { * "srsName":"EPSG:3067" * } * } * * @param mapfullConfig * @return conf.mapOptions.srsName or DEFAULT_MAP_SRS if it doesn't exist */ public String getSRSFromMapConfig(final JSONObject mapfullConfig) { if (mapfullConfig == null) { return DEFAULT_MAP_SRS; } final JSONObject options = mapfullConfig.optJSONObject(KEY_MAP_OPTIONS); if (options == null) { return DEFAULT_MAP_SRS; } final String mapSRS = options.optString(KEY_SRS); if (mapSRS != null) { return mapSRS; } return DEFAULT_MAP_SRS; } public void setProjDefsForMapConfig(final JSONObject mapfullConfig, final String... srs) { if (mapfullConfig == null || srs == null) { return; } JSONObject defs = JSONHelper.getJSONObject(mapfullConfig, KEY_PROJ_DEFS); if(defs == null) { defs = new JSONObject(); JSONHelper.putValue(mapfullConfig, KEY_PROJ_DEFS, defs); } for(String mapSRS : srs) { final String mapSRSProjDef = getMapSRSProjDef(mapSRS); // couldn't get data or already defined -> go to next one if (mapSRSProjDef == null || defs.has(mapSRS)) { continue; } JSONHelper.putValue(defs, mapSRS, mapSRSProjDef); } } public String getMapSRSProjDef(final String mapSRS) { try { if(this.epsgMap.has(mapSRS.toUpperCase())){ return JSONHelper.getStringFromJSON(this.epsgMap, mapSRS.toUpperCase(), null); } else { LOGGER.debug("ProjectionDefs not found in epsg_proj4_formats.json", mapSRS); } } catch (Exception e) { LOGGER.debug("ProjectionDefs read failed in epsg_proj4_formats.json", mapSRS, " - exception: ", e); } return null; } /** * Creates JSON array of layer configurations. * * @param layersArray * @param user * @param lang * @param viewID * @param viewType * @param bundleIds * @param useDirectURLForMyplaces * @param modifyURLs false to keep urls as is, true to modify them for easier proxy forwards * @param forceProxy false to keep urls as is, true to proxy all layers * @param plugins * @return */ public static JSONArray getFullLayerConfig(final JSONArray layersArray, final User user, final String lang, final long viewID, final String viewType, final Set<String> bundleIds, final boolean useDirectURLForMyplaces, final boolean modifyURLs, final String mapSRS, final boolean forceProxy, final JSONArray plugins) { // Create a list of layer ids final List<Integer> layerIdList = new ArrayList<>(); final List<Long> publishedMyPlaces = new ArrayList<Long>(); final List<Long> publishedAnalysis = new ArrayList<Long>(); final List<Long> publishedUserLayers = new ArrayList<Long>(); for (int i = 0; i < layersArray.length(); i++) { String layerId = null; try { final JSONObject layer = layersArray.getJSONObject(i); layerId = layer.getString(KEY_ID); if (layerId == null || layerIdList.contains(layerId)) { continue; } // special handling for myplaces and analysis layers if (layerId.startsWith(PREFIX_MYPLACES)) { final long categoryId = ConversionHelper.getLong(layerId.substring(PREFIX_MYPLACES.length()), -1); if (categoryId != -1) { publishedMyPlaces.add(categoryId); } else { LOGGER.warn("Found my places layer in selected. Error parsing id with category id: ", layerId); } } else if (layerId.startsWith(PREFIX_ANALYSIS)) { final long categoryId = AnalysisHelper.getAnalysisIdFromLayerId(layerId); if (categoryId != -1) { publishedAnalysis.add(categoryId); } else { LOGGER.warn("Found analysis layer in selected. Error parsing id with category id: ", layerId); } } else if (layerId.startsWith(PREFIX_USERLAYERS)) { final long userLayerId = ConversionHelper .getLong(layerId.substring(PREFIX_USERLAYERS.length()), -1); if (userLayerId != -1) { publishedUserLayers.add(userLayerId); } else { LOGGER.warn("Found user layer in selected. Error parsing id with prefixed id: ", layerId); } } else { int id = ConversionHelper.getInt(layerId, -1); if (id != -1) { // these should all be pointing at a layer in oskari_maplayer layerIdList.add(id); } } } catch (JSONException je) { LOGGER.error(je, "Problem handling layer id:", layerId, "skipping it!."); } } final List<OskariLayer> layers = mapLayerService.findByIdList(layerIdList); if (forceProxy) { layers.forEach(lyr -> { if (lyr.getType().equals(OskariLayer.TYPE_3DTILES)) { // Proxy is not supported for 3D layers return; } JSONObject attributes = lyr.getAttributes(); if (attributes == null) { attributes = new JSONObject(); } JSONHelper.putValue(attributes, "forceProxy", forceProxy); lyr.setAttributes(attributes); }); } final JSONObject struct = OskariLayerWorker.getListOfMapLayers( layers, user, lang, mapSRS, ViewTypes.PUBLISHED.equals(viewType), modifyURLs); if (struct.isNull(KEY_LAYERS)) { LOGGER.warn("getSelectedLayersStructure did not return layers when expanding:", layerIdList); } // construct layers JSON final JSONArray prefetch = getLayersArray(struct); appendMyPlacesLayers(prefetch, publishedMyPlaces, user, viewID, lang, bundleIds, useDirectURLForMyplaces, modifyURLs, plugins); appendAnalysisLayers(prefetch, publishedAnalysis, user, viewID, lang, bundleIds, useDirectURLForMyplaces, modifyURLs); appendUserLayers(prefetch, publishedUserLayers, user, viewID, bundleIds, mapSRS); return prefetch; } private static void appendAnalysisLayers(final JSONArray layerList, final List<Long> publishedAnalysis, final User user, final long viewID, final String lang, final Set<String> bundleIds, final boolean useDirectURL, final boolean modifyURLs) { final boolean analyseBundlePresent = bundleIds.contains(BUNDLE_ANALYSE); final Set<String> permissions = permissionsService.getResourcesWithGrantedPermissions( AnalysisLayer.TYPE, user, PermissionType.VIEW_PUBLISHED.name()); LOGGER.debug("Analysis layer permissions for published view", permissions); for (Long id : publishedAnalysis) { final Analysis analysis = analysisService.getAnalysisById(id); if(analysis == null){ continue; } if (analyseBundlePresent && analysis.isOwnedBy(user.getUuid())) { // skip it's an own bundle and analysis bundle is present -> will be loaded via analysisbundle continue; } final String permissionKey = "analysis+" + id; boolean containsKey = permissions.contains(permissionKey); if (!containsKey) { LOGGER.info("Found analysis layer in selected that is no longer published. ViewID:", viewID, "Analysis id:", id); continue; } final JSONObject json = AnalysisHelper.getlayerJSON(analysis, lang, useDirectURL, user.getUuid(), modifyURLs); if (json != null) { layerList.put(json); } } } private static boolean isMyplacesBundlePresent(Set<String> bundleIdList) { for(String bundleId : BUNDLES_HANDLING_MYPLACES_LAYERS) { if(bundleIdList.contains(bundleId)) { return true; } } return false; } private static void appendMyPlacesLayers(final JSONArray layerList, final List<Long> publishedMyPlaces, final User user, final long viewID, final String lang, final Set<String> bundleIds, final boolean useDirectURL, final boolean modifyURLs, final JSONArray plugins) { if (publishedMyPlaces.isEmpty()) { return; } final boolean myPlacesBundlePresent = isMyplacesBundlePresent(bundleIds); // get myplaces categories from service and generate layer jsons final String uuid = user.getUuid(); final List<MyPlaceCategory> myPlacesLayers = myPlaceService .getMyPlaceLayersById(publishedMyPlaces); for (MyPlaceCategory mpLayer : myPlacesLayers) { if (!mpLayer.isPublished() && !mpLayer.isOwnedBy(uuid)) { LOGGER.info("Found my places layer in selected that is no longer published. ViewID:", viewID, "Myplaces layerId:", mpLayer.getId()); // no longer published -> skip if isn't current users layer continue; } if (myPlacesBundlePresent && mpLayer.isOwnedBy(uuid)) { // if the layer is users own -> myplaces2 bundle handles it // so if myplaces2 is present we must skip the users layers continue; } JSONObject myPlaceLayer = null; if (plugins != null && plugins.toString().indexOf(PLUGIN_WFSVECTORLAYER) != -1) { myPlaceLayer = myPlaceService.getCategoryAsWfsLayerJSON(mpLayer, lang); } else { myPlaceLayer = myPlaceService.getCategoryAsWmsLayerJSON( mpLayer, lang, useDirectURL, user.getUuid(), modifyURLs); } if (myPlaceLayer != null) { layerList.put(myPlaceLayer); } } } private static void appendUserLayers(final JSONArray layerList, final List<Long> publishedUserLayers, final User user, final long viewID, final Set<String> bundleIds, final String mapSrs) { final boolean userLayersBundlePresent = bundleIds.contains(BUNDLE_MYPLACESIMPORT); final OskariLayer baseLayer = userLayerDataService.getBaseLayer(); for (Long id : publishedUserLayers) { final UserLayer userLayer = userLayerService.getUserLayerById(id); if (userLayer == null) { LOGGER.warn("Unable to find published user layer with id", id); continue; } if (userLayersBundlePresent && userLayer.isOwnedBy(user.getUuid())) { // skip if it's an own layer and myplacesimport bundle is present -> // will be loaded via aforementioned bundle continue; } if (!userLayer.isPublished() && !userLayer.isOwnedBy(user.getUuid())) { LOGGER.info("Found user layer in selected that is no longer published. ViewID:", viewID, "User layer id:", userLayer.getId()); // no longer published -> skip if isn't current users layer continue; } final JSONObject json = userLayerDataService.parseUserLayer2JSON(userLayer, baseLayer, mapSrs); if (json != null) { layerList.put(json); } } } private static JSONArray getLayersArray(final JSONObject struct) { try { final Object layers = struct.get(KEY_LAYERS); if (layers instanceof JSONArray) { return (JSONArray) layers; } else if (layers instanceof JSONObject) { final JSONArray list = new JSONArray(); list.put(layers); return list; } else { LOGGER.error("getSelectedLayersStructure returned garbage layers."); } } catch (JSONException jsonex) { LOGGER.error("Could not set prefetch layers."); } return new JSONArray(); } private void copySelectedLayersToConfigLayers(final JSONArray mfConfigLayers, final JSONArray mfStateLayers) { for (int i = 0; i < mfStateLayers.length(); i++) { String stateLayerId = null; String confLayerId = null; JSONObject stateLayer = null; JSONObject confLayer = null; try { boolean inConfigLayers = false; stateLayer = mfStateLayers.getJSONObject(i); stateLayerId = stateLayer.getString(KEY_ID); for (int j = 0; j < mfConfigLayers.length(); j++) { confLayer = mfConfigLayers.getJSONObject(j); confLayerId = confLayer.getString(KEY_ID); if (stateLayerId.equals(confLayerId)) { inConfigLayers = true; } } if (!inConfigLayers) { mfConfigLayers.put(stateLayer); } } catch (JSONException je) { LOGGER.error(je, "Problem comparing layers - StateLayerId:", stateLayerId, "vs confLayerId:", confLayerId); } } } public static JSONObject getPlugin(final String pluginClassName, final JSONObject mapfullConfig) { if (mapfullConfig == null || !mapfullConfig.has(KEY_PLUGINS)) { return null; } final JSONArray plugins = mapfullConfig.optJSONArray(KEY_PLUGINS); for (int i = 0; i < plugins.length(); i++) { final JSONObject plugin = plugins.optJSONObject(i); if (plugin == null || !plugin.has(KEY_ID)) { continue; } if (pluginClassName.equals(plugin.optString(KEY_ID))) { LOGGER.debug(pluginClassName, "plugin found at index:", i); return plugin; } } return null; } private void removeMyLocationPluginAutoCenter(final JSONObject mapfullConfig) { JSONObject plugin = getPlugin(PLUGIN_MYLOCATION, mapfullConfig); if (plugin == null) { return; } try { JSONObject config = plugin.getJSONObject(KEY_CONFIG); if(config.has(KEY_CENTER_MAP_AUTOMATICALLY)) { config.remove(KEY_CENTER_MAP_AUTOMATICALLY); } } catch (JSONException jsonex) { LOGGER.error("Problem trying to modify " + PLUGIN_MYLOCATION + " " + KEY_CENTER_MAP_AUTOMATICALLY + ".", jsonex); } } private void removePlugin(final String pluginClassName, final JSONObject mapfullConfig) { if (mapfullConfig == null || !mapfullConfig.has(KEY_PLUGINS)) { return; } final JSONArray plugins = mapfullConfig.optJSONArray(KEY_PLUGINS); for (int i = 0; i < plugins.length(); i++) { final JSONObject plugin = plugins.optJSONObject(i); if (plugin == null || !plugin.has(KEY_ID)) { continue; } if (pluginClassName.equals(plugin.optString(KEY_ID))) { LOGGER.debug(pluginClassName, "plugin found at index:", i, "- removing it"); plugins.remove(i); break; } } } private void killLayerSelectionPlugin(final JSONObject mapfullConfig) { LOGGER.debug("[killLayerSelectionPlugin] removing layer selection plugin"); try { final JSONArray plugins = mapfullConfig.getJSONArray(KEY_PLUGINS); for (int i = 0; i < plugins.length(); i++) { JSONObject plugin = plugins.getJSONObject(i); if (!plugin.has(KEY_ID) || !plugin.has(KEY_CONFIG)) { continue; } String id = plugin.getString(KEY_ID); LOGGER.debug("[killLayerSelectionPlugin] got plugin " + id); if (!id.equals(PLUGIN_LAYERSELECTION)) { continue; } JSONObject config = plugin.getJSONObject(KEY_CONFIG); LOGGER.debug("[killLayerSelectionPlugin] got config"); if (!config.has(KEY_BASELAYERS)) { continue; } JSONArray bl = config.getJSONArray(KEY_BASELAYERS); if (bl.length() < 2) { LOGGER.debug("[killLayerSelectionPlugin] " + "layercount < 2, removing plugin"); plugins.remove(i--); LOGGER.info("[killLayerSelectionPlugin] " + "Removed " + PLUGIN_LAYERSELECTION + "as layercount < 2 and oldId > 0"); } } } catch (JSONException jsonex) { LOGGER.error("Problem trying to figure out whether " + PLUGIN_LAYERSELECTION + " should be removed.", jsonex); } } void epsgInit() { try { InputStream inp = this.getClass().getResourceAsStream(EPSG_PROJ4_FORMATS); if (inp != null) { InputStreamReader reader = new InputStreamReader(inp, "UTF-8"); JSONTokener tokenizer = new JSONTokener(reader); this.epsgMap = JSONHelper.createJSONObject4Tokener(tokenizer); } } catch (Exception e) { LOGGER.info("No setup for epsg proj4 formats found", e); } } void svgInit(){ } }
control-base/src/main/java/fi/nls/oskari/control/view/modifier/bundle/MapfullHandler.java
package fi.nls.oskari.control.view.modifier.bundle; import fi.mml.map.mapwindow.util.OskariLayerWorker; import fi.nls.oskari.analysis.AnalysisHelper; import fi.nls.oskari.annotation.OskariViewModifier; import fi.nls.oskari.domain.User; import fi.nls.oskari.domain.map.MyPlaceCategory; import fi.nls.oskari.domain.map.OskariLayer; import fi.nls.oskari.domain.map.analysis.Analysis; import fi.nls.oskari.domain.map.userlayer.UserLayer; import fi.nls.oskari.domain.map.view.ViewTypes; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.map.analysis.domain.AnalysisLayer; import fi.nls.oskari.map.analysis.service.AnalysisDbService; import fi.nls.oskari.map.analysis.service.AnalysisDbServiceMybatisImpl; import fi.nls.oskari.map.layer.OskariLayerService; import fi.nls.oskari.myplaces.MyPlacesService; import fi.nls.oskari.service.OskariComponentManager; import fi.nls.oskari.util.ConversionHelper; import fi.nls.oskari.util.JSONHelper; import fi.nls.oskari.view.modifier.ModifierException; import fi.nls.oskari.view.modifier.ModifierParams; import fi.nls.oskari.view.modifier.ViewModifier; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.oskari.map.userlayer.service.UserLayerDataService; import org.oskari.map.userlayer.service.UserLayerDbService; import org.oskari.permissions.PermissionService; import org.oskari.permissions.model.PermissionType; import org.oskari.service.util.ServiceFactory; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; @OskariViewModifier("mapfull") public class MapfullHandler extends BundleHandler { private static final Logger LOGGER = LogFactory.getLogger(MapfullHandler.class); private static PermissionService permissionsService; // FIXME: default srs is hardcoded into frontend if srs is not defined in mapOptions!! public static final String DEFAULT_MAP_SRS = "EPSG:3067"; private static final String KEY_LAYERS = "layers"; private static final String KEY_SEL_LAYERS = "selectedLayers"; private static final String KEY_ID = "id"; private static final String KEY_FORCE_PROXY = "forceProxy"; private static final String KEY_MAP_OPTIONS = "mapOptions"; private static final String KEY_PROJ_DEFS = "projectionDefs"; private static final String KEY_SRS = "srsName"; private static final String KEY_PLUGINS = "plugins"; public static final String KEY_CONFIG = "config"; private static final String KEY_BASELAYERS = "baseLayers"; private static final String KEY_CENTER_MAP_AUTOMATICALLY = "centerMapAutomatically"; private static final String PREFIX_MYPLACES = "myplaces_"; private static final String PREFIX_ANALYSIS = "analysis_"; private static final String PREFIX_USERLAYERS = "userlayer_"; private static final Set<String> BUNDLES_HANDLING_MYPLACES_LAYERS = ConversionHelper.asSet(ViewModifier.BUNDLE_MYPLACES2, ViewModifier.BUNDLE_MYPLACES3); private static final String PLUGIN_LAYERSELECTION = "Oskari.mapframework.bundle.mapmodule.plugin.LayerSelectionPlugin"; private static final String PLUGIN_GEOLOCATION = "Oskari.mapframework.bundle.mapmodule.plugin.GeoLocationPlugin"; public static final String PLUGIN_WFSVECTORLAYER = "Oskari.wfsvector.WfsVectorLayerPlugin"; private static final String PLUGIN_MYLOCATION = "Oskari.mapframework.bundle.mapmodule.plugin.MyLocationPlugin"; public static final String EPSG_PROJ4_FORMATS = "epsg_proj4_formats.json"; private static MyPlacesService myPlaceService = null; private static final AnalysisDbService analysisService = new AnalysisDbServiceMybatisImpl(); private static UserLayerDbService userLayerService; private static final UserLayerDataService userLayerDataService = new UserLayerDataService(); private static OskariLayerService mapLayerService; private static JSONObject epsgMap = null; private HashMap<String, PluginHandler> pluginHandlers = null; public void init() { myPlaceService = OskariComponentManager.getComponentOfType(MyPlacesService.class); userLayerService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); mapLayerService = OskariComponentManager.getComponentOfType(OskariLayerService.class); // to prevent mocking issues in JUnit tests.... permissionsService = ServiceFactory.getPermissionsService(); // OskariComponentManager.getComponentOfType(PermissionService.class); epsgInit(); svgInit(); pluginHandlers = new HashMap<>(); registerPluginHandler(LogoPluginHandler.PLUGIN_NAME, new LogoPluginHandler()); registerPluginHandler(WfsLayerPluginHandler.PLUGIN_NAME, new WfsLayerPluginHandler()); registerPluginHandler(MyPlacesLayerPluginHandler.PLUGIN_NAME, new MyPlacesLayerPluginHandler()); registerPluginHandler(UserLayerPluginHandler.PLUGIN_NAME, new UserLayerPluginHandler()); } public void registerPluginHandler (String pluginId, PluginHandler handler) { pluginHandlers.put(pluginId, handler); } public boolean modifyBundle(final ModifierParams params) throws ModifierException { final JSONObject mapfullConfig = getBundleConfig(params.getConfig()); final JSONObject mapfullState = getBundleState(params.getConfig()); if (mapfullConfig == null) { return false; } // Any layer referenced in state.selectedLayers array NEEDS to // be in conf.layers otherwise it cant be added to map on startup final JSONArray mfConfigLayers = JSONHelper.getEmptyIfNull(mapfullConfig.optJSONArray(KEY_LAYERS)); final JSONArray mfStateLayers = JSONHelper.getEmptyIfNull(mapfullState.optJSONArray(KEY_SEL_LAYERS)); copySelectedLayersToConfigLayers(mfConfigLayers, mfStateLayers); final Set<String> bundleIds = getBundleIds(params.getStartupSequence()); final boolean useDirectURLForMyplaces = false; final String mapSRS = getSRSFromMapConfig(mapfullConfig); final boolean forceProxy = mapfullConfig.optBoolean(KEY_FORCE_PROXY, false); final JSONArray fullConfigLayers = getFullLayerConfig(mfConfigLayers, params.getUser(), params.getLocale().getLanguage(), params.getViewId(), params.getViewType(), bundleIds, useDirectURLForMyplaces, params.isModifyURLs(), mapSRS, forceProxy, JSONHelper.getJSONArray(mapfullConfig, KEY_PLUGINS)); setProjDefsForMapConfig(mapfullConfig, mapSRS); // overwrite layers try { mapfullConfig.put(KEY_LAYERS, fullConfigLayers); } catch (Exception e) { LOGGER.error(e, "Unable to overwrite layers"); } // dummyfix: because migration tool added layer selection to all migrated maps // remove it from old published maps if only one layer is selected if (params.isOldPublishedMap()) { this.killLayerSelectionPlugin(mapfullConfig); } if (params.isLocationModified()) { LOGGER.info("locationModifiedByParams -> disabling GeoLocationPlugin"); removePlugin(PLUGIN_GEOLOCATION, mapfullConfig); removeMyLocationPluginAutoCenter(mapfullConfig); } pluginHandlers.entrySet().stream().forEach(entry -> { JSONObject pluginJSON = getPlugin(entry.getKey(), mapfullConfig); if (pluginJSON != null) { entry.getValue().modifyPlugin(pluginJSON, params, mapSRS); } }); return false; } public static JSONArray getFullLayerConfig(final JSONArray layersArray, final User user, final String lang, final long viewID, final String viewType, final Set<String> bundleIds, final boolean useDirectURLForMyplaces, final String mapSRS) { return getFullLayerConfig(layersArray, user, lang, viewID, viewType, bundleIds, useDirectURLForMyplaces, false, mapSRS); } public static JSONArray getFullLayerConfig(final JSONArray layersArray, final User user, final String lang, final long viewID, final String viewType, final Set<String> bundleIds, final boolean useDirectURLForMyplaces, final boolean modifyURLs, final String mapSRS) { return getFullLayerConfig( layersArray, user, lang, viewID, viewType, bundleIds, useDirectURLForMyplaces, modifyURLs, mapSRS, false, null); } /** * Detect projection that will be used for view that is being loaded * <p/> * { * "mapOptions" : { * "srsName":"EPSG:3067" * } * } * * @param mapfullConfig * @return conf.mapOptions.srsName or DEFAULT_MAP_SRS if it doesn't exist */ public String getSRSFromMapConfig(final JSONObject mapfullConfig) { if (mapfullConfig == null) { return DEFAULT_MAP_SRS; } final JSONObject options = mapfullConfig.optJSONObject(KEY_MAP_OPTIONS); if (options == null) { return DEFAULT_MAP_SRS; } final String mapSRS = options.optString(KEY_SRS); if (mapSRS != null) { return mapSRS; } return DEFAULT_MAP_SRS; } public void setProjDefsForMapConfig(final JSONObject mapfullConfig, final String... srs) { if (mapfullConfig == null || srs == null) { return; } JSONObject defs = JSONHelper.getJSONObject(mapfullConfig, KEY_PROJ_DEFS); if(defs == null) { defs = new JSONObject(); JSONHelper.putValue(mapfullConfig, KEY_PROJ_DEFS, defs); } for(String mapSRS : srs) { final String mapSRSProjDef = getMapSRSProjDef(mapSRS); // couldn't get data or already defined -> go to next one if (mapSRSProjDef == null || defs.has(mapSRS)) { continue; } JSONHelper.putValue(defs, mapSRS, mapSRSProjDef); } } public String getMapSRSProjDef(final String mapSRS) { try { if(this.epsgMap.has(mapSRS.toUpperCase())){ return JSONHelper.getStringFromJSON(this.epsgMap, mapSRS.toUpperCase(), null); } else { LOGGER.debug("ProjectionDefs not found in epsg_proj4_formats.json", mapSRS); } } catch (Exception e) { LOGGER.debug("ProjectionDefs read failed in epsg_proj4_formats.json", mapSRS, " - exception: ", e); } return null; } /** * Creates JSON array of layer configurations. * * @param layersArray * @param user * @param lang * @param viewID * @param viewType * @param bundleIds * @param useDirectURLForMyplaces * @param modifyURLs false to keep urls as is, true to modify them for easier proxy forwards * @param forceProxy false to keep urls as is, true to proxy all layers * @param plugins * @return */ public static JSONArray getFullLayerConfig(final JSONArray layersArray, final User user, final String lang, final long viewID, final String viewType, final Set<String> bundleIds, final boolean useDirectURLForMyplaces, final boolean modifyURLs, final String mapSRS, final boolean forceProxy, final JSONArray plugins) { // Create a list of layer ids final List<Integer> layerIdList = new ArrayList<>(); final List<Long> publishedMyPlaces = new ArrayList<Long>(); final List<Long> publishedAnalysis = new ArrayList<Long>(); final List<Long> publishedUserLayers = new ArrayList<Long>(); for (int i = 0; i < layersArray.length(); i++) { String layerId = null; try { final JSONObject layer = layersArray.getJSONObject(i); layerId = layer.getString(KEY_ID); if (layerId == null || layerIdList.contains(layerId)) { continue; } // special handling for myplaces and analysis layers if (layerId.startsWith(PREFIX_MYPLACES)) { final long categoryId = ConversionHelper.getLong(layerId.substring(PREFIX_MYPLACES.length()), -1); if (categoryId != -1) { publishedMyPlaces.add(categoryId); } else { LOGGER.warn("Found my places layer in selected. Error parsing id with category id: ", layerId); } } else if (layerId.startsWith(PREFIX_ANALYSIS)) { final long categoryId = AnalysisHelper.getAnalysisIdFromLayerId(layerId); if (categoryId != -1) { publishedAnalysis.add(categoryId); } else { LOGGER.warn("Found analysis layer in selected. Error parsing id with category id: ", layerId); } } else if (layerId.startsWith(PREFIX_USERLAYERS)) { final long userLayerId = ConversionHelper .getLong(layerId.substring(PREFIX_USERLAYERS.length()), -1); if (userLayerId != -1) { publishedUserLayers.add(userLayerId); } else { LOGGER.warn("Found user layer in selected. Error parsing id with prefixed id: ", layerId); } } else { int id = ConversionHelper.getInt(layerId, -1); if (id != -1) { // these should all be pointing at a layer in oskari_maplayer layerIdList.add(id); } } } catch (JSONException je) { LOGGER.error(je, "Problem handling layer id:", layerId, "skipping it!."); } } final List<OskariLayer> layers = mapLayerService.findByIdList(layerIdList); if (forceProxy) { layers.forEach(lyr -> { if (lyr.getType().equals(OskariLayer.TYPE_3DTILES)) { // Proxy is not supported for 3D layers return; } JSONObject attributes = lyr.getAttributes(); if (attributes == null) { attributes = new JSONObject(); } JSONHelper.putValue(attributes, "forceProxy", forceProxy); lyr.setAttributes(attributes); }); } final JSONObject struct = OskariLayerWorker.getListOfMapLayers( layers, user, lang, mapSRS, ViewTypes.PUBLISHED.equals(viewType), modifyURLs); if (struct.isNull(KEY_LAYERS)) { LOGGER.warn("getSelectedLayersStructure did not return layers when expanding:", layerIdList); } // construct layers JSON final JSONArray prefetch = getLayersArray(struct); appendMyPlacesLayers(prefetch, publishedMyPlaces, user, viewID, lang, bundleIds, useDirectURLForMyplaces, modifyURLs, plugins); appendAnalysisLayers(prefetch, publishedAnalysis, user, viewID, lang, bundleIds, useDirectURLForMyplaces, modifyURLs); appendUserLayers(prefetch, publishedUserLayers, user, viewID, bundleIds, mapSRS); return prefetch; } private static void appendAnalysisLayers(final JSONArray layerList, final List<Long> publishedAnalysis, final User user, final long viewID, final String lang, final Set<String> bundleIds, final boolean useDirectURL, final boolean modifyURLs) { final boolean analyseBundlePresent = bundleIds.contains(BUNDLE_ANALYSE); final Set<String> permissions = permissionsService.getResourcesWithGrantedPermissions( AnalysisLayer.TYPE, user, PermissionType.VIEW_PUBLISHED.name()); LOGGER.debug("Analysis layer permissions for published view", permissions); for (Long id : publishedAnalysis) { final Analysis analysis = analysisService.getAnalysisById(id); if(analysis == null){ continue; } if (analyseBundlePresent && analysis.isOwnedBy(user.getUuid())) { // skip it's an own bundle and analysis bundle is present -> will be loaded via analysisbundle continue; } final String permissionKey = "analysis+" + id; boolean containsKey = permissions.contains(permissionKey); if (!containsKey) { LOGGER.info("Found analysis layer in selected that is no longer published. ViewID:", viewID, "Analysis id:", id); continue; } final JSONObject json = AnalysisHelper.getlayerJSON(analysis, lang, useDirectURL, user.getUuid(), modifyURLs); if (json != null) { layerList.put(json); } } } private static boolean isMyplacesBundlePresent(Set<String> bundleIdList) { for(String bundleId : BUNDLES_HANDLING_MYPLACES_LAYERS) { if(bundleIdList.contains(bundleId)) { return true; } } return false; } private static void appendMyPlacesLayers(final JSONArray layerList, final List<Long> publishedMyPlaces, final User user, final long viewID, final String lang, final Set<String> bundleIds, final boolean useDirectURL, final boolean modifyURLs, final JSONArray plugins) { if (publishedMyPlaces.isEmpty()) { return; } final boolean myPlacesBundlePresent = isMyplacesBundlePresent(bundleIds); // get myplaces categories from service and generate layer jsons final String uuid = user.getUuid(); final List<MyPlaceCategory> myPlacesLayers = myPlaceService .getMyPlaceLayersById(publishedMyPlaces); for (MyPlaceCategory mpLayer : myPlacesLayers) { if (!mpLayer.isPublished() && !mpLayer.isOwnedBy(uuid)) { LOGGER.info("Found my places layer in selected that is no longer published. ViewID:", viewID, "Myplaces layerId:", mpLayer.getId()); // no longer published -> skip if isn't current users layer continue; } if (myPlacesBundlePresent && mpLayer.isOwnedBy(uuid)) { // if the layer is users own -> myplaces2 bundle handles it // so if myplaces2 is present we must skip the users layers continue; } JSONObject myPlaceLayer = null; if (plugins != null && plugins.toString().indexOf(PLUGIN_WFSVECTORLAYER) != -1) { myPlaceLayer = myPlaceService.getCategoryAsWfsLayerJSON(mpLayer, lang); } else { myPlaceLayer = myPlaceService.getCategoryAsWmsLayerJSON( mpLayer, lang, useDirectURL, user.getUuid(), modifyURLs); } if (myPlaceLayer != null) { layerList.put(myPlaceLayer); } } } private static void appendUserLayers(final JSONArray layerList, final List<Long> publishedUserLayers, final User user, final long viewID, final Set<String> bundleIds, final String mapSrs) { final boolean userLayersBundlePresent = bundleIds.contains(BUNDLE_MYPLACESIMPORT); final OskariLayer baseLayer = userLayerDataService.getBaseLayer(); for (Long id : publishedUserLayers) { final UserLayer userLayer = userLayerService.getUserLayerById(id); if (userLayer == null) { LOGGER.warn("Unable to find published user layer with id", id); continue; } if (userLayersBundlePresent && userLayer.isOwnedBy(user.getUuid())) { // skip if it's an own layer and myplacesimport bundle is present -> // will be loaded via aforementioned bundle continue; } if (!userLayer.isPublished() && !userLayer.isOwnedBy(user.getUuid())) { LOGGER.info("Found user layer in selected that is no longer published. ViewID:", viewID, "User layer id:", userLayer.getId()); // no longer published -> skip if isn't current users layer continue; } final JSONObject json = userLayerDataService.parseUserLayer2JSON(userLayer, baseLayer, mapSrs); if (json != null) { layerList.put(json); } } } private static JSONArray getLayersArray(final JSONObject struct) { try { final Object layers = struct.get(KEY_LAYERS); if (layers instanceof JSONArray) { return (JSONArray) layers; } else if (layers instanceof JSONObject) { final JSONArray list = new JSONArray(); list.put(layers); return list; } else { LOGGER.error("getSelectedLayersStructure returned garbage layers."); } } catch (JSONException jsonex) { LOGGER.error("Could not set prefetch layers."); } return new JSONArray(); } private void copySelectedLayersToConfigLayers(final JSONArray mfConfigLayers, final JSONArray mfStateLayers) { for (int i = 0; i < mfStateLayers.length(); i++) { String stateLayerId = null; String confLayerId = null; JSONObject stateLayer = null; JSONObject confLayer = null; try { boolean inConfigLayers = false; stateLayer = mfStateLayers.getJSONObject(i); stateLayerId = stateLayer.getString(KEY_ID); for (int j = 0; j < mfConfigLayers.length(); j++) { confLayer = mfConfigLayers.getJSONObject(j); confLayerId = confLayer.getString(KEY_ID); if (stateLayerId.equals(confLayerId)) { inConfigLayers = true; } } if (!inConfigLayers) { mfConfigLayers.put(stateLayer); } } catch (JSONException je) { LOGGER.error(je, "Problem comparing layers - StateLayerId:", stateLayerId, "vs confLayerId:", confLayerId); } } } public static JSONObject getPlugin(final String pluginClassName, final JSONObject mapfullConfig) { if (mapfullConfig == null || !mapfullConfig.has(KEY_PLUGINS)) { return null; } final JSONArray plugins = mapfullConfig.optJSONArray(KEY_PLUGINS); for (int i = 0; i < plugins.length(); i++) { final JSONObject plugin = plugins.optJSONObject(i); if (plugin == null || !plugin.has(KEY_ID)) { continue; } if (pluginClassName.equals(plugin.optString(KEY_ID))) { LOGGER.debug(pluginClassName, "plugin found at index:", i); return plugin; } } return null; } private void removeMyLocationPluginAutoCenter(final JSONObject mapfullConfig) { JSONObject plugin = getPlugin(PLUGIN_MYLOCATION, mapfullConfig); if (plugin == null && !plugin.has(KEY_CONFIG)) { return; } try { JSONObject config = plugin.getJSONObject(KEY_CONFIG); if(config.has(KEY_CENTER_MAP_AUTOMATICALLY)) { config.remove(KEY_CENTER_MAP_AUTOMATICALLY); } } catch (JSONException jsonex) { LOGGER.error("Problem trying to modify " + PLUGIN_MYLOCATION + " " + KEY_CENTER_MAP_AUTOMATICALLY + ".", jsonex); } } private void removePlugin(final String pluginClassName, final JSONObject mapfullConfig) { if (mapfullConfig == null || !mapfullConfig.has(KEY_PLUGINS)) { return; } final JSONArray plugins = mapfullConfig.optJSONArray(KEY_PLUGINS); for (int i = 0; i < plugins.length(); i++) { final JSONObject plugin = plugins.optJSONObject(i); if (plugin == null || !plugin.has(KEY_ID)) { continue; } if (pluginClassName.equals(plugin.optString(KEY_ID))) { LOGGER.debug(pluginClassName, "plugin found at index:", i, "- removing it"); plugins.remove(i); break; } } } private void killLayerSelectionPlugin(final JSONObject mapfullConfig) { LOGGER.debug("[killLayerSelectionPlugin] removing layer selection plugin"); try { final JSONArray plugins = mapfullConfig.getJSONArray(KEY_PLUGINS); for (int i = 0; i < plugins.length(); i++) { JSONObject plugin = plugins.getJSONObject(i); if (!plugin.has(KEY_ID) || !plugin.has(KEY_CONFIG)) { continue; } String id = plugin.getString(KEY_ID); LOGGER.debug("[killLayerSelectionPlugin] got plugin " + id); if (!id.equals(PLUGIN_LAYERSELECTION)) { continue; } JSONObject config = plugin.getJSONObject(KEY_CONFIG); LOGGER.debug("[killLayerSelectionPlugin] got config"); if (!config.has(KEY_BASELAYERS)) { continue; } JSONArray bl = config.getJSONArray(KEY_BASELAYERS); if (bl.length() < 2) { LOGGER.debug("[killLayerSelectionPlugin] " + "layercount < 2, removing plugin"); plugins.remove(i--); LOGGER.info("[killLayerSelectionPlugin] " + "Removed " + PLUGIN_LAYERSELECTION + "as layercount < 2 and oldId > 0"); } } } catch (JSONException jsonex) { LOGGER.error("Problem trying to figure out whether " + PLUGIN_LAYERSELECTION + " should be removed.", jsonex); } } void epsgInit() { try { InputStream inp = this.getClass().getResourceAsStream(EPSG_PROJ4_FORMATS); if (inp != null) { InputStreamReader reader = new InputStreamReader(inp, "UTF-8"); JSONTokener tokenizer = new JSONTokener(reader); this.epsgMap = JSONHelper.createJSONObject4Tokener(tokenizer); } } catch (Exception e) { LOGGER.info("No setup for epsg proj4 formats found", e); } } void svgInit(){ } }
Fixen npe
control-base/src/main/java/fi/nls/oskari/control/view/modifier/bundle/MapfullHandler.java
Fixen npe
<ide><path>ontrol-base/src/main/java/fi/nls/oskari/control/view/modifier/bundle/MapfullHandler.java <ide> <ide> private void removeMyLocationPluginAutoCenter(final JSONObject mapfullConfig) { <ide> JSONObject plugin = getPlugin(PLUGIN_MYLOCATION, mapfullConfig); <del> if (plugin == null && !plugin.has(KEY_CONFIG)) { <add> if (plugin == null) { <ide> return; <ide> } <ide> try {
Java
apache-2.0
e404e2d37fe21396c1bc9b84ce1a06ba0983a1f1
0
konsoletyper/teavm,konsoletyper/teavm,konsoletyper/teavm,shannah/cn1-teavm-builds,shannah/cn1-teavm-builds,shannah/cn1-teavm-builds,konsoletyper/teavm,shannah/cn1-teavm-builds,shannah/cn1-teavm-builds,konsoletyper/teavm
/* * Copyright 2018 Alexey Andreev. * * 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.teavm.devserver; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import javax.servlet.AsyncContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.util.InputStreamContentProvider; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.websocket.api.UpgradeRequest; import org.eclipse.jetty.websocket.api.UpgradeResponse; import org.eclipse.jetty.websocket.api.WebSocketBehavior; import org.eclipse.jetty.websocket.api.WebSocketPolicy; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.client.io.UpgradeListener; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import org.teavm.backend.javascript.JavaScriptTarget; import org.teavm.cache.InMemoryMethodNodeCache; import org.teavm.cache.InMemoryProgramCache; import org.teavm.cache.MemoryCachedClassReaderSource; import org.teavm.debugging.information.DebugInformation; import org.teavm.debugging.information.DebugInformationBuilder; import org.teavm.dependency.FastDependencyAnalyzer; import org.teavm.model.ClassReader; import org.teavm.model.PreOptimizingClassHolderSource; import org.teavm.parsing.ClasspathClassHolderSource; import org.teavm.tooling.EmptyTeaVMToolLog; import org.teavm.tooling.TeaVMProblemRenderer; import org.teavm.tooling.TeaVMToolLog; import org.teavm.tooling.util.FileSystemWatcher; import org.teavm.vm.MemoryBuildTarget; import org.teavm.vm.TeaVM; import org.teavm.vm.TeaVMBuilder; import org.teavm.vm.TeaVMOptimizationLevel; import org.teavm.vm.TeaVMPhase; import org.teavm.vm.TeaVMProgressFeedback; import org.teavm.vm.TeaVMProgressListener; public class CodeServlet extends HttpServlet { private static final Supplier<InputStream> EMPTY_CONTENT = () -> null; private WebSocketServletFactory wsFactory; private String mainClass; private String[] classPath; private String fileName = "classes.js"; private String pathToFile = "/"; private String indicatorWsPath; private String deobfuscatorPath; private List<String> sourcePath = new ArrayList<>(); private TeaVMToolLog log = new EmptyTeaVMToolLog(); private boolean indicator; private boolean deobfuscateStack; private boolean automaticallyReloaded; private int port; private int debugPort; private String proxyUrl; private String proxyPath = "/"; private String proxyHost; private String proxyProtocol; private int proxyPort; private String proxyBaseUrl; private Map<String, Supplier<InputStream>> sourceFileCache = new HashMap<>(); private volatile boolean stopped; private FileSystemWatcher watcher; private MemoryCachedClassReaderSource classSource; private InMemoryProgramCache programCache; private InMemoryMethodNodeCache astCache; private int lastReachedClasses; private boolean firstTime = true; private final Object contentLock = new Object(); private final Map<String, byte[]> content = new HashMap<>(); private MemoryBuildTarget buildTarget = new MemoryBuildTarget(); private final Set<ProgressHandler> progressHandlers = new LinkedHashSet<>(); private final Object statusLock = new Object(); private volatile boolean cancelRequested; private boolean compiling; private double progress; private boolean waiting; private Thread buildThread; private List<DevServerListener> listeners = new ArrayList<>(); private HttpClient httpClient; private WebSocketClient wsClient = new WebSocketClient(); public CodeServlet(String mainClass, String[] classPath) { this.mainClass = mainClass; this.classPath = classPath.clone(); httpClient = new HttpClient(); httpClient.setFollowRedirects(false); } public void setFileName(String fileName) { this.fileName = fileName; } public void setPathToFile(String pathToFile) { this.pathToFile = normalizePath(pathToFile); } public List<String> getSourcePath() { return sourcePath; } public void setLog(TeaVMToolLog log) { this.log = log; } public void setIndicator(boolean indicator) { this.indicator = indicator; } public void setDeobfuscateStack(boolean deobfuscateStack) { this.deobfuscateStack = deobfuscateStack; } public void setPort(int port) { this.port = port; } public void setDebugPort(int debugPort) { this.debugPort = debugPort; } public void setAutomaticallyReloaded(boolean automaticallyReloaded) { this.automaticallyReloaded = automaticallyReloaded; } public void setProxyUrl(String proxyUrl) { this.proxyUrl = proxyUrl; } public void setProxyPath(String proxyPath) { this.proxyPath = normalizePath(proxyPath); } public void addProgressHandler(ProgressHandler handler) { synchronized (progressHandlers) { progressHandlers.add(handler); } double progress; synchronized (statusLock) { if (!compiling) { return; } progress = this.progress; } handler.progress(progress); } public void removeProgressHandler(ProgressHandler handler) { synchronized (progressHandlers) { progressHandlers.remove(handler); } } public void addListener(DevServerListener listener) { listeners.add(listener); } public void invalidateCache() { synchronized (statusLock) { if (compiling) { return; } astCache.invalidate(); programCache.invalidate(); classSource.invalidate(); } } public void buildProject() { synchronized (statusLock) { if (waiting) { buildThread.interrupt(); } } } public void cancelBuild() { synchronized (statusLock) { if (compiling) { cancelRequested = true; } } } @Override public void init(ServletConfig config) throws ServletException { super.init(config); if (proxyUrl != null) { try { httpClient.start(); wsClient.start(); } catch (Exception e) { throw new RuntimeException(e); } try { URL url = new URL(proxyUrl); proxyPort = url.getPort(); proxyHost = proxyPort >= 0 ? url.getHost() + ":" + proxyPort : url.getHost(); proxyProtocol = url.getProtocol(); StringBuilder sb = new StringBuilder(); sb.append(proxyProtocol).append("://").append(proxyHost); proxyBaseUrl = sb.toString(); } catch (MalformedURLException e) { log.warning("Could not extract host from URL: " + proxyUrl, e); } } indicatorWsPath = pathToFile + fileName + ".ws"; deobfuscatorPath = pathToFile + fileName + ".deobfuscator.js"; WebSocketPolicy wsPolicy = new WebSocketPolicy(WebSocketBehavior.SERVER); wsFactory = WebSocketServletFactory.Loader.load(config.getServletContext(), wsPolicy); wsFactory.setCreator((req, resp) -> { ProxyWsClient proxyClient = (ProxyWsClient) req.getHttpServletRequest().getAttribute("teavm.ws.client"); if (proxyClient == null) { return new CodeWsEndpoint(this); } else { ProxyWsClient proxy = new ProxyWsClient(); proxy.setTarget(proxyClient); proxyClient.setTarget(proxy); return proxy; } }); try { wsFactory.start(); } catch (Exception e) { throw new ServletException(e); } } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = req.getPathInfo(); if (path != null) { log.debug("Serving " + path); if (!path.startsWith("/")) { path = "/" + path; } if (req.getMethod().equals("GET") && path.startsWith(pathToFile) && path.length() > pathToFile.length()) { String fileName = path.substring(pathToFile.length()); if (fileName.startsWith("src/")) { if (serveSourceFile(fileName.substring("src/".length()), resp)) { log.debug("File " + path + " served as source file"); return; } } else if (path.equals(indicatorWsPath)) { if (wsFactory.isUpgradeRequest(req, resp)) { if (wsFactory.acceptWebSocket(req, resp) || resp.isCommitted()) { return; } } } else if (path.equals(deobfuscatorPath)) { serveDeobfuscator(resp); return; } else { byte[] fileContent; boolean firstTime; synchronized (contentLock) { fileContent = content.get(fileName); firstTime = this.firstTime; } if (fileContent != null) { resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getOutputStream().write(fileContent); resp.getOutputStream().flush(); log.debug("File " + path + " served as generated file"); return; } else if (fileName.equals(this.fileName) && indicator && firstTime) { serveBootFile(resp); return; } } } if (proxyUrl != null && path.startsWith(proxyPath)) { if (wsFactory.isUpgradeRequest(req, resp)) { proxyWebSocket(req, resp, path); } else { proxy(req, resp, path); } return; } } log.debug("File " + path + " not found"); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } private void serveDeobfuscator(HttpServletResponse resp) throws IOException { ClassLoader loader = CodeServlet.class.getClassLoader(); resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); try (InputStream input = loader.getResourceAsStream("teavm/devserver/deobfuscator.js")) { IOUtils.copy(input, resp.getOutputStream()); } resp.getOutputStream().flush(); } private void proxy(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException { AsyncContext async = req.startAsync(); String relPath = path.substring(proxyPath.length()); StringBuilder sb = new StringBuilder(proxyUrl); if (!relPath.isEmpty() && !proxyUrl.endsWith("/")) { sb.append("/"); } sb.append(relPath); if (req.getQueryString() != null) { sb.append("?").append(req.getQueryString()); } log.debug("Trying to serve '" + relPath + "' from '" + sb + "'"); Request proxyReq = httpClient.newRequest(sb.toString()); proxyReq.method(req.getMethod()); copyRequestHeaders(req, proxyReq::header); proxyReq.content(new InputStreamContentProvider(req.getInputStream())); HeaderSender headerSender = new HeaderSender(resp); proxyReq.onResponseContent((response, responseContent) -> { headerSender.send(response); try { WritableByteChannel channel = Channels.newChannel(resp.getOutputStream()); while (responseContent.remaining() > 0) { channel.write(responseContent); } } catch (IOException e) { throw new RuntimeException(e); } }); proxyReq.send(result -> { headerSender.send(result.getResponse()); async.complete(); }); } class HeaderSender { final HttpServletResponse resp; boolean sent; HeaderSender(HttpServletResponse resp) { this.resp = resp; } void send(Response response) { if (sent) { return; } sent = true; resp.setStatus(response.getStatus()); for (HttpField field : response.getHeaders()) { if (field.getName().toLowerCase().equals("location")) { String value = field.getValue(); if (value.startsWith(proxyUrl)) { String relLocation = value.substring(proxyUrl.length()); resp.addHeader(field.getName(), "http://localhost:" + port + proxyPath + relLocation); continue; } } resp.addHeader(field.getName(), field.getValue()); } } } private void proxyWebSocket(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException { AsyncContext async = req.startAsync(); String relPath = path.substring(proxyPath.length()); StringBuilder sb = new StringBuilder(proxyProtocol.equals("http") ? "ws" : "wss").append("://"); sb.append(proxyHost); if (!relPath.isEmpty()) { sb.append("/"); } sb.append(relPath); if (req.getQueryString() != null) { sb.append("?").append(req.getQueryString()); } URI uri; try { uri = new URI(sb.toString()); } catch (URISyntaxException e) { throw new RuntimeException(e); } ProxyWsClient client = new ProxyWsClient(); req.setAttribute("teavm.ws.client", client); ClientUpgradeRequest proxyReq = new ClientUpgradeRequest(); proxyReq.setMethod(req.getMethod()); Map<String, List<String>> headers = new LinkedHashMap<>(); copyRequestHeaders(req, (key, value) -> headers.computeIfAbsent(key, k -> new ArrayList<>()).add(value)); proxyReq.setHeaders(headers); wsClient.connect(client, uri, proxyReq, new UpgradeListener() { @Override public void onHandshakeRequest(UpgradeRequest request) { } @Override public void onHandshakeResponse(UpgradeResponse response) { resp.setStatus(response.getStatusCode()); for (String header : response.getHeaderNames()) { switch (header.toLowerCase()) { case "connection": case "date": case "sec-websocket-accept": case "upgrade": continue; } for (String value : response.getHeaders(header)) { resp.addHeader(header, value); } } try { wsFactory.acceptWebSocket(req, resp); } catch (IOException e) { throw new RuntimeException(e); } async.complete(); } }); } private void copyRequestHeaders(HttpServletRequest req, HeaderConsumer proxyReq) { Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement(); String headerLower = header.toLowerCase(); switch (headerLower) { case "host": if (proxyHost != null) { proxyReq.header(header, proxyHost); continue; } break; case "origin": if (proxyBaseUrl != null) { String origin = req.getHeader(header); if (origin.equals("http://localhost:" + port)) { proxyReq.header(header, proxyBaseUrl); continue; } } break; case "referer": { String referer = req.getHeader(header); String localUrl = "http://localhost:" + port + "/"; if (referer.startsWith(localUrl)) { String relReferer = referer.substring(localUrl.length()); proxyReq.header(header, proxyUrl + relReferer); continue; } break; } case "connection": case "upgrade": case "user-agent": case "sec-websocket-key": case "sec-websocket-version": case "sec-websocket-extensions": case "accept-encoding": continue; } Enumeration<String> values = req.getHeaders(header); while (values.hasMoreElements()) { proxyReq.header(header, values.nextElement()); } } } @Override public void destroy() { super.destroy(); try { wsFactory.stop(); } catch (Exception e) { log.warning("Error stopping WebSocket server", e); } if (proxyUrl != null) { try { httpClient.stop(); } catch (Exception e) { log.warning("Error stopping HTTP client", e); } try { wsClient.stop(); } catch (Exception e) { log.warning("Error stopping WebSocket client", e); } } stopped = true; synchronized (statusLock) { if (waiting) { buildThread.interrupt(); } } } @Override public void init() throws ServletException { super.init(); Thread thread = new Thread(this::runTeaVM); thread.setName("TeaVM compiler"); thread.start(); buildThread = thread; } private boolean serveSourceFile(String fileName, HttpServletResponse resp) throws IOException { try (InputStream stream = sourceFileCache.computeIfAbsent(fileName, this::findSourceFile).get()) { if (stream == null) { return false; } resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); IOUtils.copy(stream, resp.getOutputStream()); resp.getOutputStream().flush(); return true; } } private Supplier<InputStream> findSourceFile(String fileName) { for (String element : sourcePath) { File sourceFile = new File(element); if (sourceFile.isFile()) { Supplier<InputStream> result = findSourceFileInZip(sourceFile, fileName); if (result != null) { return result; } } else if (sourceFile.isDirectory()) { File result = new File(sourceFile, fileName); if (result.exists()) { return () -> { try { return new FileInputStream(result); } catch (FileNotFoundException e) { return null; } }; } } } return EMPTY_CONTENT; } private Supplier<InputStream> findSourceFileInZip(File zipFile, String fileName) { try (ZipFile zip = new ZipFile(zipFile)) { ZipEntry entry = zip.getEntry(fileName); if (entry == null) { return null; } return () -> { try { ZipInputStream input = new ZipInputStream(new FileInputStream(zipFile)); while (true) { ZipEntry e = input.getNextEntry(); if (e == null) { return null; } if (e.getName().equals(fileName)) { return input; } } } catch (IOException e) { return null; } }; } catch (IOException e) { return null; } } private void serveBootFile(HttpServletResponse resp) throws IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getWriter().write("function main() { }\n"); resp.getWriter().write(getIndicatorScript(true)); resp.getWriter().flush(); log.debug("Served boot file"); } private void runTeaVM() { try { initBuilder(); while (!stopped) { buildOnce(); if (stopped) { break; } try { synchronized (statusLock) { waiting = true; } watcher.waitForChange(750); synchronized (statusLock) { waiting = false; } log.info("Changes detected. Recompiling."); } catch (InterruptedException e) { if (stopped) { break; } log.info("Build triggered by user"); } List<String> staleClasses = getChangedClasses(watcher.grabChangedFiles()); if (staleClasses.size() > 15) { List<String> displayedStaleClasses = staleClasses.subList(0, 10); log.debug("Following classes changed (" + staleClasses.size() + "): " + String.join(", ", displayedStaleClasses) + " and more..."); } else { log.debug("Following classes changed (" + staleClasses.size() + "): " + String.join(", ", staleClasses)); } classSource.evict(staleClasses); } log.info("Build process stopped"); } catch (Throwable e) { log.error("Compile server crashed", e); } finally { shutdownBuilder(); } } private void initBuilder() throws IOException { watcher = new FileSystemWatcher(classPath); classSource = new MemoryCachedClassReaderSource(); astCache = new InMemoryMethodNodeCache(); programCache = new InMemoryProgramCache(); } private void shutdownBuilder() { try { watcher.dispose(); } catch (IOException e) { log.debug("Exception caught", e); } classSource = null; watcher = null; astCache = null; programCache = null; synchronized (content) { content.clear(); } buildTarget.clear(); log.info("Build thread complete"); } private void buildOnce() { fireBuildStarted(); reportProgress(0); DebugInformationBuilder debugInformationBuilder = new DebugInformationBuilder(); ClassLoader classLoader = initClassLoader(); classSource.setUnderlyingSource(new PreOptimizingClassHolderSource( new ClasspathClassHolderSource(classLoader))); long startTime = System.currentTimeMillis(); JavaScriptTarget jsTarget = new JavaScriptTarget(); TeaVM vm = new TeaVMBuilder(jsTarget) .setClassLoader(classLoader) .setClassSource(classSource) .setDependencyAnalyzerFactory(FastDependencyAnalyzer::new) .build(); jsTarget.setStackTraceIncluded(true); jsTarget.setMinifying(false); jsTarget.setAstCache(astCache); jsTarget.setDebugEmitter(debugInformationBuilder); jsTarget.setClassScoped(true); vm.setOptimizationLevel(TeaVMOptimizationLevel.SIMPLE); vm.setCacheStatus(classSource); vm.addVirtualMethods(m -> true); vm.setProgressListener(progressListener); vm.setProgramCache(programCache); vm.installPlugins(); vm.setLastKnownClasses(lastReachedClasses); vm.entryPoint(mainClass); log.info("Starting build"); progressListener.last = 0; progressListener.lastTime = System.currentTimeMillis(); vm.build(buildTarget, fileName); addIndicator(); generateDebug(debugInformationBuilder); postBuild(vm, startTime); } private void addIndicator() { String script = getIndicatorScript(false); try (Writer writer = new OutputStreamWriter(buildTarget.appendToResource(fileName), StandardCharsets.UTF_8)) { writer.append("\n"); writer.append(script); } catch (IOException e) { throw new RuntimeException("IO error occurred writing debug information", e); } } private String getIndicatorScript(boolean boot) { try (Reader reader = new InputStreamReader(CodeServlet.class.getResourceAsStream("indicator.js"), StandardCharsets.UTF_8)) { String script = IOUtils.toString(reader); script = script.substring(script.indexOf("*/") + 2); script = script.replace("WS_PATH", "localhost:" + port + pathToFile + fileName + ".ws"); script = script.replace("BOOT_FLAG", Boolean.toString(boot)); script = script.replace("RELOAD_FLAG", Boolean.toString(automaticallyReloaded)); script = script.replace("INDICATOR_FLAG", Boolean.toString(indicator)); script = script.replace("DEBUG_PORT", Integer.toString(debugPort)); script = script.replace("FILE_NAME", "\"" + fileName + "\""); script = script.replace("PATH_TO_FILE", "\"http://localhost:" + port + pathToFile + "\""); script = script.replace("DEOBFUSCATE_FLAG", String.valueOf(deobfuscateStack)); return script; } catch (IOException e) { throw new RuntimeException("IO error occurred writing debug information", e); } } private void generateDebug(DebugInformationBuilder debugInformationBuilder) { try { DebugInformation debugInformation = debugInformationBuilder.getDebugInformation(); String sourceMapName = fileName + ".map"; try (Writer writer = new OutputStreamWriter(buildTarget.appendToResource(fileName), StandardCharsets.UTF_8)) { writer.append("\n//# sourceMappingURL=" + sourceMapName); } try (Writer writer = new OutputStreamWriter(buildTarget.createResource(sourceMapName), StandardCharsets.UTF_8)) { debugInformation.writeAsSourceMaps(writer, "src", fileName); } debugInformation.write(buildTarget.createResource(fileName + ".teavmdbg")); } catch (IOException e) { throw new RuntimeException("IO error occurred writing debug information", e); } } private void postBuild(TeaVM vm, long startTime) { if (!vm.wasCancelled()) { log.info("Recompiled stale methods: " + programCache.getPendingItemsCount()); fireBuildComplete(vm); if (vm.getProblemProvider().getSevereProblems().isEmpty()) { log.info("Build complete successfully"); saveNewResult(); lastReachedClasses = vm.getDependencyInfo().getReachableClasses().size(); classSource.commit(); programCache.commit(); astCache.commit(); reportCompilationComplete(true); } else { log.info("Build complete with errors"); reportCompilationComplete(false); } printStats(vm, startTime); TeaVMProblemRenderer.describeProblems(vm, log); } else { log.info("Build cancelled"); fireBuildCancelled(); } astCache.discard(); programCache.discard(); buildTarget.clear(); cancelRequested = false; } private void printStats(TeaVM vm, long startTime) { if (vm.getWrittenClasses() != null) { int classCount = vm.getWrittenClasses().getClassNames().size(); int methodCount = 0; for (String className : vm.getWrittenClasses().getClassNames()) { ClassReader cls = vm.getWrittenClasses().get(className); methodCount += cls.getMethods().size(); } log.info("Classes compiled: " + classCount); log.info("Methods compiled: " + methodCount); } log.info("Compilation took " + (System.currentTimeMillis() - startTime) + " ms"); } private void saveNewResult() { synchronized (contentLock) { firstTime = false; content.clear(); for (String name : buildTarget.getNames()) { content.put(name, buildTarget.getContent(name)); } } } private List<String> getChangedClasses(Collection<File> changedFiles) { List<String> result = new ArrayList<>(); for (File file : changedFiles) { String path = file.getPath(); if (!path.endsWith(".class")) { continue; } String prefix = Arrays.stream(classPath) .filter(path::startsWith) .findFirst() .orElse(""); int start = prefix.length(); if (start < path.length() && path.charAt(start) == '/') { ++start; } path = path.substring(start, path.length() - ".class".length()).replace('/', '.'); result.add(path); } return result; } private ClassLoader initClassLoader() { URL[] urls = new URL[classPath.length]; try { for (int i = 0; i < classPath.length; i++) { urls[i] = new File(classPath[i]).toURI().toURL(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } return new URLClassLoader(urls, CodeServlet.class.getClassLoader()); } private void reportProgress(double progress) { synchronized (statusLock) { if (compiling && this.progress == progress) { return; } compiling = true; this.progress = progress; } ProgressHandler[] handlers; synchronized (progressHandlers) { handlers = progressHandlers.toArray(new ProgressHandler[0]); } for (ProgressHandler handler : handlers) { handler.progress(progress); } for (DevServerListener listener : listeners) { listener.compilationProgress(progress); } } private void reportCompilationComplete(boolean success) { synchronized (statusLock) { if (!compiling) { return; } compiling = false; } ProgressHandler[] handlers; synchronized (progressHandlers) { handlers = progressHandlers.toArray(new ProgressHandler[0]); } for (ProgressHandler handler : handlers) { handler.complete(success); } } private void fireBuildStarted() { for (DevServerListener listener : listeners) { listener.compilationStarted(); } } private void fireBuildCancelled() { for (DevServerListener listener : listeners) { listener.compilationCancelled(); } } private void fireBuildComplete(TeaVM vm) { CodeServletBuildResult result = new CodeServletBuildResult(vm, new ArrayList<>(buildTarget.getNames())); for (DevServerListener listener : listeners) { listener.compilationComplete(result); } } private final ProgressListenerImpl progressListener = new ProgressListenerImpl(); class ProgressListenerImpl implements TeaVMProgressListener { private int start; private int end; private int phaseLimit; private int last; private long lastTime; @Override public TeaVMProgressFeedback phaseStarted(TeaVMPhase phase, int count) { switch (phase) { case DEPENDENCY_ANALYSIS: start = 0; end = 400; break; case LINKING: start = 400; end = 500; break; case OPTIMIZATION: start = 500; end = 750; break; case RENDERING: start = 750; end = 1000; break; } phaseLimit = count; return progressReached(0); } @Override public TeaVMProgressFeedback progressReached(int progress) { if (indicator) { int current = start + Math.min(progress, phaseLimit) * (end - start) / phaseLimit; if (current != last) { if (current - last > 10 || System.currentTimeMillis() - lastTime > 100) { lastTime = System.currentTimeMillis(); last = current; reportProgress(current / 10.0); } } } return getResult(); } private TeaVMProgressFeedback getResult() { if (cancelRequested) { log.info("Trying to cancel compilation due to user request"); return TeaVMProgressFeedback.CANCEL; } if (stopped) { log.info("Trying to cancel compilation due to server stopping"); return TeaVMProgressFeedback.CANCEL; } try { if (watcher.hasChanges()) { log.info("Changes detected, cancelling build"); return TeaVMProgressFeedback.CANCEL; } } catch (IOException e) { log.info("IO error occurred", e); return TeaVMProgressFeedback.CANCEL; } return TeaVMProgressFeedback.CONTINUE; } } static String normalizePath(String path) { if (!path.endsWith("/")) { path += "/"; } if (!path.startsWith("/")) { path = "/" + path; } return path; } }
tools/devserver/src/main/java/org/teavm/devserver/CodeServlet.java
/* * Copyright 2018 Alexey Andreev. * * 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.teavm.devserver; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import javax.servlet.AsyncContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.util.InputStreamContentProvider; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.websocket.api.UpgradeRequest; import org.eclipse.jetty.websocket.api.UpgradeResponse; import org.eclipse.jetty.websocket.api.WebSocketBehavior; import org.eclipse.jetty.websocket.api.WebSocketPolicy; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; import org.eclipse.jetty.websocket.client.io.UpgradeListener; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import org.teavm.backend.javascript.JavaScriptTarget; import org.teavm.cache.InMemoryMethodNodeCache; import org.teavm.cache.InMemoryProgramCache; import org.teavm.cache.MemoryCachedClassReaderSource; import org.teavm.debugging.information.DebugInformation; import org.teavm.debugging.information.DebugInformationBuilder; import org.teavm.dependency.FastDependencyAnalyzer; import org.teavm.model.ClassReader; import org.teavm.model.PreOptimizingClassHolderSource; import org.teavm.parsing.ClasspathClassHolderSource; import org.teavm.tooling.EmptyTeaVMToolLog; import org.teavm.tooling.TeaVMProblemRenderer; import org.teavm.tooling.TeaVMToolLog; import org.teavm.tooling.util.FileSystemWatcher; import org.teavm.vm.MemoryBuildTarget; import org.teavm.vm.TeaVM; import org.teavm.vm.TeaVMBuilder; import org.teavm.vm.TeaVMOptimizationLevel; import org.teavm.vm.TeaVMPhase; import org.teavm.vm.TeaVMProgressFeedback; import org.teavm.vm.TeaVMProgressListener; public class CodeServlet extends HttpServlet { private static final Supplier<InputStream> EMPTY_CONTENT = () -> null; private WebSocketServletFactory wsFactory; private String mainClass; private String[] classPath; private String fileName = "classes.js"; private String pathToFile = "/"; private String indicatorWsPath; private String deobfuscatorPath; private List<String> sourcePath = new ArrayList<>(); private TeaVMToolLog log = new EmptyTeaVMToolLog(); private boolean indicator; private boolean deobfuscateStack; private boolean automaticallyReloaded; private int port; private int debugPort; private String proxyUrl; private String proxyPath = "/"; private String proxyHost; private String proxyProtocol; private int proxyPort; private String proxyBaseUrl; private Map<String, Supplier<InputStream>> sourceFileCache = new HashMap<>(); private volatile boolean stopped; private FileSystemWatcher watcher; private MemoryCachedClassReaderSource classSource; private InMemoryProgramCache programCache; private InMemoryMethodNodeCache astCache; private int lastReachedClasses; private boolean firstTime = true; private final Object contentLock = new Object(); private final Map<String, byte[]> content = new HashMap<>(); private MemoryBuildTarget buildTarget = new MemoryBuildTarget(); private final Set<ProgressHandler> progressHandlers = new LinkedHashSet<>(); private final Object statusLock = new Object(); private volatile boolean cancelRequested; private boolean compiling; private double progress; private boolean waiting; private Thread buildThread; private List<DevServerListener> listeners = new ArrayList<>(); private HttpClient httpClient; private WebSocketClient wsClient = new WebSocketClient(); public CodeServlet(String mainClass, String[] classPath) { this.mainClass = mainClass; this.classPath = classPath.clone(); httpClient = new HttpClient(); httpClient.setFollowRedirects(false); } public void setFileName(String fileName) { this.fileName = fileName; } public void setPathToFile(String pathToFile) { this.pathToFile = normalizePath(pathToFile); } public List<String> getSourcePath() { return sourcePath; } public void setLog(TeaVMToolLog log) { this.log = log; } public void setIndicator(boolean indicator) { this.indicator = indicator; } public void setDeobfuscateStack(boolean deobfuscateStack) { this.deobfuscateStack = deobfuscateStack; } public void setPort(int port) { this.port = port; } public void setDebugPort(int debugPort) { this.debugPort = debugPort; } public void setAutomaticallyReloaded(boolean automaticallyReloaded) { this.automaticallyReloaded = automaticallyReloaded; } public void setProxyUrl(String proxyUrl) { this.proxyUrl = proxyUrl; } public void setProxyPath(String proxyPath) { this.proxyPath = normalizePath(proxyPath); } public void addProgressHandler(ProgressHandler handler) { synchronized (progressHandlers) { progressHandlers.add(handler); } double progress; synchronized (statusLock) { if (!compiling) { return; } progress = this.progress; } handler.progress(progress); } public void removeProgressHandler(ProgressHandler handler) { synchronized (progressHandlers) { progressHandlers.remove(handler); } } public void addListener(DevServerListener listener) { listeners.add(listener); } public void invalidateCache() { synchronized (statusLock) { if (compiling) { return; } astCache.invalidate(); programCache.invalidate(); classSource.invalidate(); } } public void buildProject() { synchronized (statusLock) { if (waiting) { buildThread.interrupt(); } } } public void cancelBuild() { synchronized (statusLock) { if (compiling) { cancelRequested = true; } } } @Override public void init(ServletConfig config) throws ServletException { super.init(config); if (proxyUrl != null) { try { httpClient.start(); wsClient.start(); } catch (Exception e) { throw new RuntimeException(e); } try { URL url = new URL(proxyUrl); proxyPort = url.getPort(); proxyHost = proxyPort != 80 ? url.getHost() + ":" + proxyPort : url.getHost(); proxyProtocol = url.getProtocol(); StringBuilder sb = new StringBuilder(); sb.append(proxyProtocol).append("://").append(proxyHost); proxyBaseUrl = sb.toString(); } catch (MalformedURLException e) { log.warning("Could not extract host from URL: " + proxyUrl, e); } } indicatorWsPath = pathToFile + fileName + ".ws"; deobfuscatorPath = pathToFile + fileName + ".deobfuscator.js"; WebSocketPolicy wsPolicy = new WebSocketPolicy(WebSocketBehavior.SERVER); wsFactory = WebSocketServletFactory.Loader.load(config.getServletContext(), wsPolicy); wsFactory.setCreator((req, resp) -> { ProxyWsClient proxyClient = (ProxyWsClient) req.getHttpServletRequest().getAttribute("teavm.ws.client"); if (proxyClient == null) { return new CodeWsEndpoint(this); } else { ProxyWsClient proxy = new ProxyWsClient(); proxy.setTarget(proxyClient); proxyClient.setTarget(proxy); return proxy; } }); try { wsFactory.start(); } catch (Exception e) { throw new ServletException(e); } } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = req.getPathInfo(); if (path != null) { log.debug("Serving " + path); if (!path.startsWith("/")) { path = "/" + path; } if (req.getMethod().equals("GET") && path.startsWith(pathToFile) && path.length() > pathToFile.length()) { String fileName = path.substring(pathToFile.length()); if (fileName.startsWith("src/")) { if (serveSourceFile(fileName.substring("src/".length()), resp)) { log.debug("File " + path + " served as source file"); return; } } else if (path.equals(indicatorWsPath)) { if (wsFactory.isUpgradeRequest(req, resp)) { if (wsFactory.acceptWebSocket(req, resp) || resp.isCommitted()) { return; } } } else if (path.equals(deobfuscatorPath)) { serveDeobfuscator(resp); return; } else { byte[] fileContent; boolean firstTime; synchronized (contentLock) { fileContent = content.get(fileName); firstTime = this.firstTime; } if (fileContent != null) { resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getOutputStream().write(fileContent); resp.getOutputStream().flush(); log.debug("File " + path + " served as generated file"); return; } else if (fileName.equals(this.fileName) && indicator && firstTime) { serveBootFile(resp); return; } } } if (proxyUrl != null && path.startsWith(proxyPath)) { if (wsFactory.isUpgradeRequest(req, resp)) { proxyWebSocket(req, resp, path); } else { proxy(req, resp, path); } return; } } log.debug("File " + path + " not found"); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } private void serveDeobfuscator(HttpServletResponse resp) throws IOException { ClassLoader loader = CodeServlet.class.getClassLoader(); resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); try (InputStream input = loader.getResourceAsStream("teavm/devserver/deobfuscator.js")) { IOUtils.copy(input, resp.getOutputStream()); } resp.getOutputStream().flush(); } private void proxy(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException { AsyncContext async = req.startAsync(); String relPath = path.substring(proxyPath.length()); StringBuilder sb = new StringBuilder(proxyUrl); if (!relPath.isEmpty() && !proxyUrl.endsWith("/")) { sb.append("/"); } sb.append(relPath); if (req.getQueryString() != null) { sb.append("?").append(req.getQueryString()); } log.debug("Trying to serve '" + relPath + "' from '" + sb + "'"); Request proxyReq = httpClient.newRequest(sb.toString()); proxyReq.method(req.getMethod()); copyRequestHeaders(req, proxyReq::header); proxyReq.content(new InputStreamContentProvider(req.getInputStream())); HeaderSender headerSender = new HeaderSender(resp); proxyReq.onResponseContent((response, responseContent) -> { headerSender.send(response); try { WritableByteChannel channel = Channels.newChannel(resp.getOutputStream()); while (responseContent.remaining() > 0) { channel.write(responseContent); } } catch (IOException e) { throw new RuntimeException(e); } }); proxyReq.send(result -> { headerSender.send(result.getResponse()); async.complete(); }); } class HeaderSender { final HttpServletResponse resp; boolean sent; HeaderSender(HttpServletResponse resp) { this.resp = resp; } void send(Response response) { if (sent) { return; } sent = true; resp.setStatus(response.getStatus()); for (HttpField field : response.getHeaders()) { if (field.getName().toLowerCase().equals("location")) { String value = field.getValue(); if (value.startsWith(proxyUrl)) { String relLocation = value.substring(proxyUrl.length()); resp.addHeader(field.getName(), "http://localhost:" + port + proxyPath + relLocation); continue; } } resp.addHeader(field.getName(), field.getValue()); } } } private void proxyWebSocket(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException { AsyncContext async = req.startAsync(); String relPath = path.substring(proxyPath.length()); StringBuilder sb = new StringBuilder(proxyProtocol.equals("http") ? "ws" : "wss").append("://"); sb.append(proxyHost); if (!relPath.isEmpty()) { sb.append("/"); } sb.append(relPath); if (req.getQueryString() != null) { sb.append("?").append(req.getQueryString()); } URI uri; try { uri = new URI(sb.toString()); } catch (URISyntaxException e) { throw new RuntimeException(e); } ProxyWsClient client = new ProxyWsClient(); req.setAttribute("teavm.ws.client", client); ClientUpgradeRequest proxyReq = new ClientUpgradeRequest(); proxyReq.setMethod(req.getMethod()); Map<String, List<String>> headers = new LinkedHashMap<>(); copyRequestHeaders(req, (key, value) -> headers.computeIfAbsent(key, k -> new ArrayList<>()).add(value)); proxyReq.setHeaders(headers); wsClient.connect(client, uri, proxyReq, new UpgradeListener() { @Override public void onHandshakeRequest(UpgradeRequest request) { } @Override public void onHandshakeResponse(UpgradeResponse response) { resp.setStatus(response.getStatusCode()); for (String header : response.getHeaderNames()) { switch (header.toLowerCase()) { case "connection": case "date": case "sec-websocket-accept": case "upgrade": continue; } for (String value : response.getHeaders(header)) { resp.addHeader(header, value); } } try { wsFactory.acceptWebSocket(req, resp); } catch (IOException e) { throw new RuntimeException(e); } async.complete(); } }); } private void copyRequestHeaders(HttpServletRequest req, HeaderConsumer proxyReq) { Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String header = headers.nextElement(); String headerLower = header.toLowerCase(); switch (headerLower) { case "host": if (proxyHost != null) { proxyReq.header(header, proxyHost); continue; } break; case "origin": if (proxyBaseUrl != null) { String origin = req.getHeader(header); if (origin.equals("http://localhost:" + port)) { proxyReq.header(header, proxyBaseUrl); continue; } } break; case "referer": { String referer = req.getHeader(header); String localUrl = "http://localhost:" + port + "/"; if (referer.startsWith(localUrl)) { String relReferer = referer.substring(localUrl.length()); proxyReq.header(header, proxyUrl + relReferer); continue; } break; } case "connection": case "upgrade": case "user-agent": case "sec-websocket-key": case "sec-websocket-version": case "sec-websocket-extensions": case "accept-encoding": continue; } Enumeration<String> values = req.getHeaders(header); while (values.hasMoreElements()) { proxyReq.header(header, values.nextElement()); } } } @Override public void destroy() { super.destroy(); try { wsFactory.stop(); } catch (Exception e) { log.warning("Error stopping WebSocket server", e); } if (proxyUrl != null) { try { httpClient.stop(); } catch (Exception e) { log.warning("Error stopping HTTP client", e); } try { wsClient.stop(); } catch (Exception e) { log.warning("Error stopping WebSocket client", e); } } stopped = true; synchronized (statusLock) { if (waiting) { buildThread.interrupt(); } } } @Override public void init() throws ServletException { super.init(); Thread thread = new Thread(this::runTeaVM); thread.setName("TeaVM compiler"); thread.start(); buildThread = thread; } private boolean serveSourceFile(String fileName, HttpServletResponse resp) throws IOException { try (InputStream stream = sourceFileCache.computeIfAbsent(fileName, this::findSourceFile).get()) { if (stream == null) { return false; } resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); IOUtils.copy(stream, resp.getOutputStream()); resp.getOutputStream().flush(); return true; } } private Supplier<InputStream> findSourceFile(String fileName) { for (String element : sourcePath) { File sourceFile = new File(element); if (sourceFile.isFile()) { Supplier<InputStream> result = findSourceFileInZip(sourceFile, fileName); if (result != null) { return result; } } else if (sourceFile.isDirectory()) { File result = new File(sourceFile, fileName); if (result.exists()) { return () -> { try { return new FileInputStream(result); } catch (FileNotFoundException e) { return null; } }; } } } return EMPTY_CONTENT; } private Supplier<InputStream> findSourceFileInZip(File zipFile, String fileName) { try (ZipFile zip = new ZipFile(zipFile)) { ZipEntry entry = zip.getEntry(fileName); if (entry == null) { return null; } return () -> { try { ZipInputStream input = new ZipInputStream(new FileInputStream(zipFile)); while (true) { ZipEntry e = input.getNextEntry(); if (e == null) { return null; } if (e.getName().equals(fileName)) { return input; } } } catch (IOException e) { return null; } }; } catch (IOException e) { return null; } } private void serveBootFile(HttpServletResponse resp) throws IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getWriter().write("function main() { }\n"); resp.getWriter().write(getIndicatorScript(true)); resp.getWriter().flush(); log.debug("Served boot file"); } private void runTeaVM() { try { initBuilder(); while (!stopped) { buildOnce(); if (stopped) { break; } try { synchronized (statusLock) { waiting = true; } watcher.waitForChange(750); synchronized (statusLock) { waiting = false; } log.info("Changes detected. Recompiling."); } catch (InterruptedException e) { if (stopped) { break; } log.info("Build triggered by user"); } List<String> staleClasses = getChangedClasses(watcher.grabChangedFiles()); if (staleClasses.size() > 15) { List<String> displayedStaleClasses = staleClasses.subList(0, 10); log.debug("Following classes changed (" + staleClasses.size() + "): " + String.join(", ", displayedStaleClasses) + " and more..."); } else { log.debug("Following classes changed (" + staleClasses.size() + "): " + String.join(", ", staleClasses)); } classSource.evict(staleClasses); } log.info("Build process stopped"); } catch (Throwable e) { log.error("Compile server crashed", e); } finally { shutdownBuilder(); } } private void initBuilder() throws IOException { watcher = new FileSystemWatcher(classPath); classSource = new MemoryCachedClassReaderSource(); astCache = new InMemoryMethodNodeCache(); programCache = new InMemoryProgramCache(); } private void shutdownBuilder() { try { watcher.dispose(); } catch (IOException e) { log.debug("Exception caught", e); } classSource = null; watcher = null; astCache = null; programCache = null; synchronized (content) { content.clear(); } buildTarget.clear(); log.info("Build thread complete"); } private void buildOnce() { fireBuildStarted(); reportProgress(0); DebugInformationBuilder debugInformationBuilder = new DebugInformationBuilder(); ClassLoader classLoader = initClassLoader(); classSource.setUnderlyingSource(new PreOptimizingClassHolderSource( new ClasspathClassHolderSource(classLoader))); long startTime = System.currentTimeMillis(); JavaScriptTarget jsTarget = new JavaScriptTarget(); TeaVM vm = new TeaVMBuilder(jsTarget) .setClassLoader(classLoader) .setClassSource(classSource) .setDependencyAnalyzerFactory(FastDependencyAnalyzer::new) .build(); jsTarget.setStackTraceIncluded(true); jsTarget.setMinifying(false); jsTarget.setAstCache(astCache); jsTarget.setDebugEmitter(debugInformationBuilder); jsTarget.setClassScoped(true); vm.setOptimizationLevel(TeaVMOptimizationLevel.SIMPLE); vm.setCacheStatus(classSource); vm.addVirtualMethods(m -> true); vm.setProgressListener(progressListener); vm.setProgramCache(programCache); vm.installPlugins(); vm.setLastKnownClasses(lastReachedClasses); vm.entryPoint(mainClass); log.info("Starting build"); progressListener.last = 0; progressListener.lastTime = System.currentTimeMillis(); vm.build(buildTarget, fileName); addIndicator(); generateDebug(debugInformationBuilder); postBuild(vm, startTime); } private void addIndicator() { String script = getIndicatorScript(false); try (Writer writer = new OutputStreamWriter(buildTarget.appendToResource(fileName), StandardCharsets.UTF_8)) { writer.append("\n"); writer.append(script); } catch (IOException e) { throw new RuntimeException("IO error occurred writing debug information", e); } } private String getIndicatorScript(boolean boot) { try (Reader reader = new InputStreamReader(CodeServlet.class.getResourceAsStream("indicator.js"), StandardCharsets.UTF_8)) { String script = IOUtils.toString(reader); script = script.substring(script.indexOf("*/") + 2); script = script.replace("WS_PATH", "localhost:" + port + pathToFile + fileName + ".ws"); script = script.replace("BOOT_FLAG", Boolean.toString(boot)); script = script.replace("RELOAD_FLAG", Boolean.toString(automaticallyReloaded)); script = script.replace("INDICATOR_FLAG", Boolean.toString(indicator)); script = script.replace("DEBUG_PORT", Integer.toString(debugPort)); script = script.replace("FILE_NAME", "\"" + fileName + "\""); script = script.replace("PATH_TO_FILE", "\"http://localhost:" + port + pathToFile + "\""); script = script.replace("DEOBFUSCATE_FLAG", String.valueOf(deobfuscateStack)); return script; } catch (IOException e) { throw new RuntimeException("IO error occurred writing debug information", e); } } private void generateDebug(DebugInformationBuilder debugInformationBuilder) { try { DebugInformation debugInformation = debugInformationBuilder.getDebugInformation(); String sourceMapName = fileName + ".map"; try (Writer writer = new OutputStreamWriter(buildTarget.appendToResource(fileName), StandardCharsets.UTF_8)) { writer.append("\n//# sourceMappingURL=" + sourceMapName); } try (Writer writer = new OutputStreamWriter(buildTarget.createResource(sourceMapName), StandardCharsets.UTF_8)) { debugInformation.writeAsSourceMaps(writer, "src", fileName); } debugInformation.write(buildTarget.createResource(fileName + ".teavmdbg")); } catch (IOException e) { throw new RuntimeException("IO error occurred writing debug information", e); } } private void postBuild(TeaVM vm, long startTime) { if (!vm.wasCancelled()) { log.info("Recompiled stale methods: " + programCache.getPendingItemsCount()); fireBuildComplete(vm); if (vm.getProblemProvider().getSevereProblems().isEmpty()) { log.info("Build complete successfully"); saveNewResult(); lastReachedClasses = vm.getDependencyInfo().getReachableClasses().size(); classSource.commit(); programCache.commit(); astCache.commit(); reportCompilationComplete(true); } else { log.info("Build complete with errors"); reportCompilationComplete(false); } printStats(vm, startTime); TeaVMProblemRenderer.describeProblems(vm, log); } else { log.info("Build cancelled"); fireBuildCancelled(); } astCache.discard(); programCache.discard(); buildTarget.clear(); cancelRequested = false; } private void printStats(TeaVM vm, long startTime) { if (vm.getWrittenClasses() != null) { int classCount = vm.getWrittenClasses().getClassNames().size(); int methodCount = 0; for (String className : vm.getWrittenClasses().getClassNames()) { ClassReader cls = vm.getWrittenClasses().get(className); methodCount += cls.getMethods().size(); } log.info("Classes compiled: " + classCount); log.info("Methods compiled: " + methodCount); } log.info("Compilation took " + (System.currentTimeMillis() - startTime) + " ms"); } private void saveNewResult() { synchronized (contentLock) { firstTime = false; content.clear(); for (String name : buildTarget.getNames()) { content.put(name, buildTarget.getContent(name)); } } } private List<String> getChangedClasses(Collection<File> changedFiles) { List<String> result = new ArrayList<>(); for (File file : changedFiles) { String path = file.getPath(); if (!path.endsWith(".class")) { continue; } String prefix = Arrays.stream(classPath) .filter(path::startsWith) .findFirst() .orElse(""); int start = prefix.length(); if (start < path.length() && path.charAt(start) == '/') { ++start; } path = path.substring(start, path.length() - ".class".length()).replace('/', '.'); result.add(path); } return result; } private ClassLoader initClassLoader() { URL[] urls = new URL[classPath.length]; try { for (int i = 0; i < classPath.length; i++) { urls[i] = new File(classPath[i]).toURI().toURL(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } return new URLClassLoader(urls, CodeServlet.class.getClassLoader()); } private void reportProgress(double progress) { synchronized (statusLock) { if (compiling && this.progress == progress) { return; } compiling = true; this.progress = progress; } ProgressHandler[] handlers; synchronized (progressHandlers) { handlers = progressHandlers.toArray(new ProgressHandler[0]); } for (ProgressHandler handler : handlers) { handler.progress(progress); } for (DevServerListener listener : listeners) { listener.compilationProgress(progress); } } private void reportCompilationComplete(boolean success) { synchronized (statusLock) { if (!compiling) { return; } compiling = false; } ProgressHandler[] handlers; synchronized (progressHandlers) { handlers = progressHandlers.toArray(new ProgressHandler[0]); } for (ProgressHandler handler : handlers) { handler.complete(success); } } private void fireBuildStarted() { for (DevServerListener listener : listeners) { listener.compilationStarted(); } } private void fireBuildCancelled() { for (DevServerListener listener : listeners) { listener.compilationCancelled(); } } private void fireBuildComplete(TeaVM vm) { CodeServletBuildResult result = new CodeServletBuildResult(vm, new ArrayList<>(buildTarget.getNames())); for (DevServerListener listener : listeners) { listener.compilationComplete(result); } } private final ProgressListenerImpl progressListener = new ProgressListenerImpl(); class ProgressListenerImpl implements TeaVMProgressListener { private int start; private int end; private int phaseLimit; private int last; private long lastTime; @Override public TeaVMProgressFeedback phaseStarted(TeaVMPhase phase, int count) { switch (phase) { case DEPENDENCY_ANALYSIS: start = 0; end = 400; break; case LINKING: start = 400; end = 500; break; case OPTIMIZATION: start = 500; end = 750; break; case RENDERING: start = 750; end = 1000; break; } phaseLimit = count; return progressReached(0); } @Override public TeaVMProgressFeedback progressReached(int progress) { if (indicator) { int current = start + Math.min(progress, phaseLimit) * (end - start) / phaseLimit; if (current != last) { if (current - last > 10 || System.currentTimeMillis() - lastTime > 100) { lastTime = System.currentTimeMillis(); last = current; reportProgress(current / 10.0); } } } return getResult(); } private TeaVMProgressFeedback getResult() { if (cancelRequested) { log.info("Trying to cancel compilation due to user request"); return TeaVMProgressFeedback.CANCEL; } if (stopped) { log.info("Trying to cancel compilation due to server stopping"); return TeaVMProgressFeedback.CANCEL; } try { if (watcher.hasChanges()) { log.info("Changes detected, cancelling build"); return TeaVMProgressFeedback.CANCEL; } } catch (IOException e) { log.info("IO error occurred", e); return TeaVMProgressFeedback.CANCEL; } return TeaVMProgressFeedback.CONTINUE; } } static String normalizePath(String path) { if (!path.endsWith("/")) { path += "/"; } if (!path.startsWith("/")) { path = "/" + path; } return path; } }
Fix proxy bug in dev server
tools/devserver/src/main/java/org/teavm/devserver/CodeServlet.java
Fix proxy bug in dev server
<ide><path>ools/devserver/src/main/java/org/teavm/devserver/CodeServlet.java <ide> try { <ide> URL url = new URL(proxyUrl); <ide> proxyPort = url.getPort(); <del> proxyHost = proxyPort != 80 ? url.getHost() + ":" + proxyPort : url.getHost(); <add> proxyHost = proxyPort >= 0 ? url.getHost() + ":" + proxyPort : url.getHost(); <ide> proxyProtocol = url.getProtocol(); <ide> <ide> StringBuilder sb = new StringBuilder();
JavaScript
mit
3addf74fde4c78a4a4aefb2cbf425e7e42ee9ed5
0
bbyars/mountebank,nassimkirouane/mountebank,nassimkirouane/mountebank,nassimkirouane/mountebank,bbyars/mountebank,nassimkirouane/mountebank
'use strict'; var assert = require('assert'), HttpProxy = require('../../../src/models/http/httpProxy'), api = require('../api'), promiseIt = require('../../testHelpers').promiseIt, port = api.port + 1, timeout = parseInt(process.env.MB_SLOW_TEST_TIMEOUT || 3000), airplaneMode = process.env.MB_AIRPLANE_MODE === 'true'; describe('http proxy', function () { this.timeout(timeout); var noOp = function () {}, logger = { debug: noOp, info: noOp, warn: noOp, error: noOp }, proxy = HttpProxy.create(logger); describe('#to', function () { promiseIt('should send same request information to proxied url', function () { var proxyRequest = { protocol: 'http', port: port, name: this.name }, request = { path: '/PATH', method: 'POST', body: 'BODY', headers: { 'X-Key': 'TRUE' } }; return api.post('/imposters', proxyRequest).then(function () { return proxy.to('http://localhost:' + port, request, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 200, 'did not get a 200 from proxy'); return api.get('/imposters/' + port); }).then(function (response) { var requests = response.body.requests; assert.strictEqual(requests.length, 1); assert.strictEqual(requests[0].path, '/PATH'); assert.strictEqual(requests[0].method, 'POST'); assert.strictEqual(requests[0].body, 'BODY'); assert.strictEqual(requests[0].headers['X-Key'], 'TRUE'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should return proxied result', function () { var stub = { responses: [{ is: { statusCode: 400, body: 'ERROR' } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 400); assert.strictEqual(response.body, 'ERROR'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should proxy to https', function () { var stub = { responses: [{ is: { statusCode: 400, body: 'ERROR' } }] }, request = { protocol: 'https', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('https://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 400); assert.strictEqual(response.body, 'ERROR'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should update the host header to the origin server', function () { var stub = { responses: [{ is: { statusCode: 400, body: 'ERROR' } }], predicates: [{ equals: { headers: { host: 'localhost:' + port } } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: { host: 'www.mbtest.org' } }, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 400); assert.strictEqual(response.body, 'ERROR'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should capture response time to origin server', function () { var stub = { responses: [{ is: { body: 'ORIGIN' }, _behaviors: { wait: 250 } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.body, 'ORIGIN'); assert.ok(response._proxyResponseTime > 230); // eslint-disable-line no-underscore-dangle }).finally(function () { return api.del('/imposters'); }); }); if (!airplaneMode) { promiseIt('should gracefully deal with DNS errors', function () { return proxy.to('http://no.such.domain', { path: '/', method: 'GET', headers: {} }, {}).then(function () { assert.fail('should not have resolved promise'); }, function (reason) { assert.deepEqual(reason, { code: 'invalid proxy', message: 'Cannot resolve "http://no.such.domain"' }); }); }); promiseIt('should gracefully deal with bad urls', function () { return proxy.to('1 + 2', { path: '/', method: 'GET', headers: {} }, {}).then(function () { assert.fail('should not have resolved promise'); }, function (reason) { assert.deepEqual(reason, { code: 'invalid proxy', message: 'Unable to connect to "1 + 2"' }); }); }); } ['application/octet-stream', 'audio/mpeg', 'audio/mp4', 'image/gif', 'image/jpeg', 'video/avi', 'video/mpeg'].forEach(function (mimeType) { promiseIt('should base64 encode ' + mimeType + ' responses', function () { var buffer = new Buffer([0, 1, 2, 3]), stub = { responses: [{ is: { body: buffer.toString('base64'), headers: { 'content-type': mimeType }, _mode: 'binary' } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.body, buffer.toString('base64')); assert.strictEqual(response._mode, 'binary'); }).finally(function () { return api.del('/imposters'); }); }); }); if (!airplaneMode) { promiseIt('should proxy to different host', function () { return proxy.to('https://google.com', { path: '/', method: 'GET', headers: {} }, {}).then(function (response) { // sometimes 301, sometimes 302 assert.strictEqual(response.statusCode.toString().substring(0, 2), '30'); // https://www.google.com.br in Brasil, google.ca in Canada, etc assert.ok(response.headers.Location.indexOf('google.') >= 0, response.headers.Location); }); }); } }); });
functionalTest/api/http/httpProxyTest.js
'use strict'; var assert = require('assert'), HttpProxy = require('../../../src/models/http/httpProxy'), api = require('../api'), promiseIt = require('../../testHelpers').promiseIt, port = api.port + 1, timeout = parseInt(process.env.MB_SLOW_TEST_TIMEOUT || 3000), airplaneMode = process.env.MB_AIRPLANE_MODE === 'true'; describe('http proxy', function () { this.timeout(timeout); var noOp = function () {}, logger = { debug: noOp, info: noOp, warn: noOp, error: noOp }, proxy = HttpProxy.create(logger); describe('#to', function () { promiseIt('should send same request information to proxied url', function () { var proxyRequest = { protocol: 'http', port: port, name: this.name }, request = { path: '/PATH', method: 'POST', body: 'BODY', headers: { 'X-Key': 'TRUE' } }; return api.post('/imposters', proxyRequest).then(function () { return proxy.to('http://localhost:' + port, request, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 200, 'did not get a 200 from proxy'); return api.get('/imposters/' + port); }).then(function (response) { var requests = response.body.requests; assert.strictEqual(requests.length, 1); assert.strictEqual(requests[0].path, '/PATH'); assert.strictEqual(requests[0].method, 'POST'); assert.strictEqual(requests[0].body, 'BODY'); assert.strictEqual(requests[0].headers['X-Key'], 'TRUE'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should return proxied result', function () { var stub = { responses: [{ is: { statusCode: 400, body: 'ERROR' } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 400); assert.strictEqual(response.body, 'ERROR'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should proxy to https', function () { var stub = { responses: [{ is: { statusCode: 400, body: 'ERROR' } }] }, request = { protocol: 'https', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('https://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 400); assert.strictEqual(response.body, 'ERROR'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should update the host header to the origin server', function () { var stub = { responses: [{ is: { statusCode: 400, body: 'ERROR' } }], predicates: [{ equals: { headers: { host: 'localhost:' + port } } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: { host: 'www.mbtest.org' } }, {}); }).then(function (response) { assert.strictEqual(response.statusCode, 400); assert.strictEqual(response.body, 'ERROR'); }).finally(function () { return api.del('/imposters'); }); }); promiseIt('should capture response time to origin server', function () { var stub = { responses: [{ is: { body: 'ORIGIN' }, _behaviors: { wait: 250 } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.body, 'ORIGIN'); assert.ok(response._proxyResponseTime > 230); // eslint-disable-line no-underscore-dangle }).finally(function () { return api.del('/imposters'); }); }); if (!airplaneMode) { promiseIt('should gracefully deal with DNS errors', function () { return proxy.to('http://no.such.domain', { path: '/', method: 'GET', headers: {} }, {}).then(function () { assert.fail('should not have resolved promise'); }, function (reason) { assert.deepEqual(reason, { code: 'invalid proxy', message: 'Cannot resolve "http://no.such.domain"' }); }); }); } promiseIt('should gracefully deal with bad urls', function () { return proxy.to('1 + 2', { path: '/', method: 'GET', headers: {} }, {}).then(function () { assert.fail('should not have resolved promise'); }, function (reason) { assert.deepEqual(reason, { code: 'invalid proxy', message: 'Unable to connect to "1 + 2"' }); }); }); ['application/octet-stream', 'audio/mpeg', 'audio/mp4', 'image/gif', 'image/jpeg', 'video/avi', 'video/mpeg'].forEach(function (mimeType) { promiseIt('should base64 encode ' + mimeType + ' responses', function () { var buffer = new Buffer([0, 1, 2, 3]), stub = { responses: [{ is: { body: buffer.toString('base64'), headers: { 'content-type': mimeType }, _mode: 'binary' } }] }, request = { protocol: 'http', port: port, stubs: [stub], name: this.name }; return api.post('/imposters', request).then(function (response) { assert.strictEqual(response.statusCode, 201, JSON.stringify(response.body)); return proxy.to('http://localhost:' + port, { path: '/', method: 'GET', headers: {} }, {}); }).then(function (response) { assert.strictEqual(response.body, buffer.toString('base64')); assert.strictEqual(response._mode, 'binary'); }).finally(function () { return api.del('/imposters'); }); }); }); if (!airplaneMode) { promiseIt('should proxy to different host', function () { return proxy.to('https://google.com', { path: '/', method: 'GET', headers: {} }, {}).then(function (response) { // sometimes 301, sometimes 302 assert.strictEqual(response.statusCode.toString().substring(0, 2), '30'); // https://www.google.com.br in Brasil, google.ca in Canada, etc assert.ok(response.headers.Location.indexOf('google.') >= 0, response.headers.Location); }); }); } }); });
Wrapped in airplane check; started failing this morning at home
functionalTest/api/http/httpProxyTest.js
Wrapped in airplane check; started failing this morning at home
<ide><path>unctionalTest/api/http/httpProxyTest.js <ide> }); <ide> }); <ide> }); <add> <add> promiseIt('should gracefully deal with bad urls', function () { <add> return proxy.to('1 + 2', { path: '/', method: 'GET', headers: {} }, {}).then(function () { <add> assert.fail('should not have resolved promise'); <add> }, function (reason) { <add> assert.deepEqual(reason, { <add> code: 'invalid proxy', <add> message: 'Unable to connect to "1 + 2"' <add> }); <add> }); <add> }); <ide> } <ide> <del> promiseIt('should gracefully deal with bad urls', function () { <del> return proxy.to('1 + 2', { path: '/', method: 'GET', headers: {} }, {}).then(function () { <del> assert.fail('should not have resolved promise'); <del> }, function (reason) { <del> assert.deepEqual(reason, { <del> code: 'invalid proxy', <del> message: 'Unable to connect to "1 + 2"' <del> }); <del> }); <del> }); <ide> <ide> ['application/octet-stream', 'audio/mpeg', 'audio/mp4', 'image/gif', 'image/jpeg', 'video/avi', 'video/mpeg'].forEach(function (mimeType) { <ide> promiseIt('should base64 encode ' + mimeType + ' responses', function () {
Java
apache-2.0
d2dd9b5a3ba9a395474ad1dd5ee4d30d88f79900
0
Mnkai/PGPClipper
package moe.minori.pgpclipper.activities; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import moe.minori.pgpclipper.PGPClipperService; import moe.minori.pgpclipper.R; public class PGPClipperSettingsActivity extends AppCompatActivity { SettingFragment fragment; @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, fragment = new SettingFragment()).commit(); } @Override protected void onPause() { super.onPause(); } public static class SettingFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_general); findPreference("enabledCheckBox").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if ((boolean) newValue) // enabled getActivity().startService(new Intent(getActivity(), PGPClipperService.class)); else // disabled getActivity().stopService(new Intent(getActivity(), PGPClipperService.class)); return true; } }); findPreference("issueTrackerPreferenceItem").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent webBrowserLaunchIntent = new Intent(Intent.ACTION_VIEW); webBrowserLaunchIntent.setData(Uri.parse("https://github.com/Mnkai/PGPClipper")); startActivity(webBrowserLaunchIntent); return true; } }); findPreference("licensePreferenceItem").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent webBrowserLaunchIntent = new Intent(Intent.ACTION_VIEW); webBrowserLaunchIntent.setData(Uri.parse("https://github.com/Mnkai/PGPClipper/blob/master/LICENSE")); startActivity(webBrowserLaunchIntent); return true; } }); findPreference("thirdPartyLicensePreferenceItem").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent webBrowserLaunchIntent = new Intent(Intent.ACTION_VIEW); webBrowserLaunchIntent.setData(Uri.parse("https://github.com/Mnkai/PGPClipper/blob/master/LICENSE")); startActivity(webBrowserLaunchIntent); return true; } }); final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); final SharedPreferences.Editor editor = sharedPreferences.edit(); final ListPreference themePref = (ListPreference) findPreference("themeSelection"); themePref.setEntryValues(R.array.themes_values); themePref.setEntries(R.array.themes); String currentVal = sharedPreferences.getString("themeSelection", "dark"); switch (currentVal) { case "dark": themePref.setSummary(getResources().getString(R.string.darkText)); break; case "light": themePref.setSummary(getResources().getString(R.string.lightText)); break; } themePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch ((String) newValue) { case "dark": themePref.setSummary(getResources().getString(R.string.darkText)); break; case "light": themePref.setSummary(getResources().getString(R.string.lightText)); break; } return true; } }); final CheckBoxPreference enabledPref = (CheckBoxPreference)findPreference("enabledCheckBox"); findPreference("pgpServiceProviderApp").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String providerApp = (String) newValue; if (providerApp == null || "".equals(providerApp)) { enabledPref.setEnabled(false); enabledPref.setChecked(false); getActivity().stopService(new Intent(getActivity(), PGPClipperService.class)); } else { enabledPref.setEnabled(true); } return true; } }); String providerApp = sharedPreferences.getString("pgpServiceProviderApp",null); if(providerApp == null || "".equals(providerApp)){ enabledPref.setEnabled(false); enabledPref.setChecked(false); getActivity().stopService(new Intent(getActivity(), PGPClipperService.class)); }else { if (enabledPref.isChecked()) { getActivity().startService(new Intent(getActivity(), PGPClipperService.class)); } enabledPref.setEnabled(true); } // for NFC authentication findPreference("enableNFCAuth").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (!((boolean) newValue)) { // delete current hash and encrypted data NFCAuthenticationSetupActivity.initSetting(editor); } else { // start NFCAuthSetupActivity Intent intent = new Intent(getActivity(), NFCAuthenticationSetupActivity.class); startActivityForResult(intent, 7272 ); } return true; } }); // For Fingerprint authentication findPreference("enableFingerprintAuth").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (!((boolean) newValue)) { //TODO: Remove password entry from secure storage } else { //TODO: Check fingerprint enrollment //TODO: Put password into secure storage //TODO: Setup fingerprint flag } return true; } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("SettingsActivity", "onActivityResult called"); if ( requestCode == 7272 ) // NFCAuthSetupResult { if ( resultCode != RESULT_OK ) // error or user canceled auth operation { CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference("enableNFCAuth"); checkBoxPreference.setChecked(false); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { fragment.onActivityResult(requestCode, resultCode, data); } }
app/src/main/java/moe/minori/pgpclipper/activities/PGPClipperSettingsActivity.java
package moe.minori.pgpclipper.activities; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import moe.minori.pgpclipper.PGPClipperService; import moe.minori.pgpclipper.R; public class PGPClipperSettingsActivity extends AppCompatActivity { SettingFragment fragment; @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, fragment = new SettingFragment()).commit(); } @Override protected void onPause() { super.onPause(); } public static class SettingFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_general); findPreference("enabledCheckBox").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if ((boolean) newValue) // enabled getActivity().startService(new Intent(getActivity(), PGPClipperService.class)); else // disabled getActivity().stopService(new Intent(getActivity(), PGPClipperService.class)); return true; } }); findPreference("issueTrackerPreferenceItem").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent webBrowserLaunchIntent = new Intent(Intent.ACTION_VIEW); webBrowserLaunchIntent.setData(Uri.parse("https://github.com/Mnkai/PGPClipper")); startActivity(webBrowserLaunchIntent); return true; } }); findPreference("licensePreferenceItem").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent webBrowserLaunchIntent = new Intent(Intent.ACTION_VIEW); webBrowserLaunchIntent.setData(Uri.parse("https://github.com/Mnkai/PGPClipper/blob/master/LICENSE")); startActivity(webBrowserLaunchIntent); return true; } }); findPreference("thirdPartyLicensePreferenceItem").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent webBrowserLaunchIntent = new Intent(Intent.ACTION_VIEW); webBrowserLaunchIntent.setData(Uri.parse("https://github.com/Mnkai/PGPClipper/blob/master/LICENSE")); startActivity(webBrowserLaunchIntent); return true; } }); final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); final SharedPreferences.Editor editor = sharedPreferences.edit(); final ListPreference themePref = (ListPreference) findPreference("themeSelection"); themePref.setEntryValues(R.array.themes_values); themePref.setEntries(R.array.themes); String currentVal = sharedPreferences.getString("themeSelection", "dark"); switch (currentVal) { case "dark": themePref.setSummary(getResources().getString(R.string.darkText)); break; case "light": themePref.setSummary(getResources().getString(R.string.lightText)); break; } themePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch ((String) newValue) { case "dark": themePref.setSummary(getResources().getString(R.string.darkText)); break; case "light": themePref.setSummary(getResources().getString(R.string.lightText)); break; } return true; } }); final CheckBoxPreference enabledPref = (CheckBoxPreference)findPreference("enabledCheckBox"); findPreference("pgpServiceProviderApp").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String providerApp = (String) newValue; if (providerApp == null || "".equals(providerApp)) { enabledPref.setEnabled(false); enabledPref.setChecked(false); getActivity().stopService(new Intent(getActivity(), PGPClipperService.class)); } else { enabledPref.setEnabled(true); } return true; } }); String providerApp = sharedPreferences.getString("pgpServiceProviderApp",null); if(providerApp == null || "".equals(providerApp)){ enabledPref.setEnabled(false); enabledPref.setChecked(false); getActivity().stopService(new Intent(getActivity(), PGPClipperService.class)); }else { if (enabledPref.isChecked()) { getActivity().startService(new Intent(getActivity(), PGPClipperService.class)); } enabledPref.setEnabled(true); } // for NFC authentication findPreference("enableNFCAuth").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if ( (boolean) newValue == false ) { // delete current hash and encrypted data NFCAuthenticationSetupActivity.initSetting(editor); } else { // start NFCAuthSetupActivity Intent intent = new Intent(getActivity(), NFCAuthenticationSetupActivity.class); startActivityForResult(intent, 7272 ); } return true; } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("SettingsActivity", "onActivityResult called"); if ( requestCode == 7272 ) // NFCAuthSetupResult { if ( resultCode != RESULT_OK ) // error or user canceled auth operation { CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference("enableNFCAuth"); checkBoxPreference.setChecked(false); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { fragment.onActivityResult(requestCode, resultCode, data); } }
Major fingerprint authentication plan (disclaimer, may not be that major)
app/src/main/java/moe/minori/pgpclipper/activities/PGPClipperSettingsActivity.java
Major fingerprint authentication plan (disclaimer, may not be that major)
<ide><path>pp/src/main/java/moe/minori/pgpclipper/activities/PGPClipperSettingsActivity.java <ide> findPreference("enableNFCAuth").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { <ide> @Override <ide> public boolean onPreferenceChange(Preference preference, Object newValue) { <del> if ( (boolean) newValue == false ) <add> if (!((boolean) newValue)) <ide> { <ide> // delete current hash and encrypted data <ide> <ide> Intent intent = new Intent(getActivity(), NFCAuthenticationSetupActivity.class); <ide> <ide> startActivityForResult(intent, 7272 ); <add> } <add> return true; <add> } <add> }); <add> <add> // For Fingerprint authentication <add> <add> findPreference("enableFingerprintAuth").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { <add> @Override <add> public boolean onPreferenceChange(Preference preference, Object newValue) { <add> if (!((boolean) newValue)) <add> { <add> //TODO: Remove password entry from secure storage <add> <add> } <add> else <add> { <add> //TODO: Check fingerprint enrollment <add> //TODO: Put password into secure storage <add> //TODO: Setup fingerprint flag <ide> } <ide> return true; <ide> }
Java
mit
a7fb1e6b532e7c56d1362b33a5b18dc039e4e84e
0
stachu540/HiRezAPI,stachu540/HiRezAPI
package com.github.stachu540.hirezapi.api; import com.github.stachu540.hirezapi.api.serverstatus.ServerStatusIncident; import com.github.stachu540.hirezapi.enums.url.BasePlatform; import com.github.stachu540.hirezapi.models.json.ServiceStatus; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @Getter @Setter public class StatusServer { private final List<ServerStatusIncident> incidents = new ArrayList<ServerStatusIncident>(); @Setter(AccessLevel.NONE) private SyndFeed feed = new SyndFeedInput() .build(new XmlReader(new URL("http://status.hirezstudios.com/history.atom"))); private String game; private String platform; private ServiceStatus.Status status; public StatusServer() throws Exception { reload(); } public StatusServer(BasePlatform platform, boolean allPlatforms) throws Exception { setGamePlatform(platform, allPlatforms); reload(); } public StatusServer(BasePlatform platform) throws Exception { setGamePlatform(platform); reload(); } public void setGamePlatform(BasePlatform platform) { setGamePlatform(platform, false); } public void setGamePlatform(BasePlatform platform, boolean allPlatforms) { this.game = platform.getGame(); this.platform = (allPlatforms) ? null : platform.getPlatform(); } private void reload() { if (!incidents.isEmpty()) { incidents.clear(); } for (SyndEntry entry : feed.getEntries()) { ServerStatusIncident incident = new ServerStatusIncident( entry.getTitle(), entry.getLink(), entry.getContents().get(0).getValue()); if (incident.contains(game)) { if (platform != null && incident.contains(platform)) { incidents.add(incident); } else { incidents.add(incident); } } } } public ServerStatusIncident getIncident(int i) { reload(); return incidents.get(i); } @Override public String toString() { return incidents.toString(); } }
src/main/java/com/github/stachu540/hirezapi/api/StatusServer.java
package com.github.stachu540.hirezapi.api; import com.github.stachu540.hirezapi.api.serverstatus.ServerStatusIncident; import com.github.stachu540.hirezapi.enums.url.BasePlatform; import com.github.stachu540.hirezapi.models.json.ServiceStatus; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @Getter @Setter public class StatusServer { private final List<ServerStatusIncident> incidents = new ArrayList<ServerStatusIncident>(); @Setter(AccessLevel.NONE) private SyndFeed feed = new SyndFeedInput() .build(new XmlReader(new URL("http://status.hirezstudios.com/history.atom"))); private String game; private String platform; private ServiceStatus.Status status; public StatusServer() throws Exception { reload(); } public StatusServer(BasePlatform platform, boolean allPlatforms) throws Exception { setGamePlatform(platform, allPlatforms); reload(); } public StatusServer(BasePlatform platform) throws Exception { setGamePlatform(platform); reload(); } public void setGamePlatform(BasePlatform platform) { setGamePlatform(platform, false); } public void setGamePlatform(BasePlatform platform, boolean allPlatforms) { this.game = platform.getGame(); this.platform = (allPlatforms) ? null : platform.getPlatform(); } private void reload() { if (!incidents.isEmpty()) { incidents.clear(); } for (SyndEntry entry : feed.getEntries()) { ServerStatusIncident incident = new ServerStatusIncident( entry.getTitle(), entry.getLink(), entry.getContents().get(0).getValue()); if ((incident.contains(game) && incident.contains(platform))) { incidents.add(incident); } } } public ServerStatusIncident getIncident(int i) { reload(); return incidents.get(i); } @Override public String toString() { return incidents.toString(); } }
server status fix - status returns NullPointException for game-specific only status
src/main/java/com/github/stachu540/hirezapi/api/StatusServer.java
server status fix
<ide><path>rc/main/java/com/github/stachu540/hirezapi/api/StatusServer.java <ide> ServerStatusIncident incident = <ide> new ServerStatusIncident( <ide> entry.getTitle(), entry.getLink(), entry.getContents().get(0).getValue()); <del> if ((incident.contains(game) && incident.contains(platform))) { <del> incidents.add(incident); <add> if (incident.contains(game)) { <add> if (platform != null && incident.contains(platform)) { <add> incidents.add(incident); <add> } else { <add> incidents.add(incident); <add> } <ide> } <ide> } <ide> }
JavaScript
isc
d7ab0427691a678b56fc440811c01af5686cd303
0
aceakash/kata-roman-numerals
var romanSymbols = { exceptionsFirst: [ {symbol: 'IV', value: 4}, {symbol: 'IX', value: 9}, {symbol: 'XL', value: 40}, {symbol: 'XC', value: 90}, {symbol: 'CD', value: 400}, {symbol: 'CM', value: 900}, {symbol: 'I', value: 1}, {symbol: 'V', value: 5}, {symbol: 'X', value: 10}, {symbol: 'L', value: 50}, {symbol: 'C', value: 100}, {symbol: 'D', value: 500}, {symbol: 'M', value: 1000} ] }; romanSymbols.sortedDescByValue = romanSymbols.exceptionsFirst .slice(0).sort(function (a, b) { return b.value - a.value; }); function findLargestFittingSymbol(number) { for (var i = 0; i < romanSymbols.sortedDescByValue.length; i++) { var current = romanSymbols.sortedDescByValue[i]; if (current.value <= number) { return current; } } } exports.fromRoman = function (roman) { var total = 0; romanSymbols.exceptionsFirst.forEach(function (symbol) { var regex = new RegExp(symbol.symbol, 'g'); var matches = roman.match(regex) || []; var count = matches.length; total += count * symbol.value; roman = roman.replace(regex, ''); }); return total; }; exports.toRoman = function (number) { var roman = ''; while (number !== 0) { var bestFit = findLargestFittingSymbol(number); roman += bestFit.symbol; number -= bestFit.value; } return roman; };
roman-numerals.js
var romanSymbols = [ {symbol: 'IV', value: 4}, {symbol: 'IX', value: 9}, {symbol: 'XL', value: 40}, {symbol: 'XC', value: 90}, {symbol: 'CD', value: 400}, {symbol: 'CM', value: 900}, {symbol: 'I', value: 1}, {symbol: 'V', value: 5}, {symbol: 'X', value: 10}, {symbol: 'L', value: 50}, {symbol: 'C', value: 100}, {symbol: 'D', value: 500}, {symbol: 'M', value: 1000} ]; var sortedRomanSymbols = romanSymbols.slice(0).sort(function (a, b) { return b.value - a.value; }); function findLargestFittingSymbol(number) { for (var i = 0; i < sortedRomanSymbols.length; i++) { if (sortedRomanSymbols[i].value <= number) { return sortedRomanSymbols[i]; } } } exports.fromRoman = function (roman) { var total = 0; romanSymbols.forEach(function (symbol) { var regex = new RegExp(symbol.symbol, 'g'); var matches = roman.match(regex) || []; var count = matches.length; total += count * symbol.value; roman = roman.replace(regex, ''); }); return total; }; exports.toRoman = function (number) { var roman = ''; while (number !== 0) { var bestFit = findLargestFittingSymbol(number); roman += bestFit.symbol; number -= bestFit.value; } return roman; };
refactoring
roman-numerals.js
refactoring
<ide><path>oman-numerals.js <del>var romanSymbols = [ <del> {symbol: 'IV', value: 4}, <del> {symbol: 'IX', value: 9}, <del> {symbol: 'XL', value: 40}, <del> {symbol: 'XC', value: 90}, <del> {symbol: 'CD', value: 400}, <del> {symbol: 'CM', value: 900}, <add>var romanSymbols = { <add> exceptionsFirst: [ <add> {symbol: 'IV', value: 4}, <add> {symbol: 'IX', value: 9}, <add> {symbol: 'XL', value: 40}, <add> {symbol: 'XC', value: 90}, <add> {symbol: 'CD', value: 400}, <add> {symbol: 'CM', value: 900}, <ide> <del> {symbol: 'I', value: 1}, <del> {symbol: 'V', value: 5}, <del> {symbol: 'X', value: 10}, <del> {symbol: 'L', value: 50}, <del> {symbol: 'C', value: 100}, <del> {symbol: 'D', value: 500}, <del> {symbol: 'M', value: 1000} <del>]; <add> {symbol: 'I', value: 1}, <add> {symbol: 'V', value: 5}, <add> {symbol: 'X', value: 10}, <add> {symbol: 'L', value: 50}, <add> {symbol: 'C', value: 100}, <add> {symbol: 'D', value: 500}, <add> {symbol: 'M', value: 1000} <add> ] <add>}; <ide> <del>var sortedRomanSymbols = romanSymbols.slice(0).sort(function (a, b) { <add>romanSymbols.sortedDescByValue = romanSymbols.exceptionsFirst <add> .slice(0).sort(function (a, b) { <ide> return b.value - a.value; <ide> }); <ide> <ide> function findLargestFittingSymbol(number) { <del> for (var i = 0; i < sortedRomanSymbols.length; i++) { <del> if (sortedRomanSymbols[i].value <= number) { <del> return sortedRomanSymbols[i]; <add> for (var i = 0; i < romanSymbols.sortedDescByValue.length; i++) { <add> var current = romanSymbols.sortedDescByValue[i]; <add> if (current.value <= number) { <add> return current; <ide> } <ide> } <ide> } <ide> exports.fromRoman = function (roman) { <ide> var total = 0; <ide> <del> romanSymbols.forEach(function (symbol) { <add> romanSymbols.exceptionsFirst.forEach(function (symbol) { <ide> var regex = new RegExp(symbol.symbol, 'g'); <ide> var matches = roman.match(regex) || []; <ide> var count = matches.length;
Java
apache-2.0
0375e6e01b0b6412c2369a8d3e2a990f41a9edfa
0
zer0se7en/netty,artgon/netty,Spikhalskiy/netty,doom369/netty,artgon/netty,fenik17/netty,netty/netty,tbrooks8/netty,doom369/netty,netty/netty,artgon/netty,doom369/netty,fenik17/netty,doom369/netty,johnou/netty,doom369/netty,netty/netty,artgon/netty,netty/netty,zer0se7en/netty,Spikhalskiy/netty,zer0se7en/netty,andsel/netty,andsel/netty,ejona86/netty,NiteshKant/netty,tbrooks8/netty,tbrooks8/netty,johnou/netty,tbrooks8/netty,johnou/netty,ejona86/netty,NiteshKant/netty,Spikhalskiy/netty,zer0se7en/netty,NiteshKant/netty,ejona86/netty,netty/netty,Spikhalskiy/netty,fenik17/netty,andsel/netty,johnou/netty,NiteshKant/netty,fenik17/netty,fenik17/netty,NiteshKant/netty,Spikhalskiy/netty,ejona86/netty,zer0se7en/netty,artgon/netty,johnou/netty,andsel/netty,andsel/netty,tbrooks8/netty,ejona86/netty
/* * Copyright 2013 The Netty Project * * The Netty Project 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 io.netty.util; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicInteger; import static io.netty.util.internal.MathUtil.safeFindNextPositivePowerOfTwo; import static java.lang.Math.max; import static java.lang.Math.min; /** * Light-weight object pool based on a thread-local stack. * * @param <T> the type of the pooled object */ public abstract class Recycler<T> { private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class); @SuppressWarnings("rawtypes") private static final Handle NOOP_HANDLE = new Handle() { @Override public void recycle(Object object) { // NOOP } }; private static final AtomicInteger ID_GENERATOR = new AtomicInteger(Integer.MIN_VALUE); private static final int OWN_THREAD_ID = ID_GENERATOR.getAndIncrement(); private static final int DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD = 4 * 1024; // Use 4k instances as default. private static final int DEFAULT_MAX_CAPACITY_PER_THREAD; private static final int INITIAL_CAPACITY; private static final int MAX_SHARED_CAPACITY_FACTOR; private static final int MAX_DELAYED_QUEUES_PER_THREAD; private static final int LINK_CAPACITY; private static final int RATIO; private static final int DELAYED_QUEUE_RATIO; static { // In the future, we might have different maxCapacity for different object types. // e.g. io.netty.recycler.maxCapacity.writeTask // io.netty.recycler.maxCapacity.outboundBuffer int maxCapacityPerThread = SystemPropertyUtil.getInt("io.netty.recycler.maxCapacityPerThread", SystemPropertyUtil.getInt("io.netty.recycler.maxCapacity", DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD)); if (maxCapacityPerThread < 0) { maxCapacityPerThread = DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD; } DEFAULT_MAX_CAPACITY_PER_THREAD = maxCapacityPerThread; MAX_SHARED_CAPACITY_FACTOR = max(2, SystemPropertyUtil.getInt("io.netty.recycler.maxSharedCapacityFactor", 2)); MAX_DELAYED_QUEUES_PER_THREAD = max(0, SystemPropertyUtil.getInt("io.netty.recycler.maxDelayedQueuesPerThread", // We use the same value as default EventLoop number NettyRuntime.availableProcessors() * 2)); LINK_CAPACITY = safeFindNextPositivePowerOfTwo( max(SystemPropertyUtil.getInt("io.netty.recycler.linkCapacity", 16), 16)); // By default we allow one push to a Recycler for each 8th try on handles that were never recycled before. // This should help to slowly increase the capacity of the recycler while not be too sensitive to allocation // bursts. RATIO = max(0, SystemPropertyUtil.getInt("io.netty.recycler.ratio", 8)); DELAYED_QUEUE_RATIO = max(0, SystemPropertyUtil.getInt("io.netty.recycler.delayedQueue.ratio", RATIO)); if (logger.isDebugEnabled()) { if (DEFAULT_MAX_CAPACITY_PER_THREAD == 0) { logger.debug("-Dio.netty.recycler.maxCapacityPerThread: disabled"); logger.debug("-Dio.netty.recycler.maxSharedCapacityFactor: disabled"); logger.debug("-Dio.netty.recycler.linkCapacity: disabled"); logger.debug("-Dio.netty.recycler.ratio: disabled"); logger.debug("-Dio.netty.recycler.delayedQueue.ratio: disabled"); } else { logger.debug("-Dio.netty.recycler.maxCapacityPerThread: {}", DEFAULT_MAX_CAPACITY_PER_THREAD); logger.debug("-Dio.netty.recycler.maxSharedCapacityFactor: {}", MAX_SHARED_CAPACITY_FACTOR); logger.debug("-Dio.netty.recycler.linkCapacity: {}", LINK_CAPACITY); logger.debug("-Dio.netty.recycler.ratio: {}", RATIO); logger.debug("-Dio.netty.recycler.delayedQueue.ratio: {}", DELAYED_QUEUE_RATIO); } } INITIAL_CAPACITY = min(DEFAULT_MAX_CAPACITY_PER_THREAD, 256); } private final int maxCapacityPerThread; private final int maxSharedCapacityFactor; private final int interval; private final int maxDelayedQueuesPerThread; private final int delayedQueueInterval; private final FastThreadLocal<Stack<T>> threadLocal = new FastThreadLocal<Stack<T>>() { @Override protected Stack<T> initialValue() { return new Stack<T>(Recycler.this, Thread.currentThread(), maxCapacityPerThread, maxSharedCapacityFactor, interval, maxDelayedQueuesPerThread, delayedQueueInterval); } @Override protected void onRemoval(Stack<T> value) { // Let us remove the WeakOrderQueue from the WeakHashMap directly if its safe to remove some overhead if (value.threadRef.get() == Thread.currentThread()) { if (DELAYED_RECYCLED.isSet()) { DELAYED_RECYCLED.get().remove(value); } } } }; protected Recycler() { this(DEFAULT_MAX_CAPACITY_PER_THREAD); } protected Recycler(int maxCapacityPerThread) { this(maxCapacityPerThread, MAX_SHARED_CAPACITY_FACTOR); } protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor) { this(maxCapacityPerThread, maxSharedCapacityFactor, RATIO, MAX_DELAYED_QUEUES_PER_THREAD); } protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor, int ratio, int maxDelayedQueuesPerThread) { this(maxCapacityPerThread, maxSharedCapacityFactor, ratio, maxDelayedQueuesPerThread, DELAYED_QUEUE_RATIO); } protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor, int ratio, int maxDelayedQueuesPerThread, int delayedQueueRatio) { interval = max(0, ratio); delayedQueueInterval = max(0, delayedQueueRatio); if (maxCapacityPerThread <= 0) { this.maxCapacityPerThread = 0; this.maxSharedCapacityFactor = 1; this.maxDelayedQueuesPerThread = 0; } else { this.maxCapacityPerThread = maxCapacityPerThread; this.maxSharedCapacityFactor = max(1, maxSharedCapacityFactor); this.maxDelayedQueuesPerThread = max(0, maxDelayedQueuesPerThread); } } @SuppressWarnings("unchecked") public final T get() { if (maxCapacityPerThread == 0) { return newObject((Handle<T>) NOOP_HANDLE); } Stack<T> stack = threadLocal.get(); DefaultHandle<T> handle = stack.pop(); if (handle == null) { handle = stack.newHandle(); handle.value = newObject(handle); } return (T) handle.value; } /** * @deprecated use {@link Handle#recycle(Object)}. */ @Deprecated public final boolean recycle(T o, Handle<T> handle) { if (handle == NOOP_HANDLE) { return false; } DefaultHandle<T> h = (DefaultHandle<T>) handle; if (h.stack.parent != this) { return false; } h.recycle(o); return true; } final int threadLocalCapacity() { return threadLocal.get().elements.length; } final int threadLocalSize() { return threadLocal.get().size; } protected abstract T newObject(Handle<T> handle); public interface Handle<T> extends ObjectPool.Handle<T> { } private static final class DefaultHandle<T> implements Handle<T> { int lastRecycledId; int recycleId; boolean hasBeenRecycled; Stack<?> stack; Object value; DefaultHandle(Stack<?> stack) { this.stack = stack; } @Override public void recycle(Object object) { if (object != value) { throw new IllegalArgumentException("object does not belong to handle"); } Stack<?> stack = this.stack; if (lastRecycledId != recycleId || stack == null) { throw new IllegalStateException("recycled already"); } stack.push(this); } } private static final FastThreadLocal<Map<Stack<?>, WeakOrderQueue>> DELAYED_RECYCLED = new FastThreadLocal<Map<Stack<?>, WeakOrderQueue>>() { @Override protected Map<Stack<?>, WeakOrderQueue> initialValue() { return new WeakHashMap<Stack<?>, WeakOrderQueue>(); } }; // a queue that makes only moderate guarantees about visibility: items are seen in the correct order, // but we aren't absolutely guaranteed to ever see anything at all, thereby keeping the queue cheap to maintain private static final class WeakOrderQueue extends WeakReference<Thread> { static final WeakOrderQueue DUMMY = new WeakOrderQueue(); // Let Link extend AtomicInteger for intrinsics. The Link itself will be used as writerIndex. @SuppressWarnings("serial") static final class Link extends AtomicInteger { final DefaultHandle<?>[] elements = new DefaultHandle[LINK_CAPACITY]; int readIndex; Link next; } // Its important this does not hold any reference to either Stack or WeakOrderQueue. private static final class Head { private final AtomicInteger availableSharedCapacity; Link link; Head(AtomicInteger availableSharedCapacity) { this.availableSharedCapacity = availableSharedCapacity; } /** * Reclaim all used space and also unlink the nodes to prevent GC nepotism. */ void reclaimAllSpaceAndUnlink() { Link head = link; link = null; int reclaimSpace = 0; while (head != null) { reclaimSpace += LINK_CAPACITY; Link next = head.next; // Unlink to help GC and guard against GC nepotism. head.next = null; head = next; } if (reclaimSpace > 0) { reclaimSpace(reclaimSpace); } } private void reclaimSpace(int space) { availableSharedCapacity.addAndGet(space); } void relink(Link link) { reclaimSpace(LINK_CAPACITY); this.link = link; } /** * Creates a new {@link} and returns it if we can reserve enough space for it, otherwise it * returns {@code null}. */ Link newLink() { return reserveSpaceForLink(availableSharedCapacity) ? new Link() : null; } static boolean reserveSpaceForLink(AtomicInteger availableSharedCapacity) { for (;;) { int available = availableSharedCapacity.get(); if (available < LINK_CAPACITY) { return false; } if (availableSharedCapacity.compareAndSet(available, available - LINK_CAPACITY)) { return true; } } } } // chain of data items private final Head head; private Link tail; // pointer to another queue of delayed items for the same stack private WeakOrderQueue next; private final int id = ID_GENERATOR.getAndIncrement(); private final int interval; private int handleRecycleCount; private WeakOrderQueue() { super(null); head = new Head(null); interval = 0; } private WeakOrderQueue(Stack<?> stack, Thread thread) { super(thread); tail = new Link(); // Its important that we not store the Stack itself in the WeakOrderQueue as the Stack also is used in // the WeakHashMap as key. So just store the enclosed AtomicInteger which should allow to have the // Stack itself GCed. head = new Head(stack.availableSharedCapacity); head.link = tail; interval = stack.delayedQueueInterval; handleRecycleCount = interval; // Start at interval so the first one will be recycled. } static WeakOrderQueue newQueue(Stack<?> stack, Thread thread) { // We allocated a Link so reserve the space if (!Head.reserveSpaceForLink(stack.availableSharedCapacity)) { return null; } final WeakOrderQueue queue = new WeakOrderQueue(stack, thread); // Done outside of the constructor to ensure WeakOrderQueue.this does not escape the constructor and so // may be accessed while its still constructed. stack.setHead(queue); return queue; } WeakOrderQueue getNext() { return next; } void setNext(WeakOrderQueue next) { assert next != this; this.next = next; } void reclaimAllSpaceAndUnlink() { head.reclaimAllSpaceAndUnlink(); this.next = null; } void add(DefaultHandle<?> handle) { handle.lastRecycledId = id; // While we also enforce the recycling ratio when we transfer objects from the WeakOrderQueue to the Stack // we better should enforce it as well early. Missing to do so may let the WeakOrderQueue grow very fast // without control if (handleRecycleCount < interval) { handleRecycleCount++; // Drop the item to prevent recycling to aggressive. return; } handleRecycleCount = 0; Link tail = this.tail; int writeIndex; if ((writeIndex = tail.get()) == LINK_CAPACITY) { Link link = head.newLink(); if (link == null) { // Drop it. return; } // We allocate a Link so reserve the space this.tail = tail = tail.next = link; writeIndex = tail.get(); } tail.elements[writeIndex] = handle; handle.stack = null; // we lazy set to ensure that setting stack to null appears before we unnull it in the owning thread; // this also means we guarantee visibility of an element in the queue if we see the index updated tail.lazySet(writeIndex + 1); } boolean hasFinalData() { return tail.readIndex != tail.get(); } // transfer as many items as we can from this queue to the stack, returning true if any were transferred @SuppressWarnings("rawtypes") boolean transfer(Stack<?> dst) { Link head = this.head.link; if (head == null) { return false; } if (head.readIndex == LINK_CAPACITY) { if (head.next == null) { return false; } head = head.next; this.head.relink(head); } final int srcStart = head.readIndex; int srcEnd = head.get(); final int srcSize = srcEnd - srcStart; if (srcSize == 0) { return false; } final int dstSize = dst.size; final int expectedCapacity = dstSize + srcSize; if (expectedCapacity > dst.elements.length) { final int actualCapacity = dst.increaseCapacity(expectedCapacity); srcEnd = min(srcStart + actualCapacity - dstSize, srcEnd); } if (srcStart != srcEnd) { final DefaultHandle[] srcElems = head.elements; final DefaultHandle[] dstElems = dst.elements; int newDstSize = dstSize; for (int i = srcStart; i < srcEnd; i++) { DefaultHandle<?> element = srcElems[i]; if (element.recycleId == 0) { element.recycleId = element.lastRecycledId; } else if (element.recycleId != element.lastRecycledId) { throw new IllegalStateException("recycled already"); } srcElems[i] = null; if (dst.dropHandle(element)) { // Drop the object. continue; } element.stack = dst; dstElems[newDstSize ++] = element; } if (srcEnd == LINK_CAPACITY && head.next != null) { // Add capacity back as the Link is GCed. this.head.relink(head.next); } head.readIndex = srcEnd; if (dst.size == newDstSize) { return false; } dst.size = newDstSize; return true; } else { // The destination stack is full already. return false; } } } private static final class Stack<T> { // we keep a queue of per-thread queues, which is appended to once only, each time a new thread other // than the stack owner recycles: when we run out of items in our stack we iterate this collection // to scavenge those that can be reused. this permits us to incur minimal thread synchronisation whilst // still recycling all items. final Recycler<T> parent; // We store the Thread in a WeakReference as otherwise we may be the only ones that still hold a strong // Reference to the Thread itself after it died because DefaultHandle will hold a reference to the Stack. // // The biggest issue is if we do not use a WeakReference the Thread may not be able to be collected at all if // the user will store a reference to the DefaultHandle somewhere and never clear this reference (or not clear // it in a timely manner). final WeakReference<Thread> threadRef; final AtomicInteger availableSharedCapacity; private final int maxDelayedQueues; private final int maxCapacity; private final int interval; private final int delayedQueueInterval; DefaultHandle<?>[] elements; int size; private int handleRecycleCount; private WeakOrderQueue cursor, prev; private volatile WeakOrderQueue head; Stack(Recycler<T> parent, Thread thread, int maxCapacity, int maxSharedCapacityFactor, int interval, int maxDelayedQueues, int delayedQueueInterval) { this.parent = parent; threadRef = new WeakReference<Thread>(thread); this.maxCapacity = maxCapacity; availableSharedCapacity = new AtomicInteger(max(maxCapacity / maxSharedCapacityFactor, LINK_CAPACITY)); elements = new DefaultHandle[min(INITIAL_CAPACITY, maxCapacity)]; this.interval = interval; this.delayedQueueInterval = delayedQueueInterval; handleRecycleCount = interval; // Start at interval so the first one will be recycled. this.maxDelayedQueues = maxDelayedQueues; } // Marked as synchronized to ensure this is serialized. synchronized void setHead(WeakOrderQueue queue) { queue.setNext(head); head = queue; } int increaseCapacity(int expectedCapacity) { int newCapacity = elements.length; int maxCapacity = this.maxCapacity; do { newCapacity <<= 1; } while (newCapacity < expectedCapacity && newCapacity < maxCapacity); newCapacity = min(newCapacity, maxCapacity); if (newCapacity != elements.length) { elements = Arrays.copyOf(elements, newCapacity); } return newCapacity; } @SuppressWarnings({ "unchecked", "rawtypes" }) DefaultHandle<T> pop() { int size = this.size; if (size == 0) { if (!scavenge()) { return null; } size = this.size; if (size <= 0) { // double check, avoid races return null; } } size --; DefaultHandle ret = elements[size]; elements[size] = null; // As we already set the element[size] to null we also need to store the updated size before we do // any validation. Otherwise we may see a null value when later try to pop again without a new element // added before. this.size = size; if (ret.lastRecycledId != ret.recycleId) { throw new IllegalStateException("recycled multiple times"); } ret.recycleId = 0; ret.lastRecycledId = 0; return ret; } private boolean scavenge() { // continue an existing scavenge, if any if (scavengeSome()) { return true; } // reset our scavenge cursor prev = null; cursor = head; return false; } private boolean scavengeSome() { WeakOrderQueue prev; WeakOrderQueue cursor = this.cursor; if (cursor == null) { prev = null; cursor = head; if (cursor == null) { return false; } } else { prev = this.prev; } boolean success = false; do { if (cursor.transfer(this)) { success = true; break; } WeakOrderQueue next = cursor.getNext(); if (cursor.get() == null) { // If the thread associated with the queue is gone, unlink it, after // performing a volatile read to confirm there is no data left to collect. // We never unlink the first queue, as we don't want to synchronize on updating the head. if (cursor.hasFinalData()) { for (;;) { if (cursor.transfer(this)) { success = true; } else { break; } } } if (prev != null) { // Ensure we reclaim all space before dropping the WeakOrderQueue to be GC'ed. cursor.reclaimAllSpaceAndUnlink(); prev.setNext(next); } } else { prev = cursor; } cursor = next; } while (cursor != null && !success); this.prev = prev; this.cursor = cursor; return success; } void push(DefaultHandle<?> item) { Thread currentThread = Thread.currentThread(); if (threadRef.get() == currentThread) { // The current Thread is the thread that belongs to the Stack, we can try to push the object now. pushNow(item); } else { // The current Thread is not the one that belongs to the Stack // (or the Thread that belonged to the Stack was collected already), we need to signal that the push // happens later. pushLater(item, currentThread); } } private void pushNow(DefaultHandle<?> item) { if ((item.recycleId | item.lastRecycledId) != 0) { throw new IllegalStateException("recycled already"); } item.recycleId = item.lastRecycledId = OWN_THREAD_ID; int size = this.size; if (size >= maxCapacity || dropHandle(item)) { // Hit the maximum capacity or should drop - drop the possibly youngest object. return; } if (size == elements.length) { elements = Arrays.copyOf(elements, min(size << 1, maxCapacity)); } elements[size] = item; this.size = size + 1; } private void pushLater(DefaultHandle<?> item, Thread thread) { if (maxDelayedQueues == 0) { // We don't support recycling across threads and should just drop the item on the floor. return; } // we don't want to have a ref to the queue as the value in our weak map // so we null it out; to ensure there are no races with restoring it later // we impose a memory ordering here (no-op on x86) Map<Stack<?>, WeakOrderQueue> delayedRecycled = DELAYED_RECYCLED.get(); WeakOrderQueue queue = delayedRecycled.get(this); if (queue == null) { if (delayedRecycled.size() >= maxDelayedQueues) { // Add a dummy queue so we know we should drop the object delayedRecycled.put(this, WeakOrderQueue.DUMMY); return; } // Check if we already reached the maximum number of delayed queues and if we can allocate at all. if ((queue = newWeakOrderQueue(thread)) == null) { // drop object return; } delayedRecycled.put(this, queue); } else if (queue == WeakOrderQueue.DUMMY) { // drop object return; } queue.add(item); } /** * Allocate a new {@link WeakOrderQueue} or return {@code null} if not possible. */ private WeakOrderQueue newWeakOrderQueue(Thread thread) { return WeakOrderQueue.newQueue(this, thread); } boolean dropHandle(DefaultHandle<?> handle) { if (!handle.hasBeenRecycled) { if (handleRecycleCount < interval) { handleRecycleCount++; // Drop the object. return true; } handleRecycleCount = 0; handle.hasBeenRecycled = true; } return false; } DefaultHandle<T> newHandle() { return new DefaultHandle<T>(this); } } }
common/src/main/java/io/netty/util/Recycler.java
/* * Copyright 2013 The Netty Project * * The Netty Project 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 io.netty.util; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.ObjectPool; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicInteger; import static io.netty.util.internal.MathUtil.safeFindNextPositivePowerOfTwo; import static java.lang.Math.max; import static java.lang.Math.min; /** * Light-weight object pool based on a thread-local stack. * * @param <T> the type of the pooled object */ public abstract class Recycler<T> { private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class); @SuppressWarnings("rawtypes") private static final Handle NOOP_HANDLE = new Handle() { @Override public void recycle(Object object) { // NOOP } }; private static final AtomicInteger ID_GENERATOR = new AtomicInteger(Integer.MIN_VALUE); private static final int OWN_THREAD_ID = ID_GENERATOR.getAndIncrement(); private static final int DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD = 4 * 1024; // Use 4k instances as default. private static final int DEFAULT_MAX_CAPACITY_PER_THREAD; private static final int INITIAL_CAPACITY; private static final int MAX_SHARED_CAPACITY_FACTOR; private static final int MAX_DELAYED_QUEUES_PER_THREAD; private static final int LINK_CAPACITY; private static final int RATIO; private static final int DELAYED_QUEUE_RATIO; static { // In the future, we might have different maxCapacity for different object types. // e.g. io.netty.recycler.maxCapacity.writeTask // io.netty.recycler.maxCapacity.outboundBuffer int maxCapacityPerThread = SystemPropertyUtil.getInt("io.netty.recycler.maxCapacityPerThread", SystemPropertyUtil.getInt("io.netty.recycler.maxCapacity", DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD)); if (maxCapacityPerThread < 0) { maxCapacityPerThread = DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD; } DEFAULT_MAX_CAPACITY_PER_THREAD = maxCapacityPerThread; MAX_SHARED_CAPACITY_FACTOR = max(2, SystemPropertyUtil.getInt("io.netty.recycler.maxSharedCapacityFactor", 2)); MAX_DELAYED_QUEUES_PER_THREAD = max(0, SystemPropertyUtil.getInt("io.netty.recycler.maxDelayedQueuesPerThread", // We use the same value as default EventLoop number NettyRuntime.availableProcessors() * 2)); LINK_CAPACITY = safeFindNextPositivePowerOfTwo( max(SystemPropertyUtil.getInt("io.netty.recycler.linkCapacity", 16), 16)); // By default we allow one push to a Recycler for each 8th try on handles that were never recycled before. // This should help to slowly increase the capacity of the recycler while not be too sensitive to allocation // bursts. RATIO = max(0, SystemPropertyUtil.getInt("io.netty.recycler.ratio", 8)); DELAYED_QUEUE_RATIO = max(0, SystemPropertyUtil.getInt("io.netty.recycler.delayedQueue.ratio", RATIO)); if (logger.isDebugEnabled()) { if (DEFAULT_MAX_CAPACITY_PER_THREAD == 0) { logger.debug("-Dio.netty.recycler.maxCapacityPerThread: disabled"); logger.debug("-Dio.netty.recycler.maxSharedCapacityFactor: disabled"); logger.debug("-Dio.netty.recycler.linkCapacity: disabled"); logger.debug("-Dio.netty.recycler.ratio: disabled"); logger.debug("-Dio.netty.recycler.delayedQueue.ratio: disabled"); } else { logger.debug("-Dio.netty.recycler.maxCapacityPerThread: {}", DEFAULT_MAX_CAPACITY_PER_THREAD); logger.debug("-Dio.netty.recycler.maxSharedCapacityFactor: {}", MAX_SHARED_CAPACITY_FACTOR); logger.debug("-Dio.netty.recycler.linkCapacity: {}", LINK_CAPACITY); logger.debug("-Dio.netty.recycler.ratio: {}", RATIO); logger.debug("-Dio.netty.recycler.delayedQueue.ratio: {}", DELAYED_QUEUE_RATIO); } } INITIAL_CAPACITY = min(DEFAULT_MAX_CAPACITY_PER_THREAD, 256); } private final int maxCapacityPerThread; private final int maxSharedCapacityFactor; private final int interval; private final int maxDelayedQueuesPerThread; private final int delayedQueueInterval; private final FastThreadLocal<Stack<T>> threadLocal = new FastThreadLocal<Stack<T>>() { @Override protected Stack<T> initialValue() { return new Stack<T>(Recycler.this, Thread.currentThread(), maxCapacityPerThread, maxSharedCapacityFactor, interval, maxDelayedQueuesPerThread, delayedQueueInterval); } @Override protected void onRemoval(Stack<T> value) { // Let us remove the WeakOrderQueue from the WeakHashMap directly if its safe to remove some overhead if (value.threadRef.get() == Thread.currentThread()) { if (DELAYED_RECYCLED.isSet()) { DELAYED_RECYCLED.get().remove(value); } } } }; protected Recycler() { this(DEFAULT_MAX_CAPACITY_PER_THREAD); } protected Recycler(int maxCapacityPerThread) { this(maxCapacityPerThread, MAX_SHARED_CAPACITY_FACTOR); } protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor) { this(maxCapacityPerThread, maxSharedCapacityFactor, RATIO, MAX_DELAYED_QUEUES_PER_THREAD); } protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor, int ratio, int maxDelayedQueuesPerThread) { this(maxCapacityPerThread, maxSharedCapacityFactor, ratio, maxDelayedQueuesPerThread, DELAYED_QUEUE_RATIO); } protected Recycler(int maxCapacityPerThread, int maxSharedCapacityFactor, int ratio, int maxDelayedQueuesPerThread, int delayedQueueRatio) { interval = max(0, ratio); delayedQueueInterval = max(0, delayedQueueRatio); if (maxCapacityPerThread <= 0) { this.maxCapacityPerThread = 0; this.maxSharedCapacityFactor = 1; this.maxDelayedQueuesPerThread = 0; } else { this.maxCapacityPerThread = maxCapacityPerThread; this.maxSharedCapacityFactor = max(1, maxSharedCapacityFactor); this.maxDelayedQueuesPerThread = max(0, maxDelayedQueuesPerThread); } } @SuppressWarnings("unchecked") public final T get() { if (maxCapacityPerThread == 0) { return newObject((Handle<T>) NOOP_HANDLE); } Stack<T> stack = threadLocal.get(); DefaultHandle<T> handle = stack.pop(); if (handle == null) { handle = stack.newHandle(); handle.value = newObject(handle); } return (T) handle.value; } /** * @deprecated use {@link Handle#recycle(Object)}. */ @Deprecated public final boolean recycle(T o, Handle<T> handle) { if (handle == NOOP_HANDLE) { return false; } DefaultHandle<T> h = (DefaultHandle<T>) handle; if (h.stack.parent != this) { return false; } h.recycle(o); return true; } final int threadLocalCapacity() { return threadLocal.get().elements.length; } final int threadLocalSize() { return threadLocal.get().size; } protected abstract T newObject(Handle<T> handle); public interface Handle<T> extends ObjectPool.Handle<T> { } private static final class DefaultHandle<T> implements Handle<T> { int lastRecycledId; int recycleId; boolean hasBeenRecycled; Stack<?> stack; Object value; DefaultHandle(Stack<?> stack) { this.stack = stack; } @Override public void recycle(Object object) { if (object != value) { throw new IllegalArgumentException("object does not belong to handle"); } Stack<?> stack = this.stack; if (lastRecycledId != recycleId || stack == null) { throw new IllegalStateException("recycled already"); } stack.push(this); } } private static final FastThreadLocal<Map<Stack<?>, WeakOrderQueue>> DELAYED_RECYCLED = new FastThreadLocal<Map<Stack<?>, WeakOrderQueue>>() { @Override protected Map<Stack<?>, WeakOrderQueue> initialValue() { return new WeakHashMap<Stack<?>, WeakOrderQueue>(); } }; // a queue that makes only moderate guarantees about visibility: items are seen in the correct order, // but we aren't absolutely guaranteed to ever see anything at all, thereby keeping the queue cheap to maintain private static final class WeakOrderQueue extends WeakReference<Thread> { static final WeakOrderQueue DUMMY = new WeakOrderQueue(); // Let Link extend AtomicInteger for intrinsics. The Link itself will be used as writerIndex. @SuppressWarnings("serial") static final class Link extends AtomicInteger { final DefaultHandle<?>[] elements = new DefaultHandle[LINK_CAPACITY]; int readIndex; Link next; } // Its important this does not hold any reference to either Stack or WeakOrderQueue. private static final class Head { private final AtomicInteger availableSharedCapacity; Link link; Head(AtomicInteger availableSharedCapacity) { this.availableSharedCapacity = availableSharedCapacity; } /** * Reclaim all used space and also unlink the nodes to prevent GC nepotism. */ void reclaimAllSpaceAndUnlink() { Link head = link; link = null; int reclaimSpace = 0; while (head != null) { reclaimSpace += LINK_CAPACITY; Link next = head.next; // Unlink to help GC and guard against GC nepotism. head.next = null; head = next; } if (reclaimSpace > 0) { reclaimSpace(reclaimSpace); } } private void reclaimSpace(int space) { availableSharedCapacity.addAndGet(space); } void relink(Link link) { reclaimSpace(LINK_CAPACITY); this.link = link; } /** * Creates a new {@link} and returns it if we can reserve enough space for it, otherwise it * returns {@code null}. */ Link newLink() { return reserveSpaceForLink(availableSharedCapacity) ? new Link() : null; } static boolean reserveSpaceForLink(AtomicInteger availableSharedCapacity) { for (;;) { int available = availableSharedCapacity.get(); if (available < LINK_CAPACITY) { return false; } if (availableSharedCapacity.compareAndSet(available, available - LINK_CAPACITY)) { return true; } } } } // chain of data items private final Head head; private Link tail; // pointer to another queue of delayed items for the same stack private WeakOrderQueue next; private final int id = ID_GENERATOR.getAndIncrement(); private final int interval; private int handleRecycleCount; private WeakOrderQueue() { super(null); head = new Head(null); interval = 0; } private WeakOrderQueue(Stack<?> stack, Thread thread) { super(thread); tail = new Link(); // Its important that we not store the Stack itself in the WeakOrderQueue as the Stack also is used in // the WeakHashMap as key. So just store the enclosed AtomicInteger which should allow to have the // Stack itself GCed. head = new Head(stack.availableSharedCapacity); head.link = tail; interval = stack.delayedQueueInterval; handleRecycleCount = interval; // Start at interval so the first one will be recycled. } static WeakOrderQueue newQueue(Stack<?> stack, Thread thread) { // We allocated a Link so reserve the space if (!Head.reserveSpaceForLink(stack.availableSharedCapacity)) { return null; } final WeakOrderQueue queue = new WeakOrderQueue(stack, thread); // Done outside of the constructor to ensure WeakOrderQueue.this does not escape the constructor and so // may be accessed while its still constructed. stack.setHead(queue); return queue; } WeakOrderQueue getNext() { return next; } void setNext(WeakOrderQueue next) { assert next != this; this.next = next; } void reclaimAllSpaceAndUnlink() { head.reclaimAllSpaceAndUnlink(); this.next = null; } void add(DefaultHandle<?> handle) { handle.lastRecycledId = id; // While we also enforce the recycling ratio one we transfer objects from the WeakOrderQueue to the Stack // we better should enforce it as well early. Missing to do so may let the WeakOrderQueue grow very fast // without control if the Stack if (handleRecycleCount < interval) { handleRecycleCount++; // Drop the item to prevent recycling to aggressive. return; } handleRecycleCount = 0; Link tail = this.tail; int writeIndex; if ((writeIndex = tail.get()) == LINK_CAPACITY) { Link link = head.newLink(); if (link == null) { // Drop it. return; } // We allocate a Link so reserve the space this.tail = tail = tail.next = link; writeIndex = tail.get(); } tail.elements[writeIndex] = handle; handle.stack = null; // we lazy set to ensure that setting stack to null appears before we unnull it in the owning thread; // this also means we guarantee visibility of an element in the queue if we see the index updated tail.lazySet(writeIndex + 1); } boolean hasFinalData() { return tail.readIndex != tail.get(); } // transfer as many items as we can from this queue to the stack, returning true if any were transferred @SuppressWarnings("rawtypes") boolean transfer(Stack<?> dst) { Link head = this.head.link; if (head == null) { return false; } if (head.readIndex == LINK_CAPACITY) { if (head.next == null) { return false; } head = head.next; this.head.relink(head); } final int srcStart = head.readIndex; int srcEnd = head.get(); final int srcSize = srcEnd - srcStart; if (srcSize == 0) { return false; } final int dstSize = dst.size; final int expectedCapacity = dstSize + srcSize; if (expectedCapacity > dst.elements.length) { final int actualCapacity = dst.increaseCapacity(expectedCapacity); srcEnd = min(srcStart + actualCapacity - dstSize, srcEnd); } if (srcStart != srcEnd) { final DefaultHandle[] srcElems = head.elements; final DefaultHandle[] dstElems = dst.elements; int newDstSize = dstSize; for (int i = srcStart; i < srcEnd; i++) { DefaultHandle<?> element = srcElems[i]; if (element.recycleId == 0) { element.recycleId = element.lastRecycledId; } else if (element.recycleId != element.lastRecycledId) { throw new IllegalStateException("recycled already"); } srcElems[i] = null; if (dst.dropHandle(element)) { // Drop the object. continue; } element.stack = dst; dstElems[newDstSize ++] = element; } if (srcEnd == LINK_CAPACITY && head.next != null) { // Add capacity back as the Link is GCed. this.head.relink(head.next); } head.readIndex = srcEnd; if (dst.size == newDstSize) { return false; } dst.size = newDstSize; return true; } else { // The destination stack is full already. return false; } } } private static final class Stack<T> { // we keep a queue of per-thread queues, which is appended to once only, each time a new thread other // than the stack owner recycles: when we run out of items in our stack we iterate this collection // to scavenge those that can be reused. this permits us to incur minimal thread synchronisation whilst // still recycling all items. final Recycler<T> parent; // We store the Thread in a WeakReference as otherwise we may be the only ones that still hold a strong // Reference to the Thread itself after it died because DefaultHandle will hold a reference to the Stack. // // The biggest issue is if we do not use a WeakReference the Thread may not be able to be collected at all if // the user will store a reference to the DefaultHandle somewhere and never clear this reference (or not clear // it in a timely manner). final WeakReference<Thread> threadRef; final AtomicInteger availableSharedCapacity; private final int maxDelayedQueues; private final int maxCapacity; private final int interval; private final int delayedQueueInterval; DefaultHandle<?>[] elements; int size; private int handleRecycleCount; private WeakOrderQueue cursor, prev; private volatile WeakOrderQueue head; Stack(Recycler<T> parent, Thread thread, int maxCapacity, int maxSharedCapacityFactor, int interval, int maxDelayedQueues, int delayedQueueInterval) { this.parent = parent; threadRef = new WeakReference<Thread>(thread); this.maxCapacity = maxCapacity; availableSharedCapacity = new AtomicInteger(max(maxCapacity / maxSharedCapacityFactor, LINK_CAPACITY)); elements = new DefaultHandle[min(INITIAL_CAPACITY, maxCapacity)]; this.interval = interval; this.delayedQueueInterval = delayedQueueInterval; handleRecycleCount = interval; // Start at interval so the first one will be recycled. this.maxDelayedQueues = maxDelayedQueues; } // Marked as synchronized to ensure this is serialized. synchronized void setHead(WeakOrderQueue queue) { queue.setNext(head); head = queue; } int increaseCapacity(int expectedCapacity) { int newCapacity = elements.length; int maxCapacity = this.maxCapacity; do { newCapacity <<= 1; } while (newCapacity < expectedCapacity && newCapacity < maxCapacity); newCapacity = min(newCapacity, maxCapacity); if (newCapacity != elements.length) { elements = Arrays.copyOf(elements, newCapacity); } return newCapacity; } @SuppressWarnings({ "unchecked", "rawtypes" }) DefaultHandle<T> pop() { int size = this.size; if (size == 0) { if (!scavenge()) { return null; } size = this.size; if (size <= 0) { // double check, avoid races return null; } } size --; DefaultHandle ret = elements[size]; elements[size] = null; // As we already set the element[size] to null we also need to store the updated size before we do // any validation. Otherwise we may see a null value when later try to pop again without a new element // added before. this.size = size; if (ret.lastRecycledId != ret.recycleId) { throw new IllegalStateException("recycled multiple times"); } ret.recycleId = 0; ret.lastRecycledId = 0; return ret; } private boolean scavenge() { // continue an existing scavenge, if any if (scavengeSome()) { return true; } // reset our scavenge cursor prev = null; cursor = head; return false; } private boolean scavengeSome() { WeakOrderQueue prev; WeakOrderQueue cursor = this.cursor; if (cursor == null) { prev = null; cursor = head; if (cursor == null) { return false; } } else { prev = this.prev; } boolean success = false; do { if (cursor.transfer(this)) { success = true; break; } WeakOrderQueue next = cursor.getNext(); if (cursor.get() == null) { // If the thread associated with the queue is gone, unlink it, after // performing a volatile read to confirm there is no data left to collect. // We never unlink the first queue, as we don't want to synchronize on updating the head. if (cursor.hasFinalData()) { for (;;) { if (cursor.transfer(this)) { success = true; } else { break; } } } if (prev != null) { // Ensure we reclaim all space before dropping the WeakOrderQueue to be GC'ed. cursor.reclaimAllSpaceAndUnlink(); prev.setNext(next); } } else { prev = cursor; } cursor = next; } while (cursor != null && !success); this.prev = prev; this.cursor = cursor; return success; } void push(DefaultHandle<?> item) { Thread currentThread = Thread.currentThread(); if (threadRef.get() == currentThread) { // The current Thread is the thread that belongs to the Stack, we can try to push the object now. pushNow(item); } else { // The current Thread is not the one that belongs to the Stack // (or the Thread that belonged to the Stack was collected already), we need to signal that the push // happens later. pushLater(item, currentThread); } } private void pushNow(DefaultHandle<?> item) { if ((item.recycleId | item.lastRecycledId) != 0) { throw new IllegalStateException("recycled already"); } item.recycleId = item.lastRecycledId = OWN_THREAD_ID; int size = this.size; if (size >= maxCapacity || dropHandle(item)) { // Hit the maximum capacity or should drop - drop the possibly youngest object. return; } if (size == elements.length) { elements = Arrays.copyOf(elements, min(size << 1, maxCapacity)); } elements[size] = item; this.size = size + 1; } private void pushLater(DefaultHandle<?> item, Thread thread) { if (maxDelayedQueues == 0) { // We don't support recycling across threads and should just drop the item on the floor. return; } // we don't want to have a ref to the queue as the value in our weak map // so we null it out; to ensure there are no races with restoring it later // we impose a memory ordering here (no-op on x86) Map<Stack<?>, WeakOrderQueue> delayedRecycled = DELAYED_RECYCLED.get(); WeakOrderQueue queue = delayedRecycled.get(this); if (queue == null) { if (delayedRecycled.size() >= maxDelayedQueues) { // Add a dummy queue so we know we should drop the object delayedRecycled.put(this, WeakOrderQueue.DUMMY); return; } // Check if we already reached the maximum number of delayed queues and if we can allocate at all. if ((queue = newWeakOrderQueue(thread)) == null) { // drop object return; } delayedRecycled.put(this, queue); } else if (queue == WeakOrderQueue.DUMMY) { // drop object return; } queue.add(item); } /** * Allocate a new {@link WeakOrderQueue} or return {@code null} if not possible. */ private WeakOrderQueue newWeakOrderQueue(Thread thread) { return WeakOrderQueue.newQueue(this, thread); } boolean dropHandle(DefaultHandle<?> handle) { if (!handle.hasBeenRecycled) { if (handleRecycleCount < interval) { handleRecycleCount++; // Drop the object. return true; } handleRecycleCount = 0; handle.hasBeenRecycled = true; } return false; } DefaultHandle<T> newHandle() { return new DefaultHandle<T>(this); } } }
Fix very tiny comment error in Recycler (#10309) Motivation: Fix very tiny comment error in Recycler Modifications: Fix very tiny comment error in Recycler Result: Correctly comment about drop in WeakOrderQueue#add
common/src/main/java/io/netty/util/Recycler.java
Fix very tiny comment error in Recycler (#10309)
<ide><path>ommon/src/main/java/io/netty/util/Recycler.java <ide> void add(DefaultHandle<?> handle) { <ide> handle.lastRecycledId = id; <ide> <del> // While we also enforce the recycling ratio one we transfer objects from the WeakOrderQueue to the Stack <add> // While we also enforce the recycling ratio when we transfer objects from the WeakOrderQueue to the Stack <ide> // we better should enforce it as well early. Missing to do so may let the WeakOrderQueue grow very fast <del> // without control if the Stack <add> // without control <ide> if (handleRecycleCount < interval) { <ide> handleRecycleCount++; <ide> // Drop the item to prevent recycling to aggressive.
Java
apache-2.0
41a1e4a13ef7052776837465b4142bb47c38d60c
0
Shvid/protostuff,dyu/protostuff,svn2github/protostuff,Shvid/protostuff,dyu/protostuff,tsheasha/protostuff,svn2github/protostuff,protostuff/protostuff,tsheasha/protostuff,myxyz/protostuff,protostuff/protostuff,myxyz/protostuff
//======================================================================== //Copyright 2007-2009 David Yu [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. //======================================================================== // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.dyuproject.protostuff.me; /** * Thrown when attempting to build a protocol message that is missing required * fields. This is a {@code RuntimeException} because it normally represents * a programming error: it happens when some code which constructs a message * fails to set all the fields. * * @author [email protected] Kenton Varda * @author David Yu */ public final class UninitializedMessageException extends RuntimeException { public final Object targetMessage; public final Schema targetSchema; public UninitializedMessageException(Message targetMessage) { this(targetMessage, targetMessage.cachedSchema()); } public UninitializedMessageException(Object targetMessage, Schema targetSchema) { this.targetMessage = targetMessage; this.targetSchema = targetSchema; } public UninitializedMessageException(String msg, Message targetMessage) { this(msg, targetMessage, targetMessage.cachedSchema()); } public UninitializedMessageException(String msg, Object targetMessage, Schema targetSchema) { super(msg); this.targetMessage = targetMessage; this.targetSchema = targetSchema; } //@SuppressWarnings("unchecked") public Object getTargetMessage() { return targetMessage; } //@SuppressWarnings("unchecked") public Schema getTargetSchema() { return targetSchema; } /*@public UninitializedMessageException(final MessageLite message) { super("Message was missing required fields. (Lite runtime could not " + "determine which fields were missing)."); missingFields = null; } public UninitializedMessageException(final List<String> missingFields) { super(buildDescription(missingFields)); this.missingFields = missingFields; } private final List<String> missingFields; /** * Get a list of human-readable names of required fields missing from this * message. Each name is a full path to a field, e.g. "foo.bar[5].baz". * Returns null if the lite runtime was used, since it lacks the ability to * find missing fields. *@ public List<String> getMissingFields() { return Collections.unmodifiableList(missingFields); } /** * Converts this exception to an {@link InvalidProtocolBufferException}. * When a parsed message is missing required fields, this should be thrown * instead of {@code UninitializedMessageException}. *@ public InvalidProtocolBufferException asInvalidProtocolBufferException() { return new InvalidProtocolBufferException(getMessage()); } /** Construct the description string for this exception. *@ private static String buildDescription(final List<String> missingFields) { final StringBuilder description = new StringBuilder("Message missing required fields: "); boolean first = true; for (final String field : missingFields) { if (first) { first = false; } else { description.append(", "); } description.append(field); } return description.toString(); }*/ }
protostuff-me/src/main/java/com/dyuproject/protostuff/me/UninitializedMessageException.java
//======================================================================== //Copyright 2007-2009 David Yu [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. //======================================================================== // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.dyuproject.protostuff.me; /** * Thrown when attempting to build a protocol message that is missing required * fields. This is a {@code RuntimeException} because it normally represents * a programming error: it happens when some code which constructs a message * fails to set all the fields. * * @author [email protected] Kenton Varda * @author David Yu */ public final class UninitializedMessageException extends RuntimeException { public final Object targetMessage; public final Schema targetSchema; public UninitializedMessageException(Message targetMessage) { this(targetMessage, targetMessage.cachedSchema()); } public UninitializedMessageException(Object targetMessage, Schema targetSchema) { this.targetMessage = targetMessage; this.targetSchema = targetSchema; } //@SuppressWarnings("unchecked") public Object getTargetMessage() { return targetMessage; } //@SuppressWarnings("unchecked") public Schema getTargetSchema() { return targetSchema; } /*@public UninitializedMessageException(final MessageLite message) { super("Message was missing required fields. (Lite runtime could not " + "determine which fields were missing)."); missingFields = null; } public UninitializedMessageException(final List<String> missingFields) { super(buildDescription(missingFields)); this.missingFields = missingFields; } private final List<String> missingFields; /** * Get a list of human-readable names of required fields missing from this * message. Each name is a full path to a field, e.g. "foo.bar[5].baz". * Returns null if the lite runtime was used, since it lacks the ability to * find missing fields. *@ public List<String> getMissingFields() { return Collections.unmodifiableList(missingFields); } /** * Converts this exception to an {@link InvalidProtocolBufferException}. * When a parsed message is missing required fields, this should be thrown * instead of {@code UninitializedMessageException}. *@ public InvalidProtocolBufferException asInvalidProtocolBufferException() { return new InvalidProtocolBufferException(getMessage()); } /** Construct the description string for this exception. *@ private static String buildDescription(final List<String> missingFields) { final StringBuilder description = new StringBuilder("Message missing required fields: "); boolean first = true; for (final String field : missingFields) { if (first) { first = false; } else { description.append(", "); } description.append(field); } return description.toString(); }*/ }
overload constructor for err msg git-svn-id: 3d5cc44e79dd7516812cdf5c8b2c4439073f5b70@1555 3b38d51a-9144-11de-8ad7-8b2c2f1e2016
protostuff-me/src/main/java/com/dyuproject/protostuff/me/UninitializedMessageException.java
overload constructor for err msg
<ide><path>rotostuff-me/src/main/java/com/dyuproject/protostuff/me/UninitializedMessageException.java <ide> this.targetSchema = targetSchema; <ide> } <ide> <add> public UninitializedMessageException(String msg, Message targetMessage) { <add> this(msg, targetMessage, targetMessage.cachedSchema()); <add> } <add> <add> public UninitializedMessageException(String msg, Object targetMessage, <add> Schema targetSchema) { <add> super(msg); <add> this.targetMessage = targetMessage; <add> this.targetSchema = targetSchema; <add> } <add> <ide> //@SuppressWarnings("unchecked") <ide> public Object getTargetMessage() { <ide> return targetMessage;
Java
apache-2.0
efb7bccc10495dbb980bcabe75fabf9658382f6c
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.node.admin.nodeagent; import com.yahoo.vespa.hosted.dockerapi.Container; import com.yahoo.vespa.hosted.dockerapi.ContainerName; import com.yahoo.vespa.hosted.dockerapi.Docker; import com.yahoo.vespa.hosted.dockerapi.DockerExecTimeoutException; import com.yahoo.vespa.hosted.dockerapi.DockerImage; import com.yahoo.vespa.hosted.dockerapi.metrics.Dimensions; import com.yahoo.vespa.hosted.dockerapi.metrics.MetricReceiverWrapper; import com.yahoo.vespa.hosted.node.admin.ContainerNodeSpec; import com.yahoo.vespa.hosted.node.admin.docker.DockerOperations; import com.yahoo.vespa.hosted.node.admin.maintenance.StorageMaintainer; import com.yahoo.vespa.hosted.node.admin.maintenance.acl.AclMaintainer; import com.yahoo.vespa.hosted.node.admin.noderepository.NodeRepository; import com.yahoo.vespa.hosted.node.admin.orchestrator.Orchestrator; import com.yahoo.vespa.hosted.node.admin.orchestrator.OrchestratorException; import com.yahoo.vespa.hosted.node.admin.util.Environment; import com.yahoo.vespa.hosted.node.admin.util.PrefixLogger; import com.yahoo.vespa.hosted.provision.Node; import java.text.SimpleDateFormat; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl.ContainerState.ABSENT; import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl.ContainerState.RUNNING; import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl.ContainerState.RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; /** * @author dybis * @author bakksjo */ public class NodeAgentImpl implements NodeAgent { private final AtomicBoolean terminated = new AtomicBoolean(false); private boolean isFrozen = true; private boolean wantFrozen = false; private boolean workToDoNow = true; private final Object monitor = new Object(); private final PrefixLogger logger; private DockerImage imageBeingDownloaded = null; private final String hostname; private final ContainerName containerName; private final NodeRepository nodeRepository; private final Orchestrator orchestrator; private final DockerOperations dockerOperations; private final Optional<StorageMaintainer> storageMaintainer; private final MetricReceiverWrapper metricReceiver; private final Environment environment; private final Clock clock; private final Optional<AclMaintainer> aclMaintainer; private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private final LinkedList<String> debugMessages = new LinkedList<>(); private long delaysBetweenEachConvergeMillis = 30_000; private int numberOfUnhandledException = 0; private Instant lastConverge; private Thread loopThread; enum ContainerState { ABSENT, RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN, RUNNING } private ContainerState containerState = ABSENT; // The attributes of the last successful node repo attribute update for this node. Used to avoid redundant calls. private NodeAttributes lastAttributesSet = null; private ContainerNodeSpec lastNodeSpec = null; private CpuUsageReporter lastCpuMetric; public NodeAgentImpl( final String hostName, final NodeRepository nodeRepository, final Orchestrator orchestrator, final DockerOperations dockerOperations, final Optional<StorageMaintainer> storageMaintainer, final MetricReceiverWrapper metricReceiver, final Environment environment, final Clock clock, final Optional<AclMaintainer> aclMaintainer) { this.nodeRepository = nodeRepository; this.orchestrator = orchestrator; this.hostname = hostName; this.containerName = ContainerName.fromHostname(hostName); this.dockerOperations = dockerOperations; this.storageMaintainer = storageMaintainer; this.logger = PrefixLogger.getNodeAgentLogger(NodeAgentImpl.class, containerName); this.metricReceiver = metricReceiver; this.environment = environment; this.clock = clock; this.aclMaintainer = aclMaintainer; this.lastConverge = clock.instant(); // If the container is already running, initialize vespaVersion and lastCpuMetric lastCpuMetric = new CpuUsageReporter(clock.instant()); dockerOperations.getContainer(containerName) .ifPresent(container -> { if (container.state.isRunning()) { lastCpuMetric = new CpuUsageReporter(container.created); } containerState = RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; logger.info("Container is already running, setting containerState to " + containerState); }); } @Override public boolean setFrozen(boolean frozen) { synchronized (monitor) { if (wantFrozen != frozen) { wantFrozen = frozen; addDebugMessage(wantFrozen ? "Freezing" : "Unfreezing"); signalWorkToBeDone(); } return isFrozen == frozen; } } private void addDebugMessage(String message) { synchronized (debugMessages) { while (debugMessages.size() > 1000) { debugMessages.pop(); } logger.debug(message); debugMessages.add("[" + sdf.format(new Date()) + "] " + message); } } @Override public Map<String, Object> debugInfo() { Map<String, Object> debug = new LinkedHashMap<>(); debug.put("Hostname", hostname); debug.put("isFrozen", isFrozen); debug.put("wantFrozen", wantFrozen); debug.put("terminated", terminated); debug.put("workToDoNow", workToDoNow); synchronized (debugMessages) { debug.put("History", new LinkedList<>(debugMessages)); } debug.put("Node repo state", lastNodeSpec.nodeState.name()); return debug; } @Override public void start(int intervalMillis) { addDebugMessage("Starting with interval " + intervalMillis + "ms"); delaysBetweenEachConvergeMillis = intervalMillis; if (loopThread != null) { throw new RuntimeException("Can not restart a node agent."); } loopThread = new Thread(() -> { while (!terminated.get()) tick(); }); loopThread.setName("tick-" + hostname); loopThread.start(); } @Override public void stop() { addDebugMessage("Stopping"); if (!terminated.compareAndSet(false, true)) { throw new RuntimeException("Can not re-stop a node agent."); } signalWorkToBeDone(); try { loopThread.join(10000); if (loopThread.isAlive()) { logger.error("Could not stop host thread " + hostname); } } catch (InterruptedException e1) { logger.error("Interrupted; Could not stop host thread " + hostname); } } private void runLocalResumeScriptIfNeeded(final ContainerNodeSpec nodeSpec) { if (containerState != RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN) { return; } addDebugMessage("Starting optional node program resume command"); dockerOperations.resumeNode(containerName); containerState = RUNNING; logger.info("Resume command successfully executed, new containerState is " + containerState); } private void updateNodeRepoAndMarkNodeAsReady(ContainerNodeSpec nodeSpec) { publishStateToNodeRepoIfChanged( // Clear current Docker image and vespa version, as nothing is running on this node new NodeAttributes() .withRestartGeneration(nodeSpec.wantedRestartGeneration.orElse(null)) .withRebootGeneration(nodeSpec.wantedRebootGeneration.orElse(0L)) .withDockerImage(new DockerImage("")) .withVespaVersion("")); nodeRepository.markNodeAvailableForNewAllocation(nodeSpec.hostname); } private void updateNodeRepoWithCurrentAttributes(final ContainerNodeSpec nodeSpec) { final NodeAttributes nodeAttributes = new NodeAttributes() .withRestartGeneration(nodeSpec.wantedRestartGeneration.orElse(null)) // update reboot gen with wanted gen if set, we ignore reboot for Docker nodes but // want the two to be equal in node repo .withRebootGeneration(nodeSpec.wantedRebootGeneration.orElse(0L)) .withDockerImage(nodeSpec.wantedDockerImage.orElse(new DockerImage(""))) .withVespaVersion(nodeSpec.wantedVespaVersion.orElse("")); publishStateToNodeRepoIfChanged(nodeAttributes); } private void publishStateToNodeRepoIfChanged(NodeAttributes currentAttributes) { // TODO: We should only update if the new current values do not match the node repo's current values if (!currentAttributes.equals(lastAttributesSet)) { logger.info("Publishing new set of attributes to node repo: " + lastAttributesSet + " -> " + currentAttributes); addDebugMessage("Publishing new set of attributes to node repo: {" + lastAttributesSet + "} -> {" + currentAttributes + "}"); nodeRepository.updateNodeAttributes(hostname, currentAttributes); lastAttributesSet = currentAttributes; } } private void startContainer(ContainerNodeSpec nodeSpec) { aclMaintainer.ifPresent(AclMaintainer::run); dockerOperations.startContainer(containerName, nodeSpec); lastCpuMetric = new CpuUsageReporter(clock.instant()); writeConfigs(nodeSpec); addDebugMessage("startContainerIfNeeded: containerState " + containerState + " -> " + RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN); containerState = RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; logger.info("Container successfully started, new containerState is " + containerState); } private Optional<Container> removeContainerIfNeededUpdateContainerState(ContainerNodeSpec nodeSpec, Optional<Container> existingContainer) { return existingContainer .flatMap(container -> removeContainerIfNeeded(nodeSpec, container)) .map(container -> { shouldRestartServices(nodeSpec).ifPresent(restartReason -> { logger.info("Will restart services for container " + container + ": " + restartReason); restartServices(nodeSpec, container); }); return container; }); } private Optional<String> shouldRestartServices(ContainerNodeSpec nodeSpec) { if (!nodeSpec.wantedRestartGeneration.isPresent()) return Optional.empty(); if (!nodeSpec.currentRestartGeneration.isPresent() || nodeSpec.currentRestartGeneration.get() < nodeSpec.wantedRestartGeneration.get()) { return Optional.of("Restart requested - wanted restart generation has been bumped: " + nodeSpec.currentRestartGeneration.get() + " -> " + nodeSpec.wantedRestartGeneration.get()); } return Optional.empty(); } private void restartServices(ContainerNodeSpec nodeSpec, Container existingContainer) { if (existingContainer.state.isRunning() && nodeSpec.nodeState == Node.State.active) { ContainerName containerName = existingContainer.name; logger.info("Restarting services for " + containerName); // Since we are restarting the services we need to suspend the node. orchestratorSuspendNode(); dockerOperations.restartVespaOnNode(containerName); } } @Override public void stopServices() { logger.info("Stopping services for " + containerName); dockerOperations.trySuspendNode(containerName); dockerOperations.stopServicesOnNode(containerName); } private Optional<String> shouldRemoveContainer(ContainerNodeSpec nodeSpec, Container existingContainer) { final Node.State nodeState = nodeSpec.nodeState; if (nodeState == Node.State.dirty || nodeState == Node.State.provisioned) { return Optional.of("Node in state " + nodeState + ", container should no longer be running"); } if (nodeSpec.wantedDockerImage.isPresent() && !nodeSpec.wantedDockerImage.get().equals(existingContainer.image)) { return Optional.of("The node is supposed to run a new Docker image: " + existingContainer + " -> " + nodeSpec.wantedDockerImage.get()); } if (!existingContainer.state.isRunning()) { return Optional.of("Container no longer running"); } return Optional.empty(); } private Optional<Container> removeContainerIfNeeded(ContainerNodeSpec nodeSpec, Container existingContainer) { Optional<String> removeReason = shouldRemoveContainer(nodeSpec, existingContainer); if (removeReason.isPresent()) { logger.info("Will remove container " + existingContainer + ": " + removeReason.get()); if (existingContainer.state.isRunning()) { if (nodeSpec.nodeState == Node.State.active) { orchestratorSuspendNode(); } try { stopServices(); } catch (Exception e) { logger.info("Failed stopping services, ignoring", e); } } dockerOperations.removeContainer(existingContainer); metricReceiver.unsetMetricsForContainer(hostname); containerState = ABSENT; logger.info("Container successfully removed, new containerState is " + containerState); return Optional.empty(); } return Optional.of(existingContainer); } private void scheduleDownLoadIfNeeded(ContainerNodeSpec nodeSpec) { if (nodeSpec.currentDockerImage.equals(nodeSpec.wantedDockerImage)) return; if (dockerOperations.shouldScheduleDownloadOfImage(nodeSpec.wantedDockerImage.get())) { if (nodeSpec.wantedDockerImage.get().equals(imageBeingDownloaded)) { // Downloading already scheduled, but not done. return; } imageBeingDownloaded = nodeSpec.wantedDockerImage.get(); // Create a signalWorkToBeDone when download is finished. dockerOperations.scheduleDownloadOfImage(containerName, imageBeingDownloaded, this::signalWorkToBeDone); } else if (imageBeingDownloaded != null) { // Image was downloading, but now it's ready imageBeingDownloaded = null; } } private void signalWorkToBeDone() { synchronized (monitor) { if (!workToDoNow) { workToDoNow = true; addDebugMessage("Signaling work to be done"); monitor.notifyAll(); } } } void tick() { boolean isFrozenCopy; synchronized (monitor) { while (!workToDoNow) { long remainder = delaysBetweenEachConvergeMillis - Duration.between(lastConverge, clock.instant()).toMillis(); if (remainder > 0) { try { monitor.wait(remainder); } catch (InterruptedException e) { logger.error("Interrupted, but ignoring this: " + hostname); } } else break; } lastConverge = clock.instant(); workToDoNow = false; if (isFrozen != wantFrozen) { isFrozen = wantFrozen; logger.info("Updated NodeAgent's frozen state, new value: isFrozen: " + isFrozen); } isFrozenCopy = isFrozen; } if (isFrozenCopy) { addDebugMessage("tick: isFrozen"); } else { try { converge(); } catch (OrchestratorException e) { logger.info(e.getMessage()); addDebugMessage(e.getMessage()); } catch (Exception e) { numberOfUnhandledException++; logger.error("Unhandled exception, ignoring.", e); addDebugMessage(e.getMessage()); } catch (Throwable t) { logger.error("Unhandled throwable, taking down system.", t); System.exit(234); } } } // Public for testing void converge() { final ContainerNodeSpec nodeSpec = nodeRepository.getContainerNodeSpec(hostname) .orElseThrow(() -> new IllegalStateException(String.format("Node '%s' missing from node repository.", hostname))); Optional<Container> container = getContainer(); if (!nodeSpec.equals(lastNodeSpec)) { addDebugMessage("Loading new node spec: " + nodeSpec.toString()); lastNodeSpec = nodeSpec; // Every time the node spec changes, we should clear the metrics for this container as the dimensions // will change and we will be reporting duplicate metrics. // TODO: Should be retried if writing fails metricReceiver.unsetMetricsForContainer(hostname); if (container.isPresent()) { writeConfigs(nodeSpec); } } switch (nodeSpec.nodeState) { case ready: case reserved: case parked: case failed: removeContainerIfNeededUpdateContainerState(nodeSpec, container); updateNodeRepoWithCurrentAttributes(nodeSpec); break; case active: storageMaintainer.ifPresent(maintainer -> { maintainer.removeOldFilesFromNode(containerName); maintainer.handleCoreDumpsForContainer(containerName, nodeSpec, environment); }); scheduleDownLoadIfNeeded(nodeSpec); if (isDownloadingImage()) { addDebugMessage("Waiting for image to download " + imageBeingDownloaded.asString()); return; } container = removeContainerIfNeededUpdateContainerState(nodeSpec, container); if (! container.isPresent()) { startContainer(nodeSpec); } runLocalResumeScriptIfNeeded(nodeSpec); // Because it's more important to stop a bad release from rolling out in prod, // we put the resume call last. So if we fail after updating the node repo attributes // but before resume, the app may go through the tenant pipeline but will halt in prod. // // Note that this problem exists only because there are 2 different mechanisms // that should really be parts of a single mechanism: // - The content of node repo is used to determine whether a new Vespa+application // has been successfully rolled out. // - Slobrok and internal orchestrator state is used to determine whether // to allow upgrade (suspend). updateNodeRepoWithCurrentAttributes(nodeSpec); logger.info("Call resume against Orchestrator"); orchestrator.resume(hostname); break; case inactive: storageMaintainer.ifPresent(maintainer -> maintainer.removeOldFilesFromNode(containerName)); removeContainerIfNeededUpdateContainerState(nodeSpec, container); updateNodeRepoWithCurrentAttributes(nodeSpec); break; case provisioned: nodeRepository.markAsDirty(hostname); break; case dirty: storageMaintainer.ifPresent(maintainer -> maintainer.removeOldFilesFromNode(containerName)); removeContainerIfNeededUpdateContainerState(nodeSpec, container); logger.info("State is " + nodeSpec.nodeState + ", will delete application storage and mark node as ready"); storageMaintainer.ifPresent(maintainer -> maintainer.archiveNodeData(containerName)); updateNodeRepoAndMarkNodeAsReady(nodeSpec); break; default: throw new RuntimeException("UNKNOWN STATE " + nodeSpec.nodeState.name()); } } @SuppressWarnings("unchecked") public void updateContainerNodeMetrics(int numAllocatedContainersOnHost) { final ContainerNodeSpec nodeSpec = lastNodeSpec; if (nodeSpec == null) return; Dimensions.Builder dimensionsBuilder = new Dimensions.Builder() .add("host", hostname) .add("role", "tenants") .add("flavor", nodeSpec.nodeFlavor) .add("state", nodeSpec.nodeState.toString()) .add("zone", environment.getZone()) .add("parentHostname", environment.getParentHostHostname()); nodeSpec.vespaVersion.ifPresent(version -> dimensionsBuilder.add("vespaVersion", version)); nodeSpec.owner.ifPresent(owner -> dimensionsBuilder .add("tenantName", owner.tenant) .add("applicationName", owner.application) .add("instanceName", owner.instance) .add("applicationId", owner.tenant + "." + owner.application + "." + owner.instance) .add("app", owner.application + "." + owner.instance)); nodeSpec.membership.ifPresent(membership -> dimensionsBuilder .add("clustertype", membership.clusterType) .add("clusterid", membership.clusterId)); Dimensions dimensions = dimensionsBuilder.build(); metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_NODE, dimensions, "alive").sample(1); // TODO: REMOVE metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.alive").sample(1); // The remaining metrics require container to exists and be running if (containerState == ABSENT) return; Optional<Docker.ContainerStats> containerStats = dockerOperations.getContainerStats(containerName); if (!containerStats.isPresent()) return; Docker.ContainerStats stats = containerStats.get(); final String APP = MetricReceiverWrapper.APPLICATION_NODE; final long bytesInGB = 1 << 30; final long cpuContainerTotalTime = ((Number) ((Map) stats.getCpuStats().get("cpu_usage")).get("total_usage")).longValue(); final long cpuSystemTotalTime = ((Number) stats.getCpuStats().get("system_cpu_usage")).longValue(); final long memoryTotalBytes = ((Number) stats.getMemoryStats().get("limit")).longValue(); final long memoryTotalBytesUsage = ((Number) stats.getMemoryStats().get("usage")).longValue(); final long memoryTotalBytesCache = ((Number) ((Map) stats.getMemoryStats().get("stats")).get("cache")).longValue(); final Optional<Long> diskTotalBytes = nodeSpec.minDiskAvailableGb.map(size -> (long) (size * bytesInGB)); final Optional<Long> diskTotalBytesUsed = storageMaintainer.flatMap(maintainer -> maintainer .updateIfNeededAndGetDiskMetricsFor(containerName)); // CPU usage by a container is given by dividing used CPU time by the container with CPU time used by the entire // system. Because each container is allocated same amount of CPU shares, no container should use more than 1/n // of the total CPU time, where n is the number of running containers. double cpuPercentageOfHost = lastCpuMetric.getCpuUsagePercentage(cpuContainerTotalTime, cpuSystemTotalTime); double cpuPercentageOfAllocated = numAllocatedContainersOnHost * cpuPercentageOfHost; long memoryTotalBytesUsed = memoryTotalBytesUsage - memoryTotalBytesCache; double memoryPercentUsed = 100.0 * memoryTotalBytesUsed / memoryTotalBytes; Optional<Double> diskPercentUsed = diskTotalBytes.flatMap(total -> diskTotalBytesUsed.map(used -> 100.0 * used / total)); metricReceiver.declareGauge(APP, dimensions, "cpu.util").sample(cpuPercentageOfAllocated); metricReceiver.declareGauge(APP, dimensions, "mem.limit").sample(memoryTotalBytes); metricReceiver.declareGauge(APP, dimensions, "mem.used").sample(memoryTotalBytesUsed); metricReceiver.declareGauge(APP, dimensions, "mem.util").sample(memoryPercentUsed); diskTotalBytes.ifPresent(diskLimit -> metricReceiver.declareGauge(APP, dimensions, "disk.limit").sample(diskLimit)); diskTotalBytesUsed.ifPresent(diskUsed -> metricReceiver.declareGauge(APP, dimensions, "disk.used").sample(diskUsed)); diskPercentUsed.ifPresent(diskUtil -> metricReceiver.declareGauge(APP, dimensions, "disk.util").sample(diskUtil)); stats.getNetworks().forEach((interfaceName, interfaceStats) -> { Dimensions netDims = dimensionsBuilder.add("interface", interfaceName).build(); Map<String, Number> infStats = (Map<String, Number>) interfaceStats; metricReceiver.declareGauge(APP, netDims, "net.in.bytes").sample(infStats.get("rx_bytes").longValue()); metricReceiver.declareGauge(APP, netDims, "net.in.errors").sample(infStats.get("rx_errors").longValue()); metricReceiver.declareGauge(APP, netDims, "net.in.dropped").sample(infStats.get("rx_dropped").longValue()); metricReceiver.declareGauge(APP, netDims, "net.out.bytes").sample(infStats.get("tx_bytes").longValue()); metricReceiver.declareGauge(APP, netDims, "net.out.errors").sample(infStats.get("tx_errors").longValue()); metricReceiver.declareGauge(APP, netDims, "net.out.dropped").sample(infStats.get("tx_dropped").longValue()); }); // TODO: Remove when all alerts and dashboards have been updated to use new metric names metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.cpu.busy.pct").sample(cpuPercentageOfAllocated); addIfNotNull(dimensions, "node.cpu.throttled_time", stats.getCpuStats().get("throttling_data"), "throttled_time"); addIfNotNull(dimensions, "node.memory.limit", stats.getMemoryStats(), "limit"); long memoryUsageTotal = ((Number) stats.getMemoryStats().get("usage")).longValue(); long memoryUsageCache = ((Number) ((Map) stats.getMemoryStats().get("stats")).get("cache")).longValue(); long memoryUsage = memoryUsageTotal - memoryUsageCache; metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.memory.usage").sample(memoryUsage); stats.getNetworks().forEach((interfaceName, interfaceStats) -> { Dimensions netDims = dimensionsBuilder.add("interface", interfaceName).build(); addIfNotNull(netDims, "node.net.in.bytes", interfaceStats, "rx_bytes"); addIfNotNull(netDims, "node.net.in.errors", interfaceStats, "rx_errors"); addIfNotNull(netDims, "node.net.in.dropped", interfaceStats, "rx_dropped"); addIfNotNull(netDims, "node.net.out.bytes", interfaceStats, "tx_bytes"); addIfNotNull(netDims, "node.net.out.errors", interfaceStats, "tx_errors"); addIfNotNull(netDims, "node.net.out.dropped", interfaceStats, "tx_dropped"); }); diskTotalBytes.ifPresent(diskLimit -> metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.disk.limit").sample(diskLimit)); diskTotalBytesUsed.ifPresent(diskUsed -> metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.disk.used").sample(diskUsed)); // TODO END REMOVE metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_HOST_LIFE, dimensions, "uptime").sample(lastCpuMetric.getUptime()); metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_HOST_LIFE, dimensions, "alive").sample(1); // Push metrics to the metrics proxy in each container - give it maximum 1 seconds to complete try { //TODO The command here is almost a dummy command until we have the proper RPC method in place // Remember proper argument encoding dockerOperations.executeCommandInContainerAsRoot(containerName, 1L, "sh", "-c", "'echo " + metricReceiver.toString() + "'"); } catch (DockerExecTimeoutException e) { logger.warning("Unable to push metrics to container: " + containerName, e); } } @SuppressWarnings("unchecked") private void addIfNotNull(Dimensions dimensions, String yamasName, Object metrics, String metricName) { Map<String, Object> metricsMap = (Map<String, Object>) metrics; if (metricsMap == null || !metricsMap.containsKey(metricName)) return; try { metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, yamasName) .sample(((Number) metricsMap.get(metricName)).doubleValue()); } catch (Throwable e) { logger.warning("Failed to update " + yamasName + " metric with value " + metricsMap.get(metricName), e); } } private void writeConfigs(ContainerNodeSpec nodeSpec) { storageMaintainer.ifPresent(maintainer -> { maintainer.writeMetricsConfig(containerName, nodeSpec); maintainer.writeFilebeatConfig(containerName, nodeSpec); }); } private Optional<Container> getContainer() { if (containerState == ABSENT) return Optional.empty(); return dockerOperations.getContainer(containerName); } @Override public String getHostname() { return hostname; } @Override public boolean isDownloadingImage() { return imageBeingDownloaded != null; } @Override public int getAndResetNumberOfUnhandledExceptions() { int temp = numberOfUnhandledException; numberOfUnhandledException = 0; return temp; } class CpuUsageReporter { private long totalContainerUsage = 0; private long totalSystemUsage = 0; private final Instant created; CpuUsageReporter(Instant created) { this.created = created; } double getCpuUsagePercentage(long currentContainerUsage, long currentSystemUsage) { long deltaSystemUsage = currentSystemUsage - totalSystemUsage; double cpuUsagePct = (deltaSystemUsage == 0 || totalSystemUsage == 0) ? 0 : 100.0 * (currentContainerUsage - totalContainerUsage) / deltaSystemUsage; totalContainerUsage = currentContainerUsage; totalSystemUsage = currentSystemUsage; return cpuUsagePct; } long getUptime() { return Duration.between(created, clock.instant()).getSeconds(); } } // TODO: Also skip orchestration if we're downgrading in test/staging // How to implement: // - test/staging: We need to figure out whether we're in test/staging, zone is available in Environment // - downgrading: Impossible to know unless we look at the hosted version, which is // not available in the docker image (nor its name). Not sure how to solve this. Should // the node repo return the hosted version or a downgrade bit in addition to // wanted docker image etc? // Should the tenant pipeline instead use BCP tool to upgrade faster!? // // More generally, the node repo response should contain sufficient info on what the docker image is, // to allow the node admin to make decisions that depend on the docker image. Or, each docker image // needs to contain routines for drain and suspend. For many images, these can just be dummy routines. private void orchestratorSuspendNode() { logger.info("Ask Orchestrator for permission to suspend node " + hostname); orchestrator.suspend(hostname); } }
node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.node.admin.nodeagent; import com.yahoo.vespa.hosted.dockerapi.Container; import com.yahoo.vespa.hosted.dockerapi.ContainerName; import com.yahoo.vespa.hosted.dockerapi.Docker; import com.yahoo.vespa.hosted.dockerapi.DockerExecTimeoutException; import com.yahoo.vespa.hosted.dockerapi.DockerImage; import com.yahoo.vespa.hosted.dockerapi.metrics.Dimensions; import com.yahoo.vespa.hosted.dockerapi.metrics.MetricReceiverWrapper; import com.yahoo.vespa.hosted.node.admin.ContainerNodeSpec; import com.yahoo.vespa.hosted.node.admin.docker.DockerOperations; import com.yahoo.vespa.hosted.node.admin.maintenance.StorageMaintainer; import com.yahoo.vespa.hosted.node.admin.maintenance.acl.AclMaintainer; import com.yahoo.vespa.hosted.node.admin.noderepository.NodeRepository; import com.yahoo.vespa.hosted.node.admin.orchestrator.Orchestrator; import com.yahoo.vespa.hosted.node.admin.orchestrator.OrchestratorException; import com.yahoo.vespa.hosted.node.admin.util.Environment; import com.yahoo.vespa.hosted.node.admin.util.PrefixLogger; import com.yahoo.vespa.hosted.provision.Node; import java.text.SimpleDateFormat; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl.ContainerState.ABSENT; import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl.ContainerState.RUNNING; import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl.ContainerState.RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; /** * @author dybis * @author bakksjo */ public class NodeAgentImpl implements NodeAgent { private final AtomicBoolean terminated = new AtomicBoolean(false); private boolean isFrozen = true; private boolean wantFrozen = false; private boolean workToDoNow = true; private final Object monitor = new Object(); private final PrefixLogger logger; private DockerImage imageBeingDownloaded = null; private final String hostname; private final ContainerName containerName; private final NodeRepository nodeRepository; private final Orchestrator orchestrator; private final DockerOperations dockerOperations; private final Optional<StorageMaintainer> storageMaintainer; private final MetricReceiverWrapper metricReceiver; private final Environment environment; private final Clock clock; private final Optional<AclMaintainer> aclMaintainer; private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private final LinkedList<String> debugMessages = new LinkedList<>(); private long delaysBetweenEachConvergeMillis = 30_000; private int numberOfUnhandledException = 0; private Instant lastConverge; private Thread loopThread; enum ContainerState { ABSENT, RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN, RUNNING } private ContainerState containerState = ABSENT; // The attributes of the last successful node repo attribute update for this node. Used to avoid redundant calls. private NodeAttributes lastAttributesSet = null; private ContainerNodeSpec lastNodeSpec = null; private CpuUsageReporter lastCpuMetric; public NodeAgentImpl( final String hostName, final NodeRepository nodeRepository, final Orchestrator orchestrator, final DockerOperations dockerOperations, final Optional<StorageMaintainer> storageMaintainer, final MetricReceiverWrapper metricReceiver, final Environment environment, final Clock clock, final Optional<AclMaintainer> aclMaintainer) { this.nodeRepository = nodeRepository; this.orchestrator = orchestrator; this.hostname = hostName; this.containerName = ContainerName.fromHostname(hostName); this.dockerOperations = dockerOperations; this.storageMaintainer = storageMaintainer; this.logger = PrefixLogger.getNodeAgentLogger(NodeAgentImpl.class, containerName); this.metricReceiver = metricReceiver; this.environment = environment; this.clock = clock; this.aclMaintainer = aclMaintainer; this.lastConverge = clock.instant(); // If the container is already running, initialize vespaVersion and lastCpuMetric lastCpuMetric = new CpuUsageReporter(clock.instant()); dockerOperations.getContainer(containerName) .ifPresent(container -> { if (container.state.isRunning()) { lastCpuMetric = new CpuUsageReporter(container.created); } containerState = RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; logger.info("Container is already running, setting containerState to " + containerState); }); } @Override public boolean setFrozen(boolean frozen) { synchronized (monitor) { if (wantFrozen != frozen) { wantFrozen = frozen; addDebugMessage(wantFrozen ? "Freezing" : "Unfreezing"); signalWorkToBeDone(); } return isFrozen == frozen; } } private void addDebugMessage(String message) { synchronized (debugMessages) { while (debugMessages.size() > 1000) { debugMessages.pop(); } logger.debug(message); debugMessages.add("[" + sdf.format(new Date()) + "] " + message); } } @Override public Map<String, Object> debugInfo() { Map<String, Object> debug = new LinkedHashMap<>(); debug.put("Hostname", hostname); debug.put("isFrozen", isFrozen); debug.put("wantFrozen", wantFrozen); debug.put("terminated", terminated); debug.put("workToDoNow", workToDoNow); synchronized (debugMessages) { debug.put("History", new LinkedList<>(debugMessages)); } debug.put("Node repo state", lastNodeSpec.nodeState.name()); return debug; } @Override public void start(int intervalMillis) { addDebugMessage("Starting with interval " + intervalMillis + "ms"); delaysBetweenEachConvergeMillis = intervalMillis; if (loopThread != null) { throw new RuntimeException("Can not restart a node agent."); } loopThread = new Thread(() -> { while (!terminated.get()) tick(); }); loopThread.setName("tick-" + hostname); loopThread.start(); } @Override public void stop() { addDebugMessage("Stopping"); if (!terminated.compareAndSet(false, true)) { throw new RuntimeException("Can not re-stop a node agent."); } signalWorkToBeDone(); try { loopThread.join(10000); if (loopThread.isAlive()) { logger.error("Could not stop host thread " + hostname); } } catch (InterruptedException e1) { logger.error("Interrupted; Could not stop host thread " + hostname); } } private void runLocalResumeScriptIfNeeded(final ContainerNodeSpec nodeSpec) { if (containerState != RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN) { return; } addDebugMessage("Starting optional node program resume command"); dockerOperations.resumeNode(containerName); containerState = RUNNING; logger.info("Resume command successfully executed, new containerState is " + containerState); } private void updateNodeRepoAndMarkNodeAsReady(ContainerNodeSpec nodeSpec) { publishStateToNodeRepoIfChanged( // Clear current Docker image and vespa version, as nothing is running on this node new NodeAttributes() .withRestartGeneration(nodeSpec.wantedRestartGeneration.orElse(null)) .withRebootGeneration(nodeSpec.wantedRebootGeneration.orElse(0L)) .withDockerImage(new DockerImage("")) .withVespaVersion("")); nodeRepository.markNodeAvailableForNewAllocation(nodeSpec.hostname); } private void updateNodeRepoWithCurrentAttributes(final ContainerNodeSpec nodeSpec) { final NodeAttributes nodeAttributes = new NodeAttributes() .withRestartGeneration(nodeSpec.wantedRestartGeneration.orElse(null)) // update reboot gen with wanted gen if set, we ignore reboot for Docker nodes but // want the two to be equal in node repo .withRebootGeneration(nodeSpec.wantedRebootGeneration.orElse(0L)) .withDockerImage(nodeSpec.wantedDockerImage.orElse(new DockerImage(""))) .withVespaVersion(nodeSpec.wantedVespaVersion.orElse("")); publishStateToNodeRepoIfChanged(nodeAttributes); } private void publishStateToNodeRepoIfChanged(NodeAttributes currentAttributes) { // TODO: We should only update if the new current values do not match the node repo's current values if (!currentAttributes.equals(lastAttributesSet)) { logger.info("Publishing new set of attributes to node repo: " + lastAttributesSet + " -> " + currentAttributes); addDebugMessage("Publishing new set of attributes to node repo: {" + lastAttributesSet + "} -> {" + currentAttributes + "}"); nodeRepository.updateNodeAttributes(hostname, currentAttributes); lastAttributesSet = currentAttributes; } } private void startContainer(ContainerNodeSpec nodeSpec) { aclMaintainer.ifPresent(AclMaintainer::run); dockerOperations.startContainer(containerName, nodeSpec); lastCpuMetric = new CpuUsageReporter(clock.instant()); addDebugMessage("startContainerIfNeeded: containerState " + containerState + " -> " + RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN); containerState = RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; logger.info("Container successfully started, new containerState is " + containerState); } private Optional<Container> removeContainerIfNeededUpdateContainerState(ContainerNodeSpec nodeSpec, Optional<Container> existingContainer) { return existingContainer .flatMap(container -> removeContainerIfNeeded(nodeSpec, container)) .map(container -> { shouldRestartServices(nodeSpec).ifPresent(restartReason -> { logger.info("Will restart services for container " + container + ": " + restartReason); restartServices(nodeSpec, container); }); return container; }); } private Optional<String> shouldRestartServices(ContainerNodeSpec nodeSpec) { if (!nodeSpec.wantedRestartGeneration.isPresent()) return Optional.empty(); if (!nodeSpec.currentRestartGeneration.isPresent() || nodeSpec.currentRestartGeneration.get() < nodeSpec.wantedRestartGeneration.get()) { return Optional.of("Restart requested - wanted restart generation has been bumped: " + nodeSpec.currentRestartGeneration.get() + " -> " + nodeSpec.wantedRestartGeneration.get()); } return Optional.empty(); } private void restartServices(ContainerNodeSpec nodeSpec, Container existingContainer) { if (existingContainer.state.isRunning() && nodeSpec.nodeState == Node.State.active) { ContainerName containerName = existingContainer.name; logger.info("Restarting services for " + containerName); // Since we are restarting the services we need to suspend the node. orchestratorSuspendNode(); dockerOperations.restartVespaOnNode(containerName); } } @Override public void stopServices() { logger.info("Stopping services for " + containerName); dockerOperations.trySuspendNode(containerName); dockerOperations.stopServicesOnNode(containerName); } private Optional<String> shouldRemoveContainer(ContainerNodeSpec nodeSpec, Container existingContainer) { final Node.State nodeState = nodeSpec.nodeState; if (nodeState == Node.State.dirty || nodeState == Node.State.provisioned) { return Optional.of("Node in state " + nodeState + ", container should no longer be running"); } if (nodeSpec.wantedDockerImage.isPresent() && !nodeSpec.wantedDockerImage.get().equals(existingContainer.image)) { return Optional.of("The node is supposed to run a new Docker image: " + existingContainer + " -> " + nodeSpec.wantedDockerImage.get()); } if (!existingContainer.state.isRunning()) { return Optional.of("Container no longer running"); } return Optional.empty(); } private Optional<Container> removeContainerIfNeeded(ContainerNodeSpec nodeSpec, Container existingContainer) { Optional<String> removeReason = shouldRemoveContainer(nodeSpec, existingContainer); if (removeReason.isPresent()) { logger.info("Will remove container " + existingContainer + ": " + removeReason.get()); if (existingContainer.state.isRunning()) { if (nodeSpec.nodeState == Node.State.active) { orchestratorSuspendNode(); } try { stopServices(); } catch (Exception e) { logger.info("Failed stopping services, ignoring", e); } } dockerOperations.removeContainer(existingContainer); metricReceiver.unsetMetricsForContainer(hostname); containerState = ABSENT; logger.info("Container successfully removed, new containerState is " + containerState); return Optional.empty(); } return Optional.of(existingContainer); } private void scheduleDownLoadIfNeeded(ContainerNodeSpec nodeSpec) { if (nodeSpec.currentDockerImage.equals(nodeSpec.wantedDockerImage)) return; if (dockerOperations.shouldScheduleDownloadOfImage(nodeSpec.wantedDockerImage.get())) { if (nodeSpec.wantedDockerImage.get().equals(imageBeingDownloaded)) { // Downloading already scheduled, but not done. return; } imageBeingDownloaded = nodeSpec.wantedDockerImage.get(); // Create a signalWorkToBeDone when download is finished. dockerOperations.scheduleDownloadOfImage(containerName, imageBeingDownloaded, this::signalWorkToBeDone); } else if (imageBeingDownloaded != null) { // Image was downloading, but now it's ready imageBeingDownloaded = null; } } private void signalWorkToBeDone() { synchronized (monitor) { if (!workToDoNow) { workToDoNow = true; addDebugMessage("Signaling work to be done"); monitor.notifyAll(); } } } void tick() { boolean isFrozenCopy; synchronized (monitor) { while (!workToDoNow) { long remainder = delaysBetweenEachConvergeMillis - Duration.between(lastConverge, clock.instant()).toMillis(); if (remainder > 0) { try { monitor.wait(remainder); } catch (InterruptedException e) { logger.error("Interrupted, but ignoring this: " + hostname); } } else break; } lastConverge = clock.instant(); workToDoNow = false; if (isFrozen != wantFrozen) { isFrozen = wantFrozen; logger.info("Updated NodeAgent's frozen state, new value: isFrozen: " + isFrozen); } isFrozenCopy = isFrozen; } if (isFrozenCopy) { addDebugMessage("tick: isFrozen"); } else { try { converge(); } catch (OrchestratorException e) { logger.info(e.getMessage()); addDebugMessage(e.getMessage()); } catch (Exception e) { numberOfUnhandledException++; logger.error("Unhandled exception, ignoring.", e); addDebugMessage(e.getMessage()); } catch (Throwable t) { logger.error("Unhandled throwable, taking down system.", t); System.exit(234); } } } // Public for testing void converge() { final ContainerNodeSpec nodeSpec = nodeRepository.getContainerNodeSpec(hostname) .orElseThrow(() -> new IllegalStateException(String.format("Node '%s' missing from node repository.", hostname))); Optional<Container> container = getContainer(); if (!nodeSpec.equals(lastNodeSpec)) { addDebugMessage("Loading new node spec: " + nodeSpec.toString()); lastNodeSpec = nodeSpec; // Every time the node spec changes, we should clear the metrics for this container as the dimensions // will change and we will be reporting duplicate metrics. // TODO: Should be retried if writing fails metricReceiver.unsetMetricsForContainer(hostname); if (container.isPresent()) { storageMaintainer.ifPresent(maintainer -> { maintainer.writeMetricsConfig(containerName, nodeSpec); maintainer.writeFilebeatConfig(containerName, nodeSpec); }); } } switch (nodeSpec.nodeState) { case ready: case reserved: case parked: case failed: removeContainerIfNeededUpdateContainerState(nodeSpec, container); updateNodeRepoWithCurrentAttributes(nodeSpec); break; case active: storageMaintainer.ifPresent(maintainer -> { maintainer.removeOldFilesFromNode(containerName); maintainer.handleCoreDumpsForContainer(containerName, nodeSpec, environment); }); scheduleDownLoadIfNeeded(nodeSpec); if (isDownloadingImage()) { addDebugMessage("Waiting for image to download " + imageBeingDownloaded.asString()); return; } container = removeContainerIfNeededUpdateContainerState(nodeSpec, container); if (! container.isPresent()) { startContainer(nodeSpec); } runLocalResumeScriptIfNeeded(nodeSpec); // Because it's more important to stop a bad release from rolling out in prod, // we put the resume call last. So if we fail after updating the node repo attributes // but before resume, the app may go through the tenant pipeline but will halt in prod. // // Note that this problem exists only because there are 2 different mechanisms // that should really be parts of a single mechanism: // - The content of node repo is used to determine whether a new Vespa+application // has been successfully rolled out. // - Slobrok and internal orchestrator state is used to determine whether // to allow upgrade (suspend). updateNodeRepoWithCurrentAttributes(nodeSpec); logger.info("Call resume against Orchestrator"); orchestrator.resume(hostname); break; case inactive: storageMaintainer.ifPresent(maintainer -> maintainer.removeOldFilesFromNode(containerName)); removeContainerIfNeededUpdateContainerState(nodeSpec, container); updateNodeRepoWithCurrentAttributes(nodeSpec); break; case provisioned: nodeRepository.markAsDirty(hostname); break; case dirty: storageMaintainer.ifPresent(maintainer -> maintainer.removeOldFilesFromNode(containerName)); removeContainerIfNeededUpdateContainerState(nodeSpec, container); logger.info("State is " + nodeSpec.nodeState + ", will delete application storage and mark node as ready"); storageMaintainer.ifPresent(maintainer -> maintainer.archiveNodeData(containerName)); updateNodeRepoAndMarkNodeAsReady(nodeSpec); break; default: throw new RuntimeException("UNKNOWN STATE " + nodeSpec.nodeState.name()); } } @SuppressWarnings("unchecked") public void updateContainerNodeMetrics(int numAllocatedContainersOnHost) { final ContainerNodeSpec nodeSpec = lastNodeSpec; if (nodeSpec == null) return; Dimensions.Builder dimensionsBuilder = new Dimensions.Builder() .add("host", hostname) .add("role", "tenants") .add("flavor", nodeSpec.nodeFlavor) .add("state", nodeSpec.nodeState.toString()) .add("zone", environment.getZone()) .add("parentHostname", environment.getParentHostHostname()); nodeSpec.vespaVersion.ifPresent(version -> dimensionsBuilder.add("vespaVersion", version)); nodeSpec.owner.ifPresent(owner -> dimensionsBuilder .add("tenantName", owner.tenant) .add("applicationName", owner.application) .add("instanceName", owner.instance) .add("applicationId", owner.tenant + "." + owner.application + "." + owner.instance) .add("app", owner.application + "." + owner.instance)); nodeSpec.membership.ifPresent(membership -> dimensionsBuilder .add("clustertype", membership.clusterType) .add("clusterid", membership.clusterId)); Dimensions dimensions = dimensionsBuilder.build(); metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_NODE, dimensions, "alive").sample(1); // TODO: REMOVE metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.alive").sample(1); // The remaining metrics require container to exists and be running if (containerState == ABSENT) return; Optional<Docker.ContainerStats> containerStats = dockerOperations.getContainerStats(containerName); if (!containerStats.isPresent()) return; Docker.ContainerStats stats = containerStats.get(); final String APP = MetricReceiverWrapper.APPLICATION_NODE; final long bytesInGB = 1 << 30; final long cpuContainerTotalTime = ((Number) ((Map) stats.getCpuStats().get("cpu_usage")).get("total_usage")).longValue(); final long cpuSystemTotalTime = ((Number) stats.getCpuStats().get("system_cpu_usage")).longValue(); final long memoryTotalBytes = ((Number) stats.getMemoryStats().get("limit")).longValue(); final long memoryTotalBytesUsage = ((Number) stats.getMemoryStats().get("usage")).longValue(); final long memoryTotalBytesCache = ((Number) ((Map) stats.getMemoryStats().get("stats")).get("cache")).longValue(); final Optional<Long> diskTotalBytes = nodeSpec.minDiskAvailableGb.map(size -> (long) (size * bytesInGB)); final Optional<Long> diskTotalBytesUsed = storageMaintainer.flatMap(maintainer -> maintainer .updateIfNeededAndGetDiskMetricsFor(containerName)); // CPU usage by a container is given by dividing used CPU time by the container with CPU time used by the entire // system. Because each container is allocated same amount of CPU shares, no container should use more than 1/n // of the total CPU time, where n is the number of running containers. double cpuPercentageOfHost = lastCpuMetric.getCpuUsagePercentage(cpuContainerTotalTime, cpuSystemTotalTime); double cpuPercentageOfAllocated = numAllocatedContainersOnHost * cpuPercentageOfHost; long memoryTotalBytesUsed = memoryTotalBytesUsage - memoryTotalBytesCache; double memoryPercentUsed = 100.0 * memoryTotalBytesUsed / memoryTotalBytes; Optional<Double> diskPercentUsed = diskTotalBytes.flatMap(total -> diskTotalBytesUsed.map(used -> 100.0 * used / total)); metricReceiver.declareGauge(APP, dimensions, "cpu.util").sample(cpuPercentageOfAllocated); metricReceiver.declareGauge(APP, dimensions, "mem.limit").sample(memoryTotalBytes); metricReceiver.declareGauge(APP, dimensions, "mem.used").sample(memoryTotalBytesUsed); metricReceiver.declareGauge(APP, dimensions, "mem.util").sample(memoryPercentUsed); diskTotalBytes.ifPresent(diskLimit -> metricReceiver.declareGauge(APP, dimensions, "disk.limit").sample(diskLimit)); diskTotalBytesUsed.ifPresent(diskUsed -> metricReceiver.declareGauge(APP, dimensions, "disk.used").sample(diskUsed)); diskPercentUsed.ifPresent(diskUtil -> metricReceiver.declareGauge(APP, dimensions, "disk.util").sample(diskUtil)); stats.getNetworks().forEach((interfaceName, interfaceStats) -> { Dimensions netDims = dimensionsBuilder.add("interface", interfaceName).build(); Map<String, Number> infStats = (Map<String, Number>) interfaceStats; metricReceiver.declareGauge(APP, netDims, "net.in.bytes").sample(infStats.get("rx_bytes").longValue()); metricReceiver.declareGauge(APP, netDims, "net.in.errors").sample(infStats.get("rx_errors").longValue()); metricReceiver.declareGauge(APP, netDims, "net.in.dropped").sample(infStats.get("rx_dropped").longValue()); metricReceiver.declareGauge(APP, netDims, "net.out.bytes").sample(infStats.get("tx_bytes").longValue()); metricReceiver.declareGauge(APP, netDims, "net.out.errors").sample(infStats.get("tx_errors").longValue()); metricReceiver.declareGauge(APP, netDims, "net.out.dropped").sample(infStats.get("tx_dropped").longValue()); }); // TODO: Remove when all alerts and dashboards have been updated to use new metric names metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.cpu.busy.pct").sample(cpuPercentageOfAllocated); addIfNotNull(dimensions, "node.cpu.throttled_time", stats.getCpuStats().get("throttling_data"), "throttled_time"); addIfNotNull(dimensions, "node.memory.limit", stats.getMemoryStats(), "limit"); long memoryUsageTotal = ((Number) stats.getMemoryStats().get("usage")).longValue(); long memoryUsageCache = ((Number) ((Map) stats.getMemoryStats().get("stats")).get("cache")).longValue(); long memoryUsage = memoryUsageTotal - memoryUsageCache; metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.memory.usage").sample(memoryUsage); stats.getNetworks().forEach((interfaceName, interfaceStats) -> { Dimensions netDims = dimensionsBuilder.add("interface", interfaceName).build(); addIfNotNull(netDims, "node.net.in.bytes", interfaceStats, "rx_bytes"); addIfNotNull(netDims, "node.net.in.errors", interfaceStats, "rx_errors"); addIfNotNull(netDims, "node.net.in.dropped", interfaceStats, "rx_dropped"); addIfNotNull(netDims, "node.net.out.bytes", interfaceStats, "tx_bytes"); addIfNotNull(netDims, "node.net.out.errors", interfaceStats, "tx_errors"); addIfNotNull(netDims, "node.net.out.dropped", interfaceStats, "tx_dropped"); }); diskTotalBytes.ifPresent(diskLimit -> metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.disk.limit").sample(diskLimit)); diskTotalBytesUsed.ifPresent(diskUsed -> metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, "node.disk.used").sample(diskUsed)); // TODO END REMOVE metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_HOST_LIFE, dimensions, "uptime").sample(lastCpuMetric.getUptime()); metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_HOST_LIFE, dimensions, "alive").sample(1); // Push metrics to the metrics proxy in each container - give it maximum 1 seconds to complete try { //TODO The command here is almost a dummy command until we have the proper RPC method in place // Remember proper argument encoding dockerOperations.executeCommandInContainerAsRoot(containerName, 1L, "sh", "-c", "'echo " + metricReceiver.toString() + "'"); } catch (DockerExecTimeoutException e) { logger.warning("Unable to push metrics to container: " + containerName, e); } } @SuppressWarnings("unchecked") private void addIfNotNull(Dimensions dimensions, String yamasName, Object metrics, String metricName) { Map<String, Object> metricsMap = (Map<String, Object>) metrics; if (metricsMap == null || !metricsMap.containsKey(metricName)) return; try { metricReceiver.declareGauge(MetricReceiverWrapper.APPLICATION_DOCKER, dimensions, yamasName) .sample(((Number) metricsMap.get(metricName)).doubleValue()); } catch (Throwable e) { logger.warning("Failed to update " + yamasName + " metric with value " + metricsMap.get(metricName), e); } } private Optional<Container> getContainer() { if (containerState == ABSENT) return Optional.empty(); return dockerOperations.getContainer(containerName); } @Override public String getHostname() { return hostname; } @Override public boolean isDownloadingImage() { return imageBeingDownloaded != null; } @Override public int getAndResetNumberOfUnhandledExceptions() { int temp = numberOfUnhandledException; numberOfUnhandledException = 0; return temp; } class CpuUsageReporter { private long totalContainerUsage = 0; private long totalSystemUsage = 0; private final Instant created; CpuUsageReporter(Instant created) { this.created = created; } double getCpuUsagePercentage(long currentContainerUsage, long currentSystemUsage) { long deltaSystemUsage = currentSystemUsage - totalSystemUsage; double cpuUsagePct = (deltaSystemUsage == 0 || totalSystemUsage == 0) ? 0 : 100.0 * (currentContainerUsage - totalContainerUsage) / deltaSystemUsage; totalContainerUsage = currentContainerUsage; totalSystemUsage = currentSystemUsage; return cpuUsagePct; } long getUptime() { return Duration.between(created, clock.instant()).getSeconds(); } } // TODO: Also skip orchestration if we're downgrading in test/staging // How to implement: // - test/staging: We need to figure out whether we're in test/staging, zone is available in Environment // - downgrading: Impossible to know unless we look at the hosted version, which is // not available in the docker image (nor its name). Not sure how to solve this. Should // the node repo return the hosted version or a downgrade bit in addition to // wanted docker image etc? // Should the tenant pipeline instead use BCP tool to upgrade faster!? // // More generally, the node repo response should contain sufficient info on what the docker image is, // to allow the node admin to make decisions that depend on the docker image. Or, each docker image // needs to contain routines for drain and suspend. For many images, these can just be dummy routines. private void orchestratorSuspendNode() { logger.info("Ask Orchestrator for permission to suspend node " + hostname); orchestrator.suspend(hostname); } }
Write configs on container start as well
node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java
Write configs on container start as well
<ide><path>ode-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImpl.java <ide> dockerOperations.startContainer(containerName, nodeSpec); <ide> lastCpuMetric = new CpuUsageReporter(clock.instant()); <ide> <add> writeConfigs(nodeSpec); <add> <ide> addDebugMessage("startContainerIfNeeded: containerState " + containerState + " -> " + <ide> RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN); <ide> containerState = RUNNING_HOWEVER_RESUME_SCRIPT_NOT_RUN; <ide> // TODO: Should be retried if writing fails <ide> metricReceiver.unsetMetricsForContainer(hostname); <ide> if (container.isPresent()) { <del> storageMaintainer.ifPresent(maintainer -> { <del> maintainer.writeMetricsConfig(containerName, nodeSpec); <del> maintainer.writeFilebeatConfig(containerName, nodeSpec); <del> }); <add> writeConfigs(nodeSpec); <ide> } <ide> } <ide> <ide> } <ide> } <ide> <add> private void writeConfigs(ContainerNodeSpec nodeSpec) { <add> storageMaintainer.ifPresent(maintainer -> { <add> maintainer.writeMetricsConfig(containerName, nodeSpec); <add> maintainer.writeFilebeatConfig(containerName, nodeSpec); <add> }); <add> } <add> <ide> private Optional<Container> getContainer() { <ide> if (containerState == ABSENT) return Optional.empty(); <ide> return dockerOperations.getContainer(containerName);
Java
apache-2.0
ca6ec5b1b8f3543fc9cfb08c3d66ad0a6c01a826
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.util; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.NoSuchElementException; import java.util.function.Supplier; final class ValueMatcherImpl<T, T1> implements ValueKey.BeforeWhen<T>, ValueKey.BeforeThen<T, T1> { private enum State { NOT_MATCHED, IGNORING, SKIPPING, MATCHING, MATCHED, FINISHED } private @NotNull final String myKey; private @NotNull State myState = State.NOT_MATCHED; private T myValue; ValueMatcherImpl(@NotNull String key) { myKey = key; } @NotNull @Override public <TT> ValueKey.BeforeThen<T, TT> when(ValueKey<TT> key) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case IGNORING: case MATCHING: case SKIPPING: throw new IllegalStateException("We are in 'then' stage"); case MATCHED: if (key.getName().equals(myKey)) { throw new IllegalStateException("Key '" + key.getName() + "' already matched"); } myState = State.SKIPPING; break; case NOT_MATCHED: myState = key.getName().equals(myKey) ? State.MATCHING : State.IGNORING; } //noinspection unchecked return (ValueKey.BeforeThen<T, TT>)this; } @Override public T get() { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case NOT_MATCHED: throw new NoSuchElementException("Requested key '" + myKey + "' is not matched"); case MATCHED: return myValue; default: throw new IllegalStateException("We are in 'then' stage"); } } @Nullable @Override public T orNull() { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case NOT_MATCHED: case MATCHED: return myValue; default: throw new IllegalStateException("We are in 'then' stage"); } } @NotNull @Override public ValueKey.BeforeThen<T, T1> or(ValueKey<T1> key) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case MATCHED: case NOT_MATCHED: throw new IllegalStateException("We are in 'when' stage"); case SKIPPING: case MATCHING: if (key.getName().equals(myKey)) { throw new IllegalStateException("Key '" + key.getName() + "' already matched"); } break; case IGNORING: if (key.getName().equals(myKey)) { myState = State.MATCHING; } break; } return this; } @NotNull @Override public ValueKey.BeforeWhen<T> then(T1 value) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case MATCHED: case NOT_MATCHED: throw new IllegalStateException("We are in 'when' stage"); case SKIPPING: myState = State.MATCHED; break; case IGNORING: myState = State.NOT_MATCHED; break; case MATCHING: myState = State.MATCHED; //noinspection unchecked myValue = (T)value; } return this; } @NotNull @Override public ValueKey.BeforeWhen<T> thenGet(@NotNull Supplier<? extends T1> fn) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case MATCHED: case NOT_MATCHED: throw new IllegalStateException("We are in 'when' stage"); case SKIPPING: myState = State.MATCHED; break; case IGNORING: myState = State.NOT_MATCHED; break; case MATCHING: myState = State.MATCHED; //noinspection unchecked myValue = (T)fn.get(); } return this; } }
platform/util/src/com/intellij/openapi/util/ValueMatcherImpl.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.util; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.NoSuchElementException; import java.util.function.Supplier; final class ValueMatcherImpl<T, T1> implements ValueKey.BeforeWhen<T>, ValueKey.BeforeThen<T, T1> { private enum State { NOT_MATCHED, IGNORING, MATCHING, MATCHED, FINISHED } private @NotNull final String myKey; private @NotNull State myState = State.NOT_MATCHED; private T myValue; ValueMatcherImpl(@NotNull String key) { myKey = key; } @NotNull @Override public <TT> ValueKey.BeforeThen<T, TT> when(ValueKey<TT> key) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case IGNORING: case MATCHING: throw new IllegalStateException("We are in 'then' stage"); case MATCHED: if (key.getName().equals(myKey)) { throw new IllegalStateException("Key '" + key.getName() + "' already matched"); } myState = State.IGNORING; break; case NOT_MATCHED: myState = key.getName().equals(myKey) ? State.MATCHING : State.IGNORING; } //noinspection unchecked return (ValueKey.BeforeThen<T, TT>)this; } @Override public T get() { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case NOT_MATCHED: throw new NoSuchElementException("Requested key '" + myKey + "' is not matched"); case MATCHED: return myValue; default: throw new IllegalStateException("We are in 'then' stage"); } } @Nullable @Override public T orNull() { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case NOT_MATCHED: case MATCHED: return myValue; default: throw new IllegalStateException("We are in 'then' stage"); } } @NotNull @Override public ValueKey.BeforeThen<T, T1> or(ValueKey<T1> key) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case MATCHED: case NOT_MATCHED: throw new IllegalStateException("We are in 'when' stage"); case MATCHING: if (key.getName().equals(myKey)) { throw new IllegalStateException("Key '" + key.getName() + "' already matched"); } break; case IGNORING: if (key.getName().equals(myKey)) { myState = State.MATCHING; } break; } return this; } @NotNull @Override public ValueKey.BeforeWhen<T> then(T1 value) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case MATCHED: case NOT_MATCHED: throw new IllegalStateException("We are in 'when' stage"); case IGNORING: myState = State.NOT_MATCHED; break; case MATCHING: myState = State.MATCHED; //noinspection unchecked myValue = (T)value; } return this; } @NotNull @Override public ValueKey.BeforeWhen<T> thenGet(@NotNull Supplier<? extends T1> fn) { switch (myState) { case FINISHED: throw new IllegalStateException("We are already finished"); case MATCHED: case NOT_MATCHED: throw new IllegalStateException("We are in 'when' stage"); case IGNORING: myState = State.NOT_MATCHED; break; case MATCHING: myState = State.MATCHED; //noinspection unchecked myValue = (T)fn.get(); } return this; } }
ValueMatcherImpl: fixed state machine in case when matching was successful (IDEA-CR-52658) GitOrigin-RevId: 128ab9284687e793645cec5faa6c03e3e73abb97
platform/util/src/com/intellij/openapi/util/ValueMatcherImpl.java
ValueMatcherImpl: fixed state machine in case when matching was successful (IDEA-CR-52658)
<ide><path>latform/util/src/com/intellij/openapi/util/ValueMatcherImpl.java <ide> <ide> final class ValueMatcherImpl<T, T1> implements ValueKey.BeforeWhen<T>, ValueKey.BeforeThen<T, T1> { <ide> private enum State { <del> NOT_MATCHED, IGNORING, MATCHING, MATCHED, FINISHED <add> NOT_MATCHED, IGNORING, SKIPPING, MATCHING, MATCHED, FINISHED <ide> } <ide> <ide> private @NotNull final String myKey; <ide> throw new IllegalStateException("We are already finished"); <ide> case IGNORING: <ide> case MATCHING: <add> case SKIPPING: <ide> throw new IllegalStateException("We are in 'then' stage"); <ide> case MATCHED: <ide> if (key.getName().equals(myKey)) { <ide> throw new IllegalStateException("Key '" + key.getName() + "' already matched"); <ide> } <del> myState = State.IGNORING; <add> myState = State.SKIPPING; <ide> break; <ide> case NOT_MATCHED: <ide> myState = key.getName().equals(myKey) ? State.MATCHING : State.IGNORING; <ide> case MATCHED: <ide> case NOT_MATCHED: <ide> throw new IllegalStateException("We are in 'when' stage"); <add> case SKIPPING: <ide> case MATCHING: <ide> if (key.getName().equals(myKey)) { <ide> throw new IllegalStateException("Key '" + key.getName() + "' already matched"); <ide> case MATCHED: <ide> case NOT_MATCHED: <ide> throw new IllegalStateException("We are in 'when' stage"); <add> case SKIPPING: <add> myState = State.MATCHED; <add> break; <ide> case IGNORING: <ide> myState = State.NOT_MATCHED; <ide> break; <ide> case MATCHED: <ide> case NOT_MATCHED: <ide> throw new IllegalStateException("We are in 'when' stage"); <add> case SKIPPING: <add> myState = State.MATCHED; <add> break; <ide> case IGNORING: <ide> myState = State.NOT_MATCHED; <ide> break;
JavaScript
mit
18b402c4e5cf25ca9295ac215c789639a01af4f9
0
tsujio/webrtc-chord
define(['underscore', 'peerjs', 'Utils'], function(_, Peer, Utils) { var PeerAgent = function(config, callbacks) { var self = this; if (!_.isObject(config.peer)) { config.peer = {id: undefined, options: {}}; } if (!_.isObject(config.peer.options)) { config.peer.options = {}; } if (!Utils.isZeroOrPositiveNumber(config.connectRateLimit)) { config.connectRateLimit = 3000; } if (!Utils.isZeroOrPositiveNumber(config.connectionOpenTimeout)) { config.connectionOpenTimeout = 30000; } if (!_.isString(config.peer.id)) { this._peer = new Peer(config.peer.options); } else { this._peer = new Peer(config.peer.id, config.peer.options); } this._config = config; this._callbacks = callbacks; this._waitingTimer = null; this.connect = _.throttle(this.connect, config.connectRateLimit); var onPeerSetup = _.once(callbacks.onPeerSetup); this._peer.on('open', function(id) { Utils.debug("Peer opend (peer ID:", id, ")"); self._peer.on('connection', function(conn) { Utils.debug("Connection from", conn.peer); conn.on('open', function() { callbacks.onConnection(conn.peer, conn); }); }); self._peer.on('close', function() { Utils.debug("Peer closed."); callbacks.onPeerClosed(); }); onPeerSetup(id); }); this._peer.on('error', function(error) { Utils.debug("Peer error:", error); var match = error.message.match(/Could not connect to peer (\w+)/); if (match) { if (!self.isWaitingOpeningConnection()) { return; } clearTimeout(self._waitingTimer); self._waitingTimer = null; var peerId = match[1]; callbacks.onConnectionOpened(peerId, null, error); return; } console.log(error); onPeerSetup(null, error); }); }; PeerAgent.prototype = { connect: function(peerId) { var self = this; var conn = this._peer.connect(peerId); if (!conn) { var error = new Error("Failed to open connection to " + peerId + "."); this._callbacks.onConnectionOpened(peerId, null, error); return; } this._waitingTimer = setTimeout(function() { if (!self.isWaitingOpeningConnection()) { return; } self._waitingTimer = null; var error = new Error("Opening connection to " + peerId + " timed out."); self._callbacks.onConnectionOpened(peerId, null, error); }, this._config.connectionOpenTimeout); conn.on('open', function() { Utils.debug("Connection to", conn.peer, "opened."); if (!self.isWaitingOpeningConnection()) { conn.close(); return; } clearTimeout(self._waitingTimer); self._waitingTimer = null; self._callbacks.onConnectionOpened(peerId, conn); }); }, isWaitingOpeningConnection: function() { return !_.isNull(this._waitingTimer); }, destroy: function() { this._peer.destroy(); }, getPeerId: function() { return this._peer.id; } }; return PeerAgent; });
src/PeerAgent.js
define(['underscore', 'peerjs', 'Utils'], function(_, Peer, Utils) { var PeerAgent = function(config, callbacks) { var self = this; if (!_.isObject(config.peer)) { config.peer = {id: undefined, options: {}}; } if (!_.isObject(config.peer.options)) { config.peer.options = {}; } if (!Utils.isZeroOrPositiveNumber(config.connectRateLimit)) { config.connectRateLimit = 3000; } if (!Utils.isZeroOrPositiveNumber(config.connectionOpenTimeout)) { config.connectionOpenTimeout = 30000; } if (!_.isString(config.peer.id)) { this._peer = new Peer(config.peer.options); } else { this._peer = new Peer(config.peer.id, config.peer.options); } this._config = config; this._callbacks = callbacks; this._waitingTimer = null; this.connect = _.throttle(this.connect, config.connectRateLimit); var onPeerSetup = _.once(callbacks.onPeerSetup); this._peer.on('open', function(id) { Utils.debug("Peer opend (peer ID:", id, ")"); self._peer.on('connection', function(conn) { Utils.debug("Connection from", conn.peer); callbacks.onConnection(conn.peer, conn); }); self._peer.on('close', function() { Utils.debug("Peer closed."); callbacks.onPeerClosed(); }); onPeerSetup(id); }); this._peer.on('error', function(error) { Utils.debug("Peer error:", error); var match = error.message.match(/Could not connect to peer (\w+)/); if (match) { if (!self.isWaitingOpeningConnection()) { return; } clearTimeout(self._waitingTimer); self._waitingTimer = null; var peerId = match[1]; callbacks.onConnectionOpened(peerId, null, error); return; } console.log(error); onPeerSetup(null, error); }); }; PeerAgent.prototype = { connect: function(peerId) { var self = this; var conn = this._peer.connect(peerId); if (!conn) { var error = new Error("Failed to open connection to " + peerId + "."); this._callbacks.onConnectionOpened(peerId, null, error); return; } this._waitingTimer = setTimeout(function() { if (!self.isWaitingOpeningConnection()) { return; } self._waitingTimer = null; var error = new Error("Opening connection to " + peerId + " timed out."); self._callbacks.onConnectionOpened(peerId, null, error); }, this._config.connectionOpenTimeout); conn.on('open', function() { Utils.debug("Connection to", conn.peer, "opened."); if (!self.isWaitingOpeningConnection()) { conn.close(); return; } clearTimeout(self._waitingTimer); self._waitingTimer = null; self._callbacks.onConnectionOpened(peerId, conn); }); }, isWaitingOpeningConnection: function() { return !_.isNull(this._waitingTimer); }, destroy: function() { this._peer.destroy(); }, getPeerId: function() { return this._peer.id; } }; return PeerAgent; });
Now listeners of 'data' or 'close' are set to conn object after 'open' event fired.
src/PeerAgent.js
Now listeners of 'data' or 'close' are set to conn object after 'open' event fired.
<ide><path>rc/PeerAgent.js <ide> self._peer.on('connection', function(conn) { <ide> Utils.debug("Connection from", conn.peer); <ide> <del> callbacks.onConnection(conn.peer, conn); <add> conn.on('open', function() { <add> callbacks.onConnection(conn.peer, conn); <add> }); <ide> }); <ide> <ide> self._peer.on('close', function() {
Java
apache-2.0
4c60c7ac733c56109f5807ee57ee727a47a6055b
0
orekyuu/intellij-community,slisson/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,samthor/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,vladmm/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,slisson/intellij-community,gnuhub/intellij-community,samthor/intellij-community,hurricup/intellij-community,fnouama/intellij-community,FHannes/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,kool79/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,signed/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,akosyakov/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,clumsy/intellij-community,apixandru/intellij-community,samthor/intellij-community,da1z/intellij-community,semonte/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,ryano144/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,jexp/idea2,vvv1559/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,izonder/intellij-community,fitermay/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ibinti/intellij-community,samthor/intellij-community,fnouama/intellij-community,FHannes/intellij-community,fnouama/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,allotria/intellij-community,signed/intellij-community,fnouama/intellij-community,xfournet/intellij-community,kool79/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,amith01994/intellij-community,ryano144/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,orekyuu/intellij-community,caot/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,allotria/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ernestp/consulo,vvv1559/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,jexp/idea2,idea4bsd/idea4bsd,jexp/idea2,signed/intellij-community,nicolargo/intellij-community,samthor/intellij-community,kdwink/intellij-community,diorcety/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,amith01994/intellij-community,adedayo/intellij-community,apixandru/intellij-community,jagguli/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,slisson/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,semonte/intellij-community,ernestp/consulo,ryano144/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,consulo/consulo,jagguli/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,holmes/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,jexp/idea2,idea4bsd/idea4bsd,slisson/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,blademainer/intellij-community,retomerz/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,diorcety/intellij-community,asedunov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,consulo/consulo,amith01994/intellij-community,diorcety/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,holmes/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,caot/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,supersven/intellij-community,FHannes/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,signed/intellij-community,tmpgit/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,muntasirsyed/intellij-community,consulo/consulo,alphafoobar/intellij-community,ibinti/intellij-community,semonte/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,alphafoobar/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,izonder/intellij-community,fnouama/intellij-community,ernestp/consulo,amith01994/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,caot/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,caot/intellij-community,asedunov/intellij-community,signed/intellij-community,retomerz/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,diorcety/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,robovm/robovm-studio,semonte/intellij-community,joewalnes/idea-community,caot/intellij-community,supersven/intellij-community,supersven/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,allotria/intellij-community,wreckJ/intellij-community,izonder/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,slisson/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,retomerz/intellij-community,holmes/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,asedunov/intellij-community,kdwink/intellij-community,semonte/intellij-community,fitermay/intellij-community,izonder/intellij-community,robovm/robovm-studio,joewalnes/idea-community,holmes/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ernestp/consulo,robovm/robovm-studio,apixandru/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,petteyg/intellij-community,samthor/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,FHannes/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,jexp/idea2,da1z/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,samthor/intellij-community,da1z/intellij-community,adedayo/intellij-community,FHannes/intellij-community,slisson/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,semonte/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,holmes/intellij-community,da1z/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,allotria/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ernestp/consulo,kdwink/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,asedunov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,kool79/intellij-community,kdwink/intellij-community,blademainer/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,kool79/intellij-community,wreckJ/intellij-community,slisson/intellij-community,Lekanich/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,petteyg/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,signed/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,jagguli/intellij-community,hurricup/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,caot/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,kool79/intellij-community,vvv1559/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,dslomov/intellij-community,da1z/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,vvv1559/intellij-community,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,samthor/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,petteyg/intellij-community,adedayo/intellij-community,retomerz/intellij-community,vladmm/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,allotria/intellij-community,FHannes/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,robovm/robovm-studio,dslomov/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,dslomov/intellij-community,adedayo/intellij-community,xfournet/intellij-community,clumsy/intellij-community,blademainer/intellij-community,retomerz/intellij-community,clumsy/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,apixandru/intellij-community,vladmm/intellij-community,allotria/intellij-community,ryano144/intellij-community,signed/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,vladmm/intellij-community,ibinti/intellij-community,supersven/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,kool79/intellij-community,fitermay/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,kool79/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,allotria/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,fitermay/intellij-community,semonte/intellij-community,jexp/idea2,orekyuu/intellij-community,samthor/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ryano144/intellij-community,signed/intellij-community,semonte/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,caot/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,petteyg/intellij-community,hurricup/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,fitermay/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,jexp/idea2,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,ryano144/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,fnouama/intellij-community,kdwink/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,caot/intellij-community,caot/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,ahb0327/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,dslomov/intellij-community,slisson/intellij-community,retomerz/intellij-community,consulo/consulo,dslomov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,fnouama/intellij-community
/* * @author max */ package com.intellij.psi.impl.source.resolve; import com.intellij.psi.*; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.xml.XmlFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class JavaResolveUtil { public static PsiClass getContextClass(PsiElement element) { PsiElement scope = element.getContext(); while (scope != null) { if (scope instanceof PsiClass) return (PsiClass)scope; scope = scope.getContext(); } return null; } public static PsiElement findParentContextOfClass(PsiElement element, Class aClass, boolean strict){ PsiElement scope = strict ? element.getContext() : element; while(scope != null && !aClass.isInstance(scope)){ scope = scope.getContext(); } return scope; } public static boolean isAccessible(@NotNull PsiMember member, @Nullable final PsiClass memberClass, @Nullable PsiModifierList modifierList, @NotNull PsiElement place, @Nullable PsiClass accessObjectClass, @Nullable final PsiElement fileResolveScope) { if (modifierList == null) return true; final PsiFile placeContainingFile = place.getContainingFile(); final PsiManager manager = placeContainingFile.getManager(); if (placeContainingFile instanceof JavaCodeFragment) { JavaCodeFragment fragment = (JavaCodeFragment)placeContainingFile; JavaCodeFragment.VisibilityChecker visibilityChecker = fragment.getVisibilityChecker(); if (visibilityChecker != null) { JavaCodeFragment.VisibilityChecker.Visibility visibility = visibilityChecker.isDeclarationVisible(member, place); if (visibility == JavaCodeFragment.VisibilityChecker.Visibility.VISIBLE) return true; if (visibility == JavaCodeFragment.VisibilityChecker.Visibility.NOT_VISIBLE) return false; } } else if (placeContainingFile instanceof XmlFile && !PsiUtil.isInJspFile(placeContainingFile)) return true; // We don't care about access rights in javadoc if (isInJavaDoc(place)) return true; if (accessObjectClass != null) { if (!isAccessible(accessObjectClass, accessObjectClass.getContainingClass(), accessObjectClass.getModifierList(), place, null, null)) return false; } int effectiveAccessLevel = PsiUtil.getAccessLevel(modifierList); PsiFile file = FileContextUtil.getContextFile(place); //TODO: implementation method!!!! if (PsiUtil.isInJspFile(file) && PsiUtil.isInJspFile(member.getContainingFile())) return true; if (file instanceof XmlFile && !PsiUtil.isInJspFile(file)) return true; if (effectiveAccessLevel == PsiUtil.ACCESS_LEVEL_PUBLIC) { return true; } if (effectiveAccessLevel == PsiUtil.ACCESS_LEVEL_PROTECTED) { if (JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(member, place)) return true; if (memberClass == null) return false; for (PsiElement placeParent = place; placeParent != null; placeParent = placeParent.getContext()) { if (placeParent instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)placeParent, memberClass, true)) { if (member instanceof PsiClass || modifierList.hasModifierProperty(PsiModifier.STATIC)) return true; if (accessObjectClass == null || InheritanceUtil.isInheritorOrSelf(accessObjectClass, (PsiClass)placeParent, true)) return true; } } return false; } if (effectiveAccessLevel == PsiUtil.ACCESS_LEVEL_PRIVATE) { if (memberClass == null) return true; if (accessObjectClass != null) { PsiClass topMemberClass = getTopLevelClass(memberClass, accessObjectClass); PsiClass topAccessClass = getTopLevelClass(accessObjectClass, memberClass); if (!manager.areElementsEquivalent(topMemberClass, topAccessClass)) return false; } if (fileResolveScope == null) { PsiClass placeTopLevelClass = getTopLevelClass(place, null); PsiClass memberTopLevelClass = getTopLevelClass(memberClass, null); return manager.areElementsEquivalent(placeTopLevelClass, memberTopLevelClass); } else { return fileResolveScope instanceof PsiClass && !((PsiClass)fileResolveScope).isInheritor(memberClass, true); } } if (!JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(member, place)) return false; if (modifierList.hasModifierProperty(PsiModifier.STATIC)) return true; // maybe inheritance lead through package local class in other package ? final PsiClass placeClass = getContextClass(place); if (memberClass == null || placeClass == null) return true; // check only classes since interface members are public, and if placeClass is interface, // then its members are static, and cannot refer to nonstatic members of memberClass if (memberClass.isInterface() || placeClass.isInterface()) return true; if (placeClass.isInheritor(memberClass, true)) { PsiClass superClass = placeClass.getSuperClass(); while (!manager.areElementsEquivalent(superClass, memberClass)) { if (superClass == null || !JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(superClass, memberClass)) return false; superClass = superClass.getSuperClass(); } } return true; } public static boolean isInJavaDoc(final PsiElement place) { PsiElement scope = place; while(scope != null){ if (scope instanceof PsiDocComment) return true; if (scope instanceof PsiFile) return false; scope = scope.getContext(); } return false; } private static PsiClass getTopLevelClass(@NotNull PsiElement place, PsiClass memberClass) { PsiManager manager = place.getManager(); PsiClass lastClass = null; for (PsiElement placeParent = place; placeParent != null; placeParent = placeParent.getContext()) { if (placeParent instanceof PsiClass && !(placeParent instanceof PsiAnonymousClass) && !(placeParent instanceof PsiTypeParameter)) { PsiClass aClass = (PsiClass)placeParent; if (memberClass != null && aClass.isInheritor(memberClass, true)) return aClass; lastClass = aClass; } } return lastClass; } public static boolean processImplicitlyImportedPackages(final PsiScopeProcessor processor, final ResolveState state, final PsiElement place, PsiManager manager) { PsiPackage langPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage("java.lang"); if (langPackage != null) { if (!langPackage.processDeclarations(processor, state, null, place)) return false; } PsiPackage defaultPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(""); if (defaultPackage != null) { if (!defaultPackage.processDeclarations(processor, state, null, place)) return false; } return true; } }
source/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java
/* * @author max */ package com.intellij.psi.impl.source.resolve; import com.intellij.psi.*; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.xml.XmlFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class JavaResolveUtil { public static PsiClass getContextClass(PsiElement element) { PsiElement scope = element.getContext(); while (scope != null) { if (scope instanceof PsiClass) return (PsiClass)scope; scope = scope.getContext(); } return null; } public static PsiElement findParentContextOfClass(PsiElement element, Class aClass, boolean strict){ PsiElement scope = strict ? element.getContext() : element; while(scope != null && !aClass.isInstance(scope)){ scope = scope.getContext(); } return scope; } public static boolean isAccessible(@NotNull PsiMember member, @Nullable final PsiClass memberClass, @Nullable PsiModifierList modifierList, @NotNull PsiElement place, @Nullable PsiClass accessObjectClass, @Nullable final PsiElement fileResolveScope) { if (modifierList == null) return true; final PsiFile placeContainingFile = place.getContainingFile(); final PsiManager manager = placeContainingFile.getManager(); if (placeContainingFile instanceof JavaCodeFragment) { JavaCodeFragment fragment = (JavaCodeFragment)placeContainingFile; JavaCodeFragment.VisibilityChecker visibilityChecker = fragment.getVisibilityChecker(); if (visibilityChecker != null) { JavaCodeFragment.VisibilityChecker.Visibility visibility = visibilityChecker.isDeclarationVisible(member, place); if (visibility == JavaCodeFragment.VisibilityChecker.Visibility.VISIBLE) return true; if (visibility == JavaCodeFragment.VisibilityChecker.Visibility.NOT_VISIBLE) return false; } } else if (placeContainingFile instanceof XmlFile && !PsiUtil.isInJspFile(placeContainingFile)) return true; // We don't care about access rights in javadoc if (isInJavaDoc(place)) return true; if (accessObjectClass != null) { if (!isAccessible(accessObjectClass, accessObjectClass.getContainingClass(), accessObjectClass.getModifierList(), place, null, null)) return false; } int effectiveAccessLevel = PsiUtil.getAccessLevel(modifierList); PsiFile file = FileContextUtil.getContextFile(place); //TODO: implementation method!!!! if (PsiUtil.isInJspFile(file) && PsiUtil.isInJspFile(member.getContainingFile())) return true; if (file instanceof XmlFile && !PsiUtil.isInJspFile(file)) return true; if (effectiveAccessLevel == PsiUtil.ACCESS_LEVEL_PUBLIC) { return true; } if (effectiveAccessLevel == PsiUtil.ACCESS_LEVEL_PROTECTED) { if (JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(member, place)) return true; if (memberClass == null) return false; for (PsiElement placeParent = place; placeParent != null; placeParent = placeParent.getContext()) { if (placeParent instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)placeParent, memberClass, true)) { if (member instanceof PsiClass || modifierList.hasModifierProperty(PsiModifier.STATIC)) return true; if (accessObjectClass == null || InheritanceUtil.isInheritorOrSelf(accessObjectClass, (PsiClass)placeParent, true)) return true; } } return false; } if (effectiveAccessLevel == PsiUtil.ACCESS_LEVEL_PRIVATE) { if (memberClass == null) return true; if (accessObjectClass != null) { PsiClass topMemberClass = getTopLevelClass(memberClass, accessObjectClass); PsiClass topAccessClass = getTopLevelClass(accessObjectClass, memberClass); if (!manager.areElementsEquivalent(topMemberClass, topAccessClass)) return false; } if (fileResolveScope == null) { PsiClass placeTopLevelClass = getTopLevelClass(place, null); PsiClass memberTopLevelClass = getTopLevelClass(memberClass, null); return manager.areElementsEquivalent(placeTopLevelClass, memberTopLevelClass); } else { return fileResolveScope instanceof PsiClass && !((PsiClass)fileResolveScope).isInheritor(memberClass, true); } } if (!JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(member, place)) return false; if (modifierList.hasModifierProperty(PsiModifier.STATIC)) return true; // maybe inheritance lead through package local class in other package ? final PsiClass placeClass = getContextClass(place); if (memberClass == null || placeClass == null) return true; // check only classes since interface members are public, and if placeClass is interface, // then its members are static, and cannot refer to nonstatic members of memberClass if (memberClass.isInterface() || placeClass.isInterface()) return true; if (placeClass.isInheritor(memberClass, true)) { PsiClass superClass = placeClass.getSuperClass(); while (!manager.areElementsEquivalent(superClass, memberClass)) { if (superClass == null || !JavaPsiFacade.getInstance(manager.getProject()).arePackagesTheSame(superClass, memberClass)) return false; superClass = superClass.getSuperClass(); } } return true; } public static boolean isInJavaDoc(final PsiElement place) { PsiElement scope = place; while(scope != null){ if (scope instanceof PsiDocComment) return true; if (scope instanceof PsiFile) return false; scope = scope.getContext(); } return false; } private static PsiClass getTopLevelClass(@NotNull PsiElement place, PsiClass memberClass) { PsiManager manager = place.getManager(); PsiClass lastClass = null; for (PsiElement placeParent = place; placeParent != null; placeParent = placeParent.getContext()) { if (placeParent instanceof PsiClass && !(placeParent instanceof PsiAnonymousClass) && !(placeParent instanceof PsiTypeParameter)) { PsiClass aClass = (PsiClass)placeParent; if (memberClass != null && manager.areElementsEquivalent(memberClass, aClass.getSuperClass())) return aClass; lastClass = aClass; } } return lastClass; } public static boolean processImplicitlyImportedPackages(final PsiScopeProcessor processor, final ResolveState state, final PsiElement place, PsiManager manager) { PsiPackage langPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage("java.lang"); if (langPackage != null) { if (!langPackage.processDeclarations(processor, state, null, place)) return false; } PsiPackage defaultPackage = JavaPsiFacade.getInstance(manager.getProject()).findPackage(""); if (defaultPackage != null) { if (!defaultPackage.processDeclarations(processor, state, null, place)) return false; } return true; } }
IDEADEV-25243
source/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java
IDEADEV-25243
<ide><path>ource/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java <ide> !(placeParent instanceof PsiTypeParameter)) { <ide> PsiClass aClass = (PsiClass)placeParent; <ide> <del> if (memberClass != null && manager.areElementsEquivalent(memberClass, aClass.getSuperClass())) return aClass; <add> if (memberClass != null && aClass.isInheritor(memberClass, true)) return aClass; <ide> <ide> lastClass = aClass; <ide> }
Java
mit
8b1e19a30b8042f2215f68965334f94d3e925261
0
leppaott/Bulletin-Board,leppaott/Bulletin-Board
package Dao; import BulletinBoard.Database; import Domain.Subforum; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class SubforumDao { private final Database database; public SubforumDao(Database database) { this.database = database; } public Subforum findOne(int forumId) throws SQLException { List<Subforum> row = database.queryAndCollect( "SELECT * FROM Subforum WHERE forumId = ?;", rs -> { return new Subforum( rs.getInt("forumId"), rs.getString("name"), rs.getInt("postcount") ); }, forumId); return !row.isEmpty() ? row.get(0) : null; } public List<Subforum> findAll() throws SQLException { return database.queryAndCollect("SELECT * FROM Subforum;", rs -> { return new Subforum( rs.getInt("forumId"), rs.getString("name"), rs.getInt("postcount")); }); } public List<Subforum> findAllIn(Collection<Integer> keys) throws SQLException { List<Subforum> forums = new ArrayList<>(); StringBuilder params = new StringBuilder("?"); for (int i = 1; i < keys.size(); i++) { params.append(", ?"); } try (ResultSet rs = database.query("SELECT * FROM Subforum WHERE forumId IN (" + params + ");", keys)) { while (rs.next()) { forums.add(new Subforum(rs.getInt("forumId"), rs.getString("name"), rs.getInt("postcount"))); } } return forums; } }
Bulletin-Board/src/main/java/Dao/SubforumDao.java
package Dao; import BulletinBoard.Database; import Domain.Subforum; import java.sql.SQLException; import java.util.Collection; import java.util.List; public class SubforumDao { private final Database database; public SubforumDao(Database database) { this.database = database; } public Subforum findOne(int forumId) throws SQLException { List<Subforum> row = database.queryAndCollect( "SELECT * FROM Subforum WHERE forumId = ?;", rs -> { return new Subforum( rs.getInt("forumId"), rs.getString("name"), rs.getInt("postcount") ); }, forumId); return !row.isEmpty() ? row.get(0) : null; } public List<Subforum> findAll() throws SQLException { return database.queryAndCollect("SELECT * FROM Subforum;", rs -> { return new Subforum( rs.getInt("forumId"), rs.getString("name"), rs.getInt("postcount")); }); } public List<Subforum> findAllIn(Collection<Integer> keys) throws SQLException { //todo return null; } }
SubforumDao findAllIn
Bulletin-Board/src/main/java/Dao/SubforumDao.java
SubforumDao findAllIn
<ide><path>ulletin-Board/src/main/java/Dao/SubforumDao.java <ide> <ide> import BulletinBoard.Database; <ide> import Domain.Subforum; <add>import java.sql.ResultSet; <ide> import java.sql.SQLException; <add>import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.List; <ide> <ide> rs.getInt("postcount")); <ide> }); <ide> } <del> <add> <ide> public List<Subforum> findAllIn(Collection<Integer> keys) throws SQLException { <del> //todo <del> return null; <add> List<Subforum> forums = new ArrayList<>(); <add> <add> StringBuilder params = new StringBuilder("?"); <add> for (int i = 1; i < keys.size(); i++) { <add> params.append(", ?"); <add> } <add> <add> try (ResultSet rs = database.query("SELECT * FROM Subforum WHERE forumId IN (" <add> + params + ");", keys)) { <add> while (rs.next()) { <add> forums.add(new Subforum(rs.getInt("forumId"), <add> rs.getString("name"), <add> rs.getInt("postcount"))); <add> } <add> } <add> return forums; <ide> } <ide> }
Java
epl-1.0
079cd22442681e0453b0982b529ae38681d9557f
0
CityOfLearning/ForgeEssentials,aschmois/ForgeEssentialsMain,Techjar/ForgeEssentials,liachmodded/ForgeEssentials,planetguy32/ForgeEssentials,ForgeEssentials/ForgeEssentialsMain
package com.forgeessentials.playerlogger; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.persistence.metamodel.SingularAttribute; import javax.sql.rowset.serial.SerialBlob; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityCommandBlock; import net.minecraft.world.ChunkPosition; import net.minecraftforge.common.util.BlockSnapshot; import net.minecraftforge.event.CommandEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.living.LivingSpawnEvent.CheckSpawn; import net.minecraftforge.event.entity.living.LivingSpawnEvent.SpecialSpawn; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.PlayerEvent.StartTracking; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import net.minecraftforge.event.world.ExplosionEvent; import net.minecraftforge.event.world.WorldEvent; import com.forgeessentials.commons.selections.Selection; import com.forgeessentials.playerlogger.entity.ActionBlock; import com.forgeessentials.playerlogger.entity.ActionBlock.ActionBlockType; import com.forgeessentials.playerlogger.entity.ActionCommand; import com.forgeessentials.playerlogger.entity.Action_; import com.forgeessentials.playerlogger.entity.BlockData; import com.forgeessentials.playerlogger.entity.BlockData_; import com.forgeessentials.playerlogger.entity.PlayerData; import com.forgeessentials.playerlogger.entity.PlayerData_; import com.forgeessentials.playerlogger.entity.WorldData; import com.forgeessentials.util.OutputHandler; import com.forgeessentials.util.events.PlayerChangedZone; import com.forgeessentials.util.events.ServerEventHandler; import com.google.common.base.Charsets; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.registry.GameData; public class PlayerLogger extends ServerEventHandler { private EntityManagerFactory entityManagerFactory; private EntityManager em; private int transactionIndex; private Map<String, BlockData> blockCache = new HashMap<>(); private Map<UUID, PlayerData> playerCache = new HashMap<>(); /** * Closes any existing database connection and frees resources */ public void close() { transactionIndex = 0; playerCache.clear(); blockCache.clear(); if (em != null && em.isOpen()) em.close(); if (entityManagerFactory != null && entityManagerFactory.isOpen()) entityManagerFactory.close(); } /** * */ public void loadDatabase() { close(); // Set log level Logger.getLogger("org.hibernate").setLevel(Level.SEVERE); Properties properties = new Properties(); switch (PlayerLoggerConfig.databaseType) { case "h2": properties.setProperty("hibernate.connection.url", "jdbc:h2:" + PlayerLoggerConfig.databaseUrl); break; case "mysql": properties.setProperty("hibernate.connection.url", "jdbc:mysql://" + PlayerLoggerConfig.databaseUrl); // e.g.: jdbc:mysql://localhost:3306/forgeessentials break; default: throw new RuntimeException("PlayerLogger database type must be either h2 or mysql."); } properties.setProperty("hibernate.connection.username", PlayerLoggerConfig.databaseUsername); properties.setProperty("hibernate.connection.password", PlayerLoggerConfig.databasePassword); //properties.setProperty("hibernate.hbm2ddl.auto", "update"); //properties.setProperty("hibernate.format_sql", "false"); //properties.setProperty("hibernate.show_sql", "true"); entityManagerFactory = Persistence.createEntityManagerFactory("playerlogger_" + PlayerLoggerConfig.databaseType, properties); //entityManagerFactory = Persistence.createEntityManagerFactory("playerlogger_eclipselink_" + PlayerLoggerConfig.databaseType, properties); em = entityManagerFactory.createEntityManager(); } // ============================================================ // Utilities protected <T> TypedQuery<T> buildSimpleQuery(Class<T> clazz, String fieldName, Object value) { CriteriaBuilder cBuilder = em.getCriteriaBuilder(); CriteriaQuery<T> cQuery = cBuilder.createQuery(clazz); Root<T> cRoot = cQuery.from(clazz); cQuery.select(cRoot).where(cBuilder.equal(cRoot.get(fieldName), value)); return em.createQuery(cQuery); } protected <T,V> TypedQuery<T> buildSimpleQuery(Class<T> clazz, SingularAttribute<T, V> field, V value) { CriteriaBuilder cBuilder = em.getCriteriaBuilder(); CriteriaQuery<T> cQuery = cBuilder.createQuery(clazz); Root<T> cRoot = cQuery.from(clazz); cQuery.select(cRoot).where(cBuilder.equal(cRoot.get(field), value)); return em.createQuery(cQuery); } protected <T> T getOneOrNullResult(TypedQuery<T> query) { List<T> results = query.getResultList(); if (results.size() == 1) return results.get(0); if (results.isEmpty()) return null; throw new NonUniqueResultException(); } protected void beginTransaction() { if (transactionIndex <= 0) { em.getTransaction().begin(); transactionIndex = 0; } transactionIndex++; } protected void commitTransaction() { transactionIndex--; if (transactionIndex == 0) em.getTransaction().commit(); } protected void rollbackTransaction() { em.getTransaction().rollback(); transactionIndex = 0; } protected PlayerData getPlayer(String uuid) { beginTransaction(); PlayerData data = getOneOrNullResult(buildSimpleQuery(PlayerData.class, PlayerData_.uuid, uuid)); if (data == null) { data = new PlayerData(); data.uuid = uuid; em.persist(data); } commitTransaction(); return data; } protected PlayerData getPlayer(UUID uuid) { PlayerData data = playerCache.get(uuid); if (data != null) return data; data = getPlayer(uuid.toString()); playerCache.put(uuid, data); return data; } protected BlockData getBlock(String name) { BlockData data = blockCache.get(name); if (data != null) return data; beginTransaction(); data = getOneOrNullResult(buildSimpleQuery(BlockData.class, BlockData_.name, name)); if (data == null) { data = new BlockData(); data.name = name; em.persist(data); } commitTransaction(); blockCache.put(name, data); return data; } protected BlockData getBlock(Block block) { return getBlock(GameData.getBlockRegistry().getNameForObject(block)); } protected SerialBlob getTileEntityBlob(TileEntity entity) { if (entity == null) return null; NBTTagCompound nbt = new NBTTagCompound(); entity.writeToNBT(nbt); nbt.setString("ENTITY_CLASS", entity.getClass().getName()); try { return new SerialBlob(nbt.toString().getBytes(Charsets.UTF_8)); } catch (Exception ex) { OutputHandler.felog.severe(ex.toString()); ex.printStackTrace(); } return null; } // ============================================================ // Rollback public List<ActionBlock> getBlockChangeSet(Selection area, Date startTime) { CriteriaBuilder cBuilder = em.getCriteriaBuilder(); CriteriaQuery<ActionBlock> cQuery = cBuilder.createQuery(ActionBlock.class); Root<ActionBlock> cRoot = cQuery.from(ActionBlock.class); cQuery.select(cRoot); cQuery.where(cBuilder.and( cBuilder.greaterThanOrEqualTo(cRoot.get(Action_.time), cBuilder.literal(startTime)), cBuilder.equal(cRoot.<Integer>get(Action_.world.getName()), cBuilder.literal(area.getDimension())), cBuilder.between(cRoot.get(Action_.x), cBuilder.literal(area.getLowPoint().x), cBuilder.literal(area.getHighPoint().x)), cBuilder.between(cRoot.get(Action_.y), cBuilder.literal(area.getLowPoint().y), cBuilder.literal(area.getHighPoint().y)), cBuilder.between(cRoot.get(Action_.z), cBuilder.literal(area.getLowPoint().z), cBuilder.literal(area.getHighPoint().z)) )); cQuery.orderBy(cBuilder.desc(cRoot.get(Action_.time))); TypedQuery<ActionBlock> query = em.createQuery(cQuery); beginTransaction(); List<ActionBlock> changes = query.getResultList(); commitTransaction(); return changes; } // ============================================================ // Block events @SubscribeEvent(priority = EventPriority.LOWEST) public void worldLoad(WorldEvent.Load e) { beginTransaction(); WorldData world = em.find(WorldData.class, e.world.provider.dimensionId); if (world == null) { world = new WorldData(); world.id = e.world.provider.dimensionId; world.name = e.world.provider.getDimensionName(); em.persist(world); } commitTransaction(); } @SubscribeEvent(priority = EventPriority.LOWEST) public void placeEvent(BlockEvent.PlaceEvent e) { beginTransaction(); ActionBlock action = new ActionBlock(); action.time = new Date(); action.player = getPlayer(e.player.getPersistentID()); action.world = em.getReference(WorldData.class, e.world.provider.dimensionId); action.block = getBlock(e.block); action.metadata = e.blockMetadata; action.type = ActionBlockType.PLACE; action.x = e.x; action.y = e.y; action.z = e.z; em.persist(action); commitTransaction(); } @SubscribeEvent(priority = EventPriority.LOWEST) public void multiPlaceEvent(BlockEvent.MultiPlaceEvent e) { for (BlockSnapshot snapshot : e.getReplacedBlockSnapshots()) { beginTransaction(); ActionBlock action = new ActionBlock(); action.time = new Date(); action.player = getPlayer(e.player.getPersistentID()); action.world = em.getReference(WorldData.class, snapshot.world.provider.dimensionId); action.block = getBlock(snapshot.blockIdentifier.toString()); action.metadata = snapshot.meta; action.type = ActionBlockType.PLACE; action.x = snapshot.x; action.y = snapshot.y; action.z = snapshot.z; em.persist(action); commitTransaction(); } } @SubscribeEvent(priority = EventPriority.LOWEST) public void breakEvent(BreakEvent e) { beginTransaction(); ActionBlock action = new ActionBlock(); action.time = new Date(); action.player = getPlayer(e.getPlayer().getPersistentID()); action.world = em.getReference(WorldData.class, e.world.provider.dimensionId); action.block = getBlock(e.block); action.metadata = e.blockMetadata; action.entity = getTileEntityBlob(e.world.getTileEntity(e.x, e.y, e.z)); action.type = ActionBlockType.BREAK; action.x = e.x; action.y = e.y; action.z = e.z; em.persist(action); commitTransaction(); } @SuppressWarnings("unchecked") @SubscribeEvent(priority = EventPriority.LOWEST) public void explosionEvent(ExplosionEvent.Detonate e) { beginTransaction(); WorldData worldData = em.getReference(WorldData.class, e.world.provider.dimensionId); for (ChunkPosition blockPos : (List<ChunkPosition>) e.explosion.affectedBlockPositions) { ActionBlock action = new ActionBlock(); action.time = new Date(); action.world = worldData; action.block = getBlock(e.world.getBlock(blockPos.chunkPosX, blockPos.chunkPosY, blockPos.chunkPosZ)); action.metadata = e.world.getBlockMetadata(blockPos.chunkPosX, blockPos.chunkPosY, blockPos.chunkPosZ); action.entity = getTileEntityBlob(e.world.getTileEntity(blockPos.chunkPosX, blockPos.chunkPosY, blockPos.chunkPosZ)); action.type = ActionBlockType.DETONATE; action.x = blockPos.chunkPosX; action.y = blockPos.chunkPosY; action.z = blockPos.chunkPosZ; em.persist(action); } commitTransaction(); } // ============================================================ // Other events @SubscribeEvent(priority = EventPriority.LOWEST) public void commandEvent(CommandEvent e) { beginTransaction(); ActionCommand action = new ActionCommand(); action.time = new Date(); action.command = e.command.getCommandName(); if (e.sender instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) e.sender); action.player = getPlayer(player.getPersistentID()); action.world = em.getReference(WorldData.class, player.worldObj.provider.dimensionId); action.x = (int) player.posX; action.y = (int) player.posY; action.z = (int) player.posZ; } else if (e.sender instanceof TileEntityCommandBlock) { TileEntityCommandBlock block = ((TileEntityCommandBlock) e.sender); action.player = getPlayer("commandblock"); action.world = em.getReference(WorldData.class, block.getWorldObj().provider.dimensionId); action.x = block.xCoord; action.y = block.yCoord; action.z = block.zCoord; } em.persist(action); commitTransaction(); } // ============================================================ // Player events @SubscribeEvent(priority = EventPriority.LOWEST) public void playerLoggedInEvent(PlayerEvent.PlayerLoggedInEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerLoggedOutEvent(PlayerEvent.PlayerLoggedOutEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerRespawnEvent(PlayerEvent.PlayerRespawnEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerChangedDimensionEvent(PlayerEvent.PlayerChangedDimensionEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerChangedZoneEvent(PlayerChangedZone e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerOpenContainerEvent(PlayerOpenContainerEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void itemPickupEvent(EntityItemPickupEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void dropItemEvent(StartTracking e) { // TODO } // ============================================================ // Interact events @SubscribeEvent(priority = EventPriority.LOWEST) public void attackEntityEvent(AttackEntityEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void livingHurtEvent(LivingHurtEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerInteractEvent(PlayerInteractEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void entityInteractEvent(EntityInteractEvent e) { // TODO } // ============================================================ // Spawn events @SubscribeEvent(priority = EventPriority.LOWEST) public void checkSpawnEvent(CheckSpawn e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void specialSpawnEvent(SpecialSpawn e) { // TODO } }
src/main/java/com/forgeessentials/playerlogger/PlayerLogger.java
package com.forgeessentials.playerlogger; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.persistence.metamodel.SingularAttribute; import javax.sql.rowset.serial.SerialBlob; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityCommandBlock; import net.minecraft.world.ChunkPosition; import net.minecraftforge.event.CommandEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.living.LivingSpawnEvent.CheckSpawn; import net.minecraftforge.event.entity.living.LivingSpawnEvent.SpecialSpawn; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.PlayerEvent.StartTracking; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import net.minecraftforge.event.world.ExplosionEvent; import net.minecraftforge.event.world.WorldEvent; import com.forgeessentials.commons.selections.Selection; import com.forgeessentials.playerlogger.entity.ActionBlock; import com.forgeessentials.playerlogger.entity.ActionBlock.ActionBlockType; import com.forgeessentials.playerlogger.entity.ActionCommand; import com.forgeessentials.playerlogger.entity.Action_; import com.forgeessentials.playerlogger.entity.BlockData; import com.forgeessentials.playerlogger.entity.BlockData_; import com.forgeessentials.playerlogger.entity.PlayerData; import com.forgeessentials.playerlogger.entity.PlayerData_; import com.forgeessentials.playerlogger.entity.WorldData; import com.forgeessentials.util.OutputHandler; import com.forgeessentials.util.events.PlayerChangedZone; import com.forgeessentials.util.events.ServerEventHandler; import com.google.common.base.Charsets; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.registry.GameData; public class PlayerLogger extends ServerEventHandler { private EntityManagerFactory entityManagerFactory; private EntityManager em; private int transactionIndex; private Map<String, BlockData> blockCache = new HashMap<>(); private Map<UUID, PlayerData> playerCache = new HashMap<>(); /** * Closes any existing database connection and frees resources */ public void close() { transactionIndex = 0; playerCache.clear(); blockCache.clear(); if (em != null && em.isOpen()) em.close(); if (entityManagerFactory != null && entityManagerFactory.isOpen()) entityManagerFactory.close(); } /** * */ public void loadDatabase() { close(); Properties properties = new Properties(); switch (PlayerLoggerConfig.databaseType) { case "h2": properties.setProperty("hibernate.connection.url", "jdbc:h2:" + PlayerLoggerConfig.databaseUrl); break; case "mysql": properties.setProperty("hibernate.connection.url", "jdbc:mysql://" + PlayerLoggerConfig.databaseUrl); // e.g.: jdbc:mysql://localhost:3306/forgeessentials break; default: throw new RuntimeException("PlayerLogger database type must be either h2 or mysql."); } properties.setProperty("hibernate.connection.username", PlayerLoggerConfig.databaseUsername); properties.setProperty("hibernate.connection.password", PlayerLoggerConfig.databasePassword); //properties.setProperty("hibernate.hbm2ddl.auto", "update"); //properties.setProperty("hibernate.format_sql", "false"); //properties.setProperty("hibernate.show_sql", "true"); entityManagerFactory = Persistence.createEntityManagerFactory("playerlogger_" + PlayerLoggerConfig.databaseType, properties); //entityManagerFactory = Persistence.createEntityManagerFactory("playerlogger_eclipselink_" + PlayerLoggerConfig.databaseType, properties); em = entityManagerFactory.createEntityManager(); } // ============================================================ // Utilities protected <T> TypedQuery<T> buildSimpleQuery(Class<T> clazz, String fieldName, Object value) { CriteriaBuilder cBuilder = em.getCriteriaBuilder(); CriteriaQuery<T> cQuery = cBuilder.createQuery(clazz); Root<T> cRoot = cQuery.from(clazz); cQuery.select(cRoot).where(cBuilder.equal(cRoot.get(fieldName), value)); return em.createQuery(cQuery); } protected <T,V> TypedQuery<T> buildSimpleQuery(Class<T> clazz, SingularAttribute<T, V> field, V value) { CriteriaBuilder cBuilder = em.getCriteriaBuilder(); CriteriaQuery<T> cQuery = cBuilder.createQuery(clazz); Root<T> cRoot = cQuery.from(clazz); cQuery.select(cRoot).where(cBuilder.equal(cRoot.get(field), value)); return em.createQuery(cQuery); } protected <T> T getOneOrNullResult(TypedQuery<T> query) { List<T> results = query.getResultList(); if (results.size() == 1) return results.get(0); if (results.isEmpty()) return null; throw new NonUniqueResultException(); } protected void beginTransaction() { if (transactionIndex <= 0) { em.getTransaction().begin(); transactionIndex = 0; } transactionIndex++; } protected void commitTransaction() { transactionIndex--; if (transactionIndex == 0) em.getTransaction().commit(); } protected void rollbackTransaction() { em.getTransaction().rollback(); transactionIndex = 0; } protected PlayerData getPlayer(String uuid) { beginTransaction(); PlayerData data = getOneOrNullResult(buildSimpleQuery(PlayerData.class, PlayerData_.uuid, uuid)); if (data == null) { data = new PlayerData(); data.uuid = uuid; em.persist(data); } commitTransaction(); return data; } protected PlayerData getPlayer(UUID uuid) { PlayerData data = playerCache.get(uuid); if (data != null) return data; data = getPlayer(uuid.toString()); playerCache.put(uuid, data); return data; } protected BlockData getBlock(String name) { BlockData data = blockCache.get(name); if (data != null) return data; beginTransaction(); data = getOneOrNullResult(buildSimpleQuery(BlockData.class, BlockData_.name, name)); if (data == null) { data = new BlockData(); data.name = name; em.persist(data); } commitTransaction(); blockCache.put(name, data); return data; } protected BlockData getBlock(Block block) { return getBlock(GameData.getBlockRegistry().getNameForObject(block)); } protected SerialBlob getTileEntityBlob(TileEntity entity) { if (entity == null) return null; NBTTagCompound nbt = new NBTTagCompound(); entity.writeToNBT(nbt); nbt.setString("ENTITY_CLASS", entity.getClass().getName()); try { return new SerialBlob(nbt.toString().getBytes(Charsets.UTF_8)); } catch (Exception ex) { OutputHandler.felog.severe(ex.toString()); ex.printStackTrace(); } return null; } // ============================================================ // Rollback public List<ActionBlock> getBlockChangeSet(Selection area, Date startTime) { CriteriaBuilder cBuilder = em.getCriteriaBuilder(); CriteriaQuery<ActionBlock> cQuery = cBuilder.createQuery(ActionBlock.class); Root<ActionBlock> cRoot = cQuery.from(ActionBlock.class); cQuery.select(cRoot); cQuery.where(cBuilder.and( cBuilder.greaterThanOrEqualTo(cRoot.get(Action_.time), cBuilder.literal(startTime)), cBuilder.equal(cRoot.<Integer>get(Action_.world.getName()), cBuilder.literal(area.getDimension())), cBuilder.between(cRoot.get(Action_.x), cBuilder.literal(area.getLowPoint().x), cBuilder.literal(area.getHighPoint().x)), cBuilder.between(cRoot.get(Action_.y), cBuilder.literal(area.getLowPoint().y), cBuilder.literal(area.getHighPoint().y)), cBuilder.between(cRoot.get(Action_.z), cBuilder.literal(area.getLowPoint().z), cBuilder.literal(area.getHighPoint().z)) )); cQuery.orderBy(cBuilder.desc(cRoot.get(Action_.time))); TypedQuery<ActionBlock> query = em.createQuery(cQuery); beginTransaction(); List<ActionBlock> changes = query.getResultList(); commitTransaction(); return changes; } // ============================================================ // Block events @SubscribeEvent(priority = EventPriority.LOWEST) public void worldLoad(WorldEvent.Load e) { beginTransaction(); WorldData world = em.find(WorldData.class, e.world.provider.dimensionId); if (world == null) { world = new WorldData(); world.id = e.world.provider.dimensionId; world.name = e.world.provider.getDimensionName(); em.persist(world); } commitTransaction(); } @SubscribeEvent(priority = EventPriority.LOWEST) public void placeEvent(BlockEvent.PlaceEvent e) { beginTransaction(); ActionBlock action = new ActionBlock(); action.time = new Date(); action.player = getPlayer(e.player.getPersistentID()); action.world = em.getReference(WorldData.class, e.world.provider.dimensionId); action.block = getBlock(e.block); action.metadata = e.blockMetadata; action.type = ActionBlockType.PLACE; action.x = e.x; action.y = e.y; action.z = e.z; em.persist(action); commitTransaction(); } @SubscribeEvent(priority = EventPriority.LOWEST) public void multiPlaceEvent(BlockEvent.MultiPlaceEvent e) { /* beginTransaction(); ActionBlock action = new ActionBlock(); action.time = new Date(); action.player = getPlayer(e.player.getPersistentID()); action.world = em.getReference(WorldData.class, e.world.provider.dimensionId); action.block = getBlock(e.block); action.metadata = e.blockMetadata; action.type = ActionBlockType.PLACE; action.x = e.x; action.y = e.y; action.z = e.z; em.persist(action); commitTransaction(); */ } @SubscribeEvent(priority = EventPriority.LOWEST) public void breakEvent(BreakEvent e) { beginTransaction(); ActionBlock action = new ActionBlock(); action.time = new Date(); action.player = getPlayer(e.getPlayer().getPersistentID()); action.world = em.getReference(WorldData.class, e.world.provider.dimensionId); action.block = getBlock(e.block); action.metadata = e.blockMetadata; action.entity = getTileEntityBlob(e.world.getTileEntity(e.x, e.y, e.z)); action.type = ActionBlockType.BREAK; action.x = e.x; action.y = e.y; action.z = e.z; em.persist(action); commitTransaction(); } @SuppressWarnings("unchecked") @SubscribeEvent(priority = EventPriority.LOWEST) public void explosionEvent(ExplosionEvent.Detonate e) { beginTransaction(); WorldData worldData = em.getReference(WorldData.class, e.world.provider.dimensionId); for (ChunkPosition blockPos : (List<ChunkPosition>) e.explosion.affectedBlockPositions) { ActionBlock action = new ActionBlock(); action.time = new Date(); action.world = worldData; action.block = getBlock(e.world.getBlock(blockPos.chunkPosX, blockPos.chunkPosY, blockPos.chunkPosZ)); action.metadata = e.world.getBlockMetadata(blockPos.chunkPosX, blockPos.chunkPosY, blockPos.chunkPosZ); action.entity = getTileEntityBlob(e.world.getTileEntity(blockPos.chunkPosX, blockPos.chunkPosY, blockPos.chunkPosZ)); action.type = ActionBlockType.DETONATE; action.x = blockPos.chunkPosX; action.y = blockPos.chunkPosY; action.z = blockPos.chunkPosZ; em.persist(action); } commitTransaction(); } // ============================================================ // Other events @SubscribeEvent(priority = EventPriority.LOWEST) public void commandEvent(CommandEvent e) { beginTransaction(); ActionCommand action = new ActionCommand(); action.time = new Date(); action.command = e.command.getCommandName(); if (e.sender instanceof EntityPlayer) { EntityPlayer player = ((EntityPlayer) e.sender); action.player = getPlayer(player.getPersistentID()); action.world = em.getReference(WorldData.class, player.worldObj.provider.dimensionId); action.x = (int) player.posX; action.y = (int) player.posY; action.z = (int) player.posZ; } else if (e.sender instanceof TileEntityCommandBlock) { TileEntityCommandBlock block = ((TileEntityCommandBlock) e.sender); action.player = getPlayer("commandblock"); action.world = em.getReference(WorldData.class, block.getWorldObj().provider.dimensionId); action.x = block.xCoord; action.y = block.yCoord; action.z = block.zCoord; } em.persist(action); commitTransaction(); } // ============================================================ // Player events @SubscribeEvent(priority = EventPriority.LOWEST) public void playerLoggedInEvent(PlayerEvent.PlayerLoggedInEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerLoggedOutEvent(PlayerEvent.PlayerLoggedOutEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerRespawnEvent(PlayerEvent.PlayerRespawnEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerChangedDimensionEvent(PlayerEvent.PlayerChangedDimensionEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerChangedZoneEvent(PlayerChangedZone e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerOpenContainerEvent(PlayerOpenContainerEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void itemPickupEvent(EntityItemPickupEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void dropItemEvent(StartTracking e) { // TODO } // ============================================================ // Interact events @SubscribeEvent(priority = EventPriority.LOWEST) public void attackEntityEvent(AttackEntityEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void livingHurtEvent(LivingHurtEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void playerInteractEvent(PlayerInteractEvent e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void entityInteractEvent(EntityInteractEvent e) { // TODO } // ============================================================ // Spawn events @SubscribeEvent(priority = EventPriority.LOWEST) public void checkSpawnEvent(CheckSpawn e) { // TODO } @SubscribeEvent(priority = EventPriority.LOWEST) public void specialSpawnEvent(SpecialSpawn e) { // TODO } }
Fixed PlayerLogger spamming console. Fixed some PL events.
src/main/java/com/forgeessentials/playerlogger/PlayerLogger.java
Fixed PlayerLogger spamming console. Fixed some PL events.
<ide><path>rc/main/java/com/forgeessentials/playerlogger/PlayerLogger.java <ide> import java.util.Map; <ide> import java.util.Properties; <ide> import java.util.UUID; <add>import java.util.logging.Level; <add>import java.util.logging.Logger; <ide> <ide> import javax.persistence.EntityManager; <ide> import javax.persistence.EntityManagerFactory; <ide> import net.minecraft.tileentity.TileEntity; <ide> import net.minecraft.tileentity.TileEntityCommandBlock; <ide> import net.minecraft.world.ChunkPosition; <add>import net.minecraftforge.common.util.BlockSnapshot; <ide> import net.minecraftforge.event.CommandEvent; <ide> import net.minecraftforge.event.entity.living.LivingHurtEvent; <ide> import net.minecraftforge.event.entity.living.LivingSpawnEvent.CheckSpawn; <ide> public void loadDatabase() <ide> { <ide> close(); <del> <add> <add> // Set log level <add> Logger.getLogger("org.hibernate").setLevel(Level.SEVERE); <add> <ide> Properties properties = new Properties(); <ide> switch (PlayerLoggerConfig.databaseType) <ide> { <ide> @SubscribeEvent(priority = EventPriority.LOWEST) <ide> public void multiPlaceEvent(BlockEvent.MultiPlaceEvent e) <ide> { <del> /* <del> beginTransaction(); <del> ActionBlock action = new ActionBlock(); <del> action.time = new Date(); <del> action.player = getPlayer(e.player.getPersistentID()); <del> action.world = em.getReference(WorldData.class, e.world.provider.dimensionId); <del> action.block = getBlock(e.block); <del> action.metadata = e.blockMetadata; <del> action.type = ActionBlockType.PLACE; <del> action.x = e.x; <del> action.y = e.y; <del> action.z = e.z; <del> em.persist(action); <del> commitTransaction(); <del> */ <add> for (BlockSnapshot snapshot : e.getReplacedBlockSnapshots()) <add> { <add> beginTransaction(); <add> ActionBlock action = new ActionBlock(); <add> action.time = new Date(); <add> action.player = getPlayer(e.player.getPersistentID()); <add> action.world = em.getReference(WorldData.class, snapshot.world.provider.dimensionId); <add> action.block = getBlock(snapshot.blockIdentifier.toString()); <add> action.metadata = snapshot.meta; <add> action.type = ActionBlockType.PLACE; <add> action.x = snapshot.x; <add> action.y = snapshot.y; <add> action.z = snapshot.z; <add> em.persist(action); <add> commitTransaction(); <add> } <ide> } <ide> <ide> @SubscribeEvent(priority = EventPriority.LOWEST)
JavaScript
mpl-2.0
1b512a84bd8baa83e665d7a6b40504e56854a115
0
tonY1883/fleet-battle,tonY1883/fleet-battle
var counter_text_left; var counter_label_left; var counter_text_right; var counter_label_right; var game_phase = 0; var GAME_PHASE_SHIP_PLACEMENT = 0; var GAME_PAHSE_AERIAL_COMBAT = 1; var GAME_PHASE_COMBAT = 2; var grid_size; var map_size; var SHIP_COURSE_VERTICAL = 0; var SHIP_COURSE_HORIZONTAL = 1; var FLEET_SPEED_FAST = 0; var FLEET_SPEED_SLOW = 1; var ENGAGEMENT_FORM_PARALLEL = 0; var ENGAGEMENT_FORM_HEADON = 1; var ENGAGEMENT_FORM_T_ADV = 2; var ENGAGEMENT_FORM_T_DIS = 3; var SHIP_CLASS_BB = 0; var SHIP_CLASS_CV = 1; var SHIP_CLASS_CA = 2; var SHIP_CLASS_DD = 3; var SHIP_CLASS_AP = 4; var max_ship_count; var max_bb_count; var max_cv_count; var max_ca_count; var max_dd_count; var max_ap_count; var ship_class_placing; var ship_course_placing = 0; var ship_size_placing; var ship_class_target; var ship_class_acting; var acting_player; var PLAYER_1 = 0; var PLAYER_2 = 1; var player_1_first_act_complete = false; var player_2_first_act_complete = false; var total_turn_counter = 0; var max_turn_intercept_breakthrough; //game stats field for each player var player_1_ship_set = 0; var player_1_ships_count = [0, 0, 0, 0, 0]; var player_1_fleet_course = 0; var player_1_fleet_speed; var player_1_engagement_form; //Form Of Engagement var player_1_attack_count; var player_1_turn_counter = 0; var player_1_acted = false; var player_2_ship_set = 0; var player_2_ships_count = [0, 0, 0, 0, 0]; var player_2_fleet_course = 0; var player_2_fleet_speed; var player_2_engagement_form; var player_2_attack_count; var player_2_turn_counter = 0; var player_2_acted = false; //SFXs var gun_fire_sound; var plane_attack_sound; var attack_hit_sound; var attack_miss_sound; var attack_hit_sound_distant; /** * Set up the basic ui for the game */ function readyGame() { //load the sound first if (SOUND_ENABLED) { gun_fire_sound = new Audio(sfx_url.gun_fire); plane_attack_sound = new Audio(sfx_url.plane_attack); attack_hit_sound = new Audio(sfx_url.explosion); attack_miss_sound = new Audio(sfx_url.explosion_water); attack_hit_sound_distant = new Audio(sfx_url.explosion_distant); } document.getElementById("gameTitle").innerHTML = string.game_title; //set up the main moniters var monitors = document.querySelectorAll('.Monitor'); if (game_mode == GAME_MODE_CLASSIC) { map_size = 10; grid_size = Math.floor(DEFAULT_GRID_SIZE * DEFAULT_MAP_SIZE / map_size); } else { if (RANDOM_MAP_SIZE) { map_size = RNG(RANDOM_MAP_SIZE_MIN, RANDOM_MAP_SIZE_MAX); grid_size = Math.floor(DEFAULT_GRID_SIZE * DEFAULT_MAP_SIZE / map_size); } else { map_size = DEFAULT_MAP_SIZE; grid_size = DEFAULT_GRID_SIZE; } } if (game_mode == GAME_MODE_INTERCEPT || game_mode == GAME_MODE_BREAKTHROUGH || game_mode == GAME_MODE_CONVOY) { if (RANDOM_TIME_INTERCEPT_BREAKTHROUGH) { max_turn_intercept_breakthrough = RNG(MAX_TURN_INTERCEPT_MIN, MAX_TURN_INTERCEPT_MAX) } else { max_turn_intercept_breakthrough = MAX_TURN_INTERCEPT_DEFAULT; } } for (var i = 0; i < monitors.length; i++) { //set the map size monitors[i].style.width = grid_size * map_size + 2 + "px"; monitors[i].style.height = grid_size * map_size + 2 + "px"; //create a grid of map_size * map_size for (var j = 0; j < map_size; j++) { for (var k = 0; k < map_size; k++) { var grid = document.createElement('div'); grid.style.height = grid_size + 'px'; grid.style.width = grid_size + 'px'; grid.setAttribute('x', j); grid.setAttribute('y', k); grid.setAttribute('class', 'MonitorGrid'); var topPosition = j * grid_size; var leftPosition = k * grid_size; grid.style.top = topPosition + 'px'; grid.style.left = leftPosition + 'px'; var grid_canvas = document.createElement('canvas'); grid_canvas.style.height = grid_size + 'px'; grid_canvas.style.width = grid_size + 'px'; grid_canvas.setAttribute('c-x', j); grid_canvas.setAttribute('c-y', k); grid_canvas.setAttribute('class', 'GridCanvas'); grid_canvas.style.top = topPosition + 'px'; grid_canvas.style.left = leftPosition + 'px'; grid.appendChild(grid_canvas); monitors[i].appendChild(grid); } } } //upper panel document.getElementById("objective").innerHTML = string.game_objective_label; var objective = document.getElementById("objectiveList"); var game_mode_label = document.getElementById("gameModeLabel"); game_mode_label.innerHTML = string.game_mode_label; var game_mode_display = document.getElementById("gameMode"); game_mode_display.innerHTML = string.game_mode[game_mode]; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_BREAKTHROUGH: var o = document.createElement('li'); o.innerHTML = string.game_objective_loading; objective.appendChild(o); max_ship_count = MAX_SHIP_COUNT_STANDARD; max_cv_count = MAX_CV_COUNT_STANDARD; max_bb_count = MAX_BB_COUNT_STANDARD; max_ca_count = MAX_CA_COUNT_STANDARD; max_dd_count = MAX_DD_COUNT_STANDARD; break; case GAME_MODE_CLASSIC: var o = document.createElement('li'); o.innerHTML = string.game_objective_standard; objective.appendChild(o); max_ship_count = MAX_SHIP_COUNT_CLASSIC; max_cv_count = MAX_CV_COUNT_CLASSIC; max_bb_count = MAX_BB_COUNT_CLASSIC; max_ca_count = MAX_CA_COUNT_CLASSIC; max_dd_count = MAX_DD_COUNT_CLASSIC; break; case GAME_MODE_CONVOY: var o = document.createElement('li'); o.innerHTML = string.game_objective_loading; objective.appendChild(o); max_ship_count = MAX_SHIP_COUNT_STANDARD; max_cv_count = MAX_CV_COUNT_STANDARD; max_bb_count = MAX_BB_COUNT_STANDARD; max_ca_count = MAX_CA_COUNT_STANDARD; max_dd_count = MAX_DD_COUNT_STANDARD; max_ap_count = AP_COUNT_CONVOY; break; } //set up the data Panel document.getElementById("dataPanelLeft").style.height = grid_size * map_size + 2 + "px"; document.getElementById("dataPanelRight").style.height = grid_size * map_size + 2 + "px"; //left panel var rButton = document.getElementById('rbutton'); rButton.innerHTML = string.rotate; //rButton.setAttribute('class', 'Button'); rButton.style.display = 'none'; var label = document.createElement('p'); label.innerHTML = string.ship_placement_remaining; label.setAttribute('id', 'counterLabelLeft'); counter_label_left = label; document.getElementById("dataPanelContentLeft").appendChild(label); var counter = document.createElement('p'); counter.innerHTML = max_ship_count; counter.setAttribute('class', 'Counter'); counter.setAttribute('id', 'counterLeft'); counter_text_left = counter; document.getElementById("dataPanelContentLeft").appendChild(counter); //determine the ship iocn set to be used by each player var shipset = RNG(0, 3); player_1_ship_set = shipset; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_BREAKTHROUGH: case GAME_MODE_CLASSIC: for (var i = 0; i <= SHIP_CLASS_DD; i++) { var sLabel = document.createElement('p'); sLabel.setAttribute('class', 'ShipClassLabel'); sLabel.innerHTML = string.ship_classes[i]; document.getElementById("dataPanelContentLeft").appendChild(sLabel); var sIcon = document.createElement('img'); var classes; switch (i) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: classes = 'ShipIcons'; break; case SHIP_CLASS_CA: classes = 'ShipIcons ShipIconsCA'; break; case SHIP_CLASS_DD: classes = 'ShipIcons ShipIconsDD'; break; } sIcon.setAttribute('class', classes); sIcon.setAttribute('id', i); sIcon.setAttribute('src', img_url.ship_icons[player_1_ship_set][i]); document.getElementById("dataPanelContentLeft").appendChild(sIcon); } break; case GAME_MODE_CONVOY: for (var i = 0; i <= SHIP_CLASS_AP; i++) { var sLabel = document.createElement('p'); sLabel.setAttribute('class', 'ShipClassLabel'); sLabel.innerHTML = string.ship_classes[i]; document.getElementById("dataPanelContentLeft").appendChild(sLabel); var sIcon = document.createElement('img'); var classes; switch (i) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: classes = 'ShipIcons'; break; case SHIP_CLASS_CA: classes = 'ShipIcons ShipIconsCA'; break; case SHIP_CLASS_DD: classes = 'ShipIcons ShipIconsDD'; break; case SHIP_CLASS_AP: classes = 'ShipIcons ShipIconsCA'; break; } sIcon.setAttribute('class', classes); sIcon.setAttribute('id', i); sIcon.setAttribute('src', img_url.ship_icons[player_1_ship_set][i]); document.getElementById("dataPanelContentLeft").appendChild(sIcon); } break; } document.getElementById("apLeft").innerHTML = string.action_prompt_enemy; //right Panel var label2 = document.createElement('p'); label2.innerHTML = string.ship_placement_remaining; counter_label_right = label2; document.getElementById("dataPanelContentRight").appendChild(label2); var counter2 = document.createElement('p'); counter2.innerHTML = max_ship_count; counter2.setAttribute('class', 'Counter'); counter2.setAttribute('id', 'counterRight'); counter_text_right = counter2; document.getElementById("dataPanelContentRight").appendChild(counter2); //use a different ship icon set than player 1 while (player_2_ship_set == player_1_ship_set) { var shipset = RNG(0, 2); player_2_ship_set = shipset; } for (var i = 0; i <= SHIP_CLASS_DD; i++) { var sLabel2 = document.createElement('p'); sLabel2.setAttribute('class', 'ShipClassLabel'); sLabel2.innerHTML = string.ship_classes[i]; document.getElementById("dataPanelContentRight").appendChild(sLabel2); var sIcon2 = document.createElement('img'); var classes; switch (i) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: classes = 'ShipIconsEnemy ShipIcons'; break; case SHIP_CLASS_CA: classes = 'ShipIconsEnemy ShipIcons ShipIconsCA'; break; case SHIP_CLASS_DD: classes = 'ShipIconsEnemy ShipIcons ShipIconsDD'; break; } sIcon2.setAttribute('class', classes); sIcon2.setAttribute('src', img_url.ship_icons[player_2_ship_set][i]); document.getElementById("dataPanelContentRight").appendChild(sIcon2); } document.getElementById("apRight").innerHTML = string.action_prompt_player; //main button var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.assemble_fleet; mainButton.addEventListener('click', startShipPlacement, false); //show all stuff document.getElementById("content").style.visibility = "visible"; document.getElementById('settingBox').style.display = "none"; } function startShipPlacement() { //hide the panel for player 2 first document.getElementById("dataPanelContentRight").style.display = 'none'; var p = document.createElement('p'); p.innerHTML = string.pending; p.setAttribute('class', 'DataPanelOverlay'); p.setAttribute('id', 'pending'); document.getElementById("dataPanelRight").appendChild(p); //add onclicklistener for the ship icons var ships = document.getElementById("dataPanelContentLeft").querySelectorAll('.ShipIcons'); for (var i = 0; i < ships.length; i++) { var classes = ships[i].getAttribute('class'); classes = classes + " ShipIconsSelectable"; ships[i].setAttribute('class', classes); } var ships = document.querySelectorAll('.ShipIconsSelectable'); for (var i = 0; i < ships.length; i++) { var t = i; ships[i].addEventListener("click", onShipIconSelected, false); } document.getElementById('rbutton').addEventListener('click', function () { if (ship_course_placing == SHIP_COURSE_VERTICAL) { ship_course_placing = SHIP_COURSE_HORIZONTAL; } else { ship_course_placing = SHIP_COURSE_VERTICAL; } }, false); //prepare button for next page var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.start_battle; mainButton.removeEventListener('click', startShipPlacement, false); mainButton.addEventListener('click', startGame, false); } function onShipIconSelected(evt) { ship_class_placing = parseInt(evt.target.id); //set eventlistener for all the moniter grids var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].addEventListener('click', placeShip, false); grids[i].addEventListener('mouseover', projectShip, false); grids[i].addEventListener('mouseout', unProjectShip, false); grids[i].addEventListener('contextmenu', changeShipCourse, false); } window.oncontextmenu = function () { return false; }; document.getElementById("rbutton").style.display = 'inline'; } /** * Check if a ship can be placed in the given coordinate */ function shipPlaceable(x, y) { switch (ship_class_placing) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: ship_size_placing = 4; break; case SHIP_CLASS_CA: case SHIP_CLASS_AP: ship_size_placing = 3; break; case SHIP_CLASS_DD: ship_size_placing = 2; break; } if (ship_course_placing == SHIP_COURSE_VERTICAL) { //check if over edge of map if ((x + ship_size_placing) <= map_size && y <= map_size) { //check if another ship already exist for (var i = 0; i < ship_size_placing; i++) { if (document.querySelector("[x='" + (x + i) + "'][y='" + y + "']").hasAttribute("placed")) { return false; } } return true; } else { return false; } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { if ((y + ship_size_placing) <= map_size && x <= map_size) { for (var i = 0; i < ship_size_placing; i++) { if (document.querySelector("[y='" + (y + i) + "'][x='" + x + "']").hasAttribute("placed")) { return false; } } return true; } else { return false; } } } /** * creates a "projection" of a ship on the moniter to indicate this is possible to place a ship */ function projectShip(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (shipPlaceable(targetX, targetY)) { if (ship_course_placing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[x='" + (targetX + i) + "'][y='" + targetY + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[y='" + (targetY + i) + "'][x='" + targetX + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; tGrid.classList.add("ShipsTileHorizontal"); } } } } /** * remove the ship projection left by player */ function unProjectShip(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (shipPlaceable(targetX, targetY)) { if (ship_course_placing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[x='" + (targetX + i) + "'][y='" + targetY + "']"); tGrid.style.backgroundImage = ""; } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[y='" + (targetY + i) + "'][x='" + targetX + "']"); tGrid.style.backgroundImage = ""; tGrid.classList.remove("ShipsTileHorizontal"); } } } } function changeShipCourse(evt) { unProjectShip(evt); if (ship_course_placing == SHIP_COURSE_VERTICAL) { ship_course_placing = SHIP_COURSE_HORIZONTAL; } else { ship_course_placing = SHIP_COURSE_VERTICAL; } projectShip(evt); } function placeShip(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (shipPlaceable(targetX, targetY)) { if (ship_course_placing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[x='" + (targetX + i) + "'][y='" + targetY + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; var classes = tGrid.getAttribute('class'); classes = classes + " ShipsTile"; tGrid.setAttribute('class', classes); tGrid.setAttribute("placed", "true"); tGrid.setAttribute("ship-class", ship_class_placing); tGrid.setAttribute("ship-bearing", ship_course_placing); tGrid.setAttribute("sector", i); tGrid.setAttribute("head-x", targetX); tGrid.setAttribute("head-y", targetY); tGrid.style.backgroundColor = ''; tGrid.removeEventListener('click', placeShip, false); tGrid.removeEventListener('mouseover', projectShip, false); tGrid.removeEventListener('mouseout', unProjectShip, false); } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[y='" + (targetY + i) + "'][x='" + targetX + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; var classes = tGrid.getAttribute('class'); classes = classes + " ShipsTileHorizontal"; tGrid.setAttribute('class', classes); tGrid.removeEventListener('click', placeShip, false); tGrid.setAttribute("placed", "true"); tGrid.setAttribute("ship-class", ship_class_placing); tGrid.setAttribute("ship-bearing", ship_course_placing); tGrid.setAttribute("sector", i); tGrid.setAttribute("head-x", targetX); tGrid.setAttribute("head-y", targetY); tGrid.style.backgroundColor = ''; tGrid.removeEventListener('mouseover', projectShip, false); tGrid.removeEventListener('mouseout', unProjectShip, false); } } player_1_fleet_course = player_1_fleet_course + ship_course_placing; document.getElementById("counterLeft").innerHTML = parseInt(counter_text_left.innerHTML) - 1; //check for ship class limit switch (ship_class_placing) { case SHIP_CLASS_BB: player_1_ships_count[SHIP_CLASS_BB] = player_1_ships_count[SHIP_CLASS_BB] + 1; if (player_1_ships_count[SHIP_CLASS_BB] >= max_bb_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); //stops player from placing more ships for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_CV: player_1_ships_count[SHIP_CLASS_CV] = player_1_ships_count[SHIP_CLASS_CV] + 1; if (player_1_ships_count[SHIP_CLASS_CV] >= max_cv_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_CA: player_1_ships_count[SHIP_CLASS_CA] = player_1_ships_count[SHIP_CLASS_CA] + 1; if (player_1_ships_count[SHIP_CLASS_CA] >= max_ca_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_DD: player_1_ships_count[SHIP_CLASS_DD] = player_1_ships_count[SHIP_CLASS_DD] + 1; if (player_1_ships_count[SHIP_CLASS_DD] >= max_dd_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_AP: player_1_ships_count[SHIP_CLASS_AP] = player_1_ships_count[SHIP_CLASS_AP] + 1; if (player_1_ships_count[SHIP_CLASS_AP] >= max_ap_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; } if (getPlayerShipCount(PLAYER_1) >= max_ship_count) { stopPlayerShipPlacement(); } //enforce total number of transports if (game_mode == GAME_MODE_CONVOY) { if ((max_ship_count - getPlayerShipCount(PLAYER_1)) <= (max_ap_count - player_1_ships_count[SHIP_CLASS_AP]) && getPlayerShipCount(PLAYER_1) < max_ship_count && ship_class_placing != SHIP_CLASS_AP) { var allShips = document.querySelectorAll('.ShipIcons'); for (var n = 0; n < allShips.length; n++) { if (n != SHIP_CLASS_AP) { var c = allShips[n].getAttribute('class'); c = c.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); allShips[n].setAttribute('class', c); allShips[n].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var m = 0; m < grids.length; m++) { grids[m].removeEventListener('click', placeShip, false); grids[m].removeEventListener('mouseover', projectShip, false); grids[m].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } } } } } } /** * end the ship placing and prompt ai to place ship if possible */ function stopPlayerShipPlacement() { //disable ship selector var ships = document.querySelectorAll('.ShipIcons'); window.oncontextmenu = function () { return true; }; for (var i = 0; i < ships.length; i++) { var t = i; ships[i].removeEventListener("click", onShipIconSelected, false); //remove hover effect var classes = ships[i].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ''); classes = classes.replace(' ShipIconsUnSelectable', ''); ships[i].setAttribute('class', classes); } //disable grids var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); } //delete the button if it still exsists if (document.getElementById("rbutton") != null) { var button = document.getElementById("rbutton"); button.parentNode.removeChild(button); } if (getPlayerShipCount(PLAYER_2) < max_ship_count) { shipPlacementMain(); } } function getPlayerShipCount(player) { if (player == PLAYER_1) { return player_1_ships_count.reduce(function (a, b) { return a + b; }, 0); } else { return player_2_ships_count.reduce(function (a, b) { return a + b; }, 0); } } function startGame() { if (getPlayerShipCount(PLAYER_1) <= 0) { //TODO change this to html overl;ay dialog alert(string.no_ship_prompt); } else if (game_mode == GAME_MODE_CONVOY && player_1_ships_count[SHIP_CLASS_AP] < max_ap_count) { alert(string.no_ap_prompt); } else { stopPlayerShipPlacement(); //just in case var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.surrender; mainButton.removeEventListener('click', startGame, false); mainButton.addEventListener('click', surrender, false); //display info for both players var labels = document.getElementById("dataPanelContentLeft").querySelectorAll('.ShipClassLabel'); for (var i = 0; i < labels.length; i++) { labels[i].innerHTML = labels[i].innerHTML + " : " + player_1_ships_count[i]; } document.getElementById("counterLeft").innerHTML = getPlayerShipCount(PLAYER_1); //player 2 //unhide the panel document.getElementById("dataPanelContentRight").style.display = ''; var overlay = document.getElementById('pending'); overlay.parentNode.removeChild(overlay); var labels = document.getElementById("dataPanelContentRight").querySelectorAll('.ShipClassLabel'); if (!FOG_OF_WAR) { //show number of enemy ships by class for (var i = 0; i < labels.length; i++) { labels[i].innerHTML = labels[i].innerHTML + " : " + player_2_ships_count[i]; } } else { for (var i = 0; i < labels.length; i++) { labels[i].innerHTML = labels[i].innerHTML + " : " + "???"; } } document.getElementById("counterRight").innerHTML = getPlayerShipCount(PLAYER_2); switch (game_mode) { case GAME_MODE_SKIRMISH: //calculate the stats for each fleet //speed if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); o.innerHTML = string.game_objective_standard; objective.innerHTML = ""; objective.appendChild(o); aerialCombat(); break; case GAME_MODE_INTERCEPT: //ditto if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_2_ships_count[SHIP_CLASS_CV] > 0 && player_2_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = RNG(SHIP_CLASS_BB, SHIP_CLASS_CV); } else if (player_2_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = SHIP_CLASS_BB; } else if (player_2_ships_count[SHIP_CLASS_CV] > 0) { ship_class_target = SHIP_CLASS_CV; } else { //nothing of interest. SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH = false;//kill'em all. } } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (ship_class_target == SHIP_CLASS_BB) { o.innerHTML = string.game_objective_intercept_bb; } else { o.innerHTML = string.game_objective_intercept_cv; } } else { o.innerHTML = string.game_objective_standard; } objective.innerHTML = ""; objective.appendChild(o); document.getElementById("TurnCounterField").style.visibility = "visible"; document.getElementById("TurnCounterLabel").innerHTML = string.turn_counter_label; document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); aerialCombat(); break; case GAME_MODE_BREAKTHROUGH: //ditto if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_1_ships_count[SHIP_CLASS_CV] > 0 && player_1_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = RNG(SHIP_CLASS_BB, SHIP_CLASS_CV); } else if (player_1_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = SHIP_CLASS_BB; } else if (player_1_ships_count[SHIP_CLASS_CV] > 0) { ship_class_target = SHIP_CLASS_CV; } else { //nothing of interest. SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH = false;//kill'em all. } } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (ship_class_target == SHIP_CLASS_BB) { o.innerHTML = string.game_objective_breakthrough_bb; } else { o.innerHTML = string.game_objective_breakthrough_cv } } else { o.innerHTML = string.game_objective_breakthrough; } objective.innerHTML = ""; objective.appendChild(o); document.getElementById("TurnCounterField").style.visibility = "visible"; document.getElementById("TurnCounterLabel").innerHTML = string.turn_counter_label; document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); aerialCombat(); break; case GAME_MODE_CONVOY: //ditto if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); o.innerHTML = string.game_objective_convoy; objective.innerHTML = ""; objective.appendChild(o); document.getElementById("TurnCounterField").style.visibility = "visible"; document.getElementById("TurnCounterLabel").innerHTML = string.turn_counter_label; document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); aerialCombat(); break; case GAME_MODE_CLASSIC: //DO NOTHING //no aerial combat, too. startFleetCombat(); break; } } } /** * start the aerial combat phase */ function aerialCombat() { game_phase = GAME_PAHSE_AERIAL_COMBAT; ship_class_acting = SHIP_CLASS_CV; document.getElementById("stage").innerHTML = string.game_stage_aerial; //determine who will go first var first = RNG(PLAYER_1, PLAYER_2); if (first == PLAYER_1) { acting_player = PLAYER_1; promptAction(); player_1_attack_count = player_1_ships_count[SHIP_CLASS_CV] * 2; if (player_1_attack_count > 0) { beginTargeting(); } else { //no CVs nextPlayer(); } } else { acting_player = PLAYER_2; promptAction(); player_2_attack_count = player_2_ships_count[SHIP_CLASS_CV] * 2; if (player_2_attack_count > 0) { attackMain(); } else { //no CVs nextPlayer(); } } } function startFleetCombat() { game_phase = GAME_PHASE_COMBAT; document.getElementById("stage").innerHTML = string.game_stage_artillery; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_BREAKTHROUGH: case GAME_MODE_CONVOY: //first decide the engagement form if (player_1_fleet_course == player_2_fleet_course) { player_1_engagement_form = RNG(ENGAGEMENT_FORM_PARALLEL, ENGAGEMENT_FORM_HEADON); player_2_engagement_form = player_1_engagement_form; } else { if (player_1_fleet_speed != player_2_fleet_speed) { if (player_1_fleet_speed == FLEET_SPEED_SLOW) { player_1_engagement_form = ENGAGEMENT_FORM_T_DIS; player_2_engagement_form = ENGAGEMENT_FORM_T_ADV; } else if (player_2_fleet_speed == FLEET_SPEED_SLOW) { player_1_engagement_form = ENGAGEMENT_FORM_T_ADV; player_2_engagement_form = ENGAGEMENT_FORM_T_DIS; } } else { player_1_engagement_form = RNG(ENGAGEMENT_FORM_T_ADV, ENGAGEMENT_FORM_T_DIS); if (player_1_engagement_form == ENGAGEMENT_FORM_T_DIS) { player_2_engagement_form = ENGAGEMENT_FORM_T_ADV; } else { player_2_engagement_form = ENGAGEMENT_FORM_T_DIS; } } } break; case GAME_MODE_CLASSIC: //DO NOTHING break; } //TODO sound fx and animation if (!FOG_OF_WAR) { document.getElementById("FoELabel").innerHTML = string.form_of_engagement_label; document.getElementById("FoE").innerHTML = string.form_of_engagement[player_1_engagement_form]; } player_1_acted = false; player_2_acted = false; //determine who will go first var first = RNG(PLAYER_1, PLAYER_2); if (first == PLAYER_1) { acting_player = PLAYER_1; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: //let's see what type of ships we have. if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_1_attack_count = BB_ATTACK_COUNT[player_1_engagement_form]; } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_1) > 0) { player_1_attack_count = 1; } break; } if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { nextPlayer(); } } else { acting_player = PLAYER_2; switch (game_mode) { case GAME_MODE_SKIRMISH: //let's see what type of ships we have. if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_2_attack_count = BB_ATTACK_COUNT[player_2_engagement_form]; } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_2) > 0) { player_2_attack_count = 1; } break; } if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; promptAction(); attackMain(); } else { nextPlayer(); } } } /** * allow the player to select a squre to fire on */ function beginTargeting() { promptAction(); document.getElementById("counterLeft").innerHTML = player_1_attack_count; document.getElementById("counterLabelLeft").innerHTML = string.attack_remaining; var grids = document.getElementById("monitorRight").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { if (!grids[i].hasAttribute("sunk")) { grids[i].addEventListener('click', fire, false); } if (!grids[i].hasAttribute("sunk") && !grids[i].hasAttribute("hit_count")) { grids[i].addEventListener('mouseover', lockOnSector, false); grids[i].addEventListener('mouseout', unLockOnSector, false); } } } function fire(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (acting_player == PLAYER_1) { player_1_attack_count = player_1_attack_count - 1; document.getElementById("counterLeft").innerHTML = player_1_attack_count; } else if (acting_player == PLAYER_2) { player_2_attack_count = player_2_attack_count - 1; } stopTargeting(); if (ship_class_acting == SHIP_CLASS_CV) { airStrike(targetX, targetY); } else { artilleryStrike(targetX, targetY); } } function airStrike(x, y) { if (SOUND_ENABLED) { plane_attack_sound.play(); setTimeout(function () { onAttackLanded(x, y); }, plane_attack_sound.duration * 1000 + 800); } else { onAttackLanded(x, y); } } function artilleryStrike(x, y) { if (SOUND_ENABLED && acting_player == PLAYER_1) { gun_fire_sound.play(); setTimeout(function () { onAttackLanded(x, y); }, gun_fire_sound.duration * 1000 + 800); } else { onAttackLanded(x, y); } } //determine if the attack hit and its consequences function onAttackLanded(x, y) { if (acting_player == PLAYER_1) { var tGrid = document.getElementById("monitorRight").querySelector("[y='" + y + "'][x='" + x + "']"); if (tGrid.hasAttribute("hit_count")) { var hit = parseInt(tGrid.getAttribute("hit_count")); tGrid.setAttribute("hit_count", hit + 1); } else { tGrid.setAttribute("hit_count", "1"); } tGrid.style.backgroundColor = 'navy'; tGrid.style.backgroundImage = ""; //see if we hit a ship if (tGrid.hasAttribute("placed")) { tGrid.style.backgroundColor = ''; tGrid.style.backgroundImage = ""; if (tGrid.hasAttribute("effectId")) { //stop all previous effects var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); } //show explosion effect var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 8; i++) { particles.push(new explosionParticle()); } var eid = setInterval(function () { showExplosion(canvas, particles, true); }, 40); setTimeout(function () { clearInterval(eid); if (!tGrid.hasAttribute("sunk")) { var hc = parseInt(tGrid.getAttribute("hit_count")); if (hc <= 1) { var canvas = tGrid.firstElementChild; var particles = []; var particle_count = 8; for (var i = 0; i < particle_count; i++) { particles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showSmoke(canvas, particles, true); }, 40); } else { var id = setInterval(function () { showSmoke(canvas, particles, false); }, 40); } tGrid.setAttribute("effectId", id); } else { //clear the old effect first var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); var canvas = tGrid.firstElementChild; var fireParticles = []; var smokeParticles = []; for (var i = 0; i < 10; i++) { fireParticles.push(new fireParticle()); } for (var i = 0; i < 5; i++) { smokeParticles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, true); }, 40); } else { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, false); }, 40); } tGrid.setAttribute("effectId", id); } } }, 1200); //see if we sunk it if (shipDestroyed("monitorRight", x, y)) { //TODO add instant win determiner //mark the ships as destroyed var tx = parseInt(tGrid.getAttribute("head-x")); var ty = parseInt(tGrid.getAttribute("head-y")); var tclass = parseInt(tGrid.getAttribute("ship-class")); var tbearing = parseInt(tGrid.getAttribute("ship-bearing")); var ship_size; switch (tclass) { case SHIP_CLASS_BB: ship_size = 4; player_2_ships_count[SHIP_CLASS_BB] = player_2_ships_count[SHIP_CLASS_BB] - 1; break; case SHIP_CLASS_CV: ship_size = 4; player_2_ships_count[SHIP_CLASS_CV] = player_2_ships_count[SHIP_CLASS_CV] - 1; break; case SHIP_CLASS_CA: ship_size = 3; player_2_ships_count[SHIP_CLASS_CA] = player_2_ships_count[SHIP_CLASS_CA] - 1; break; case SHIP_CLASS_DD: ship_size = 2; player_2_ships_count[SHIP_CLASS_DD] = player_2_ships_count[SHIP_CLASS_DD] - 1; break; } if (!FOG_OF_WAR) { refreshEnemyPanel(); } else { document.getElementById("counterRight").innerHTML = getPlayerShipCount(PLAYER_2); } if (tbearing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorRight").querySelector("[x='" + (tx + i) + "'][y='" + ty + "']"); if (!FOG_OF_WAR) { Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; } else { Grid.style.backgroundColor = "#990000"; } Grid.setAttribute("sunk", "true"); var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.removeEventListener('click', fire, false); } } else if (tbearing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorRight").querySelector("[y='" + (ty + i) + "'][x='" + tx + "']"); if (!FOG_OF_WAR) { Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; } else { Grid.style.backgroundColor = "#990000"; } Grid.setAttribute("sunk", "true"); var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.removeEventListener('click', fire, false); } } } if (SOUND_ENABLED) { attack_hit_sound_distant.play(); setTimeout(function () { if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, attack_hit_sound_distant.duration * 1000 + 800); } else { setTimeout(function () { if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, 1200); } } else { var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 340; i++) { particles.push(new waterParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var sid = setInterval(function () { showWaterSplash(canvas, particles, true); }, 60); } else { var sid = setInterval(function () { showWaterSplash(canvas, particles, false); }, 60); } if (SOUND_ENABLED) { attack_miss_sound.play(); setTimeout(function () { clearInterval(sid); if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, attack_miss_sound.duration * 1000 + 800); } else { setTimeout(function () { clearInterval(sid); if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, 3000); } } } else if (acting_player == PLAYER_2) { var tGrid = document.getElementById("monitorLeft").querySelector("[y='" + y + "'][x='" + x + "']"); if (tGrid.hasAttribute("hit_count")) { var hit = parseInt(tGrid.getAttribute("hit_count")); tGrid.setAttribute("hit_count", hit + 1); } else { tGrid.setAttribute("hit_count", "1"); } tGrid.style.backgroundColor = 'navy'; //see if we hit a ship if (tGrid.hasAttribute("placed")) { tGrid.style.backgroundColor = ''; //tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[parseInt(tGrid.getAttribute("ship-class"))][1][parseInt(tGrid.getAttribute("sector"))] + "')"; if (tGrid.hasAttribute("effectId")) { //stop all previous effects var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); } //show explosion effect var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 8; i++) { particles.push(new explosionParticle()); } var eid = setInterval(function () { showExplosion(canvas, particles, true); }, 40); setTimeout(function () { clearInterval(eid); if (!tGrid.hasAttribute("sunk")) { var hc = parseInt(tGrid.getAttribute("hit_count")); if (hc <= 1) { var canvas = tGrid.firstElementChild; var particles = []; var particle_count = 8; for (var i = 0; i < particle_count; i++) { particles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showSmoke(canvas, particles, true); }, 40); } else { var id = setInterval(function () { showSmoke(canvas, particles, false); }, 40); } tGrid.setAttribute("effectId", id); } else { //clear the old effect first var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); var canvas = tGrid.firstElementChild; var fireParticles = []; var smokeParticles = []; for (var i = 0; i < 10; i++) { fireParticles.push(new fireParticle()); } for (var i = 0; i < 5; i++) { smokeParticles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, true); }, 40); } else { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, false); }, 40); } tGrid.setAttribute("effectId", id); } } }, 1200); //see if we sunk it if (shipDestroyed("monitorLeft", x, y)) { var tx = parseInt(tGrid.getAttribute("head-x")); var ty = parseInt(tGrid.getAttribute("head-y")); var tclass = parseInt(tGrid.getAttribute("ship-class")); var tbearing = parseInt(tGrid.getAttribute("ship-bearing")); //mark the ships as destroyed var ship_size; switch (tclass) { case SHIP_CLASS_BB: ship_size = 4; player_1_ships_count[SHIP_CLASS_BB] = player_1_ships_count[SHIP_CLASS_BB] - 1; break; case SHIP_CLASS_CV: ship_size = 4; player_1_ships_count[SHIP_CLASS_CV] = player_1_ships_count[SHIP_CLASS_CV] - 1; break; case SHIP_CLASS_CA: ship_size = 3; player_1_ships_count[SHIP_CLASS_CA] = player_1_ships_count[SHIP_CLASS_CA] - 1; break; case SHIP_CLASS_DD: ship_size = 2; player_1_ships_count[SHIP_CLASS_DD] = player_1_ships_count[SHIP_CLASS_DD] - 1; break; } refreshPlayerPanel(); if (tbearing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorLeft").querySelector("[x='" + (tx + i) + "'][y='" + ty + "']"); Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.setAttribute("sunk", "true"); } } else if (tbearing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorLeft").querySelector("[y='" + (ty + i) + "'][x='" + tx + "']"); Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.setAttribute("sunk", "true"); } } } onAttackResult(true); if (SOUND_ENABLED) { attack_hit_sound.play(); setTimeout(function () { if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, attack_hit_sound.duration * 1000 + 800); } else { setTimeout(function () { clearInterval(sid); if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, 1200); } } else { var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 340; i++) { particles.push(new waterParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var sid = setInterval(function () { showWaterSplash(canvas, particles, true); }, 60); } else { var sid = setInterval(function () { showWaterSplash(canvas, particles, false); }, 60); } onAttackResult(false); if (SOUND_ENABLED) { attack_miss_sound.play(); setTimeout(function () { clearInterval(sid); if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, attack_miss_sound.duration * 1000 + 800); } else { setTimeout(function () { clearInterval(sid); if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, 3000); } } } } //effects when a ship is hit //TODO maybe putting these into a separate "game-graphic.js" file? function showSmoke(canvas, particleList, hBearing) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "source-over"; if (hBearing == true) { //rotate the context ctx.translate(canvas.width / 2, canvas.height / 2); ctx.rotate(Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); } ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleList.length; i++) { var p = particleList[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100; var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); gradient.addColorStop(0, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(0.5, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; if (p.remaining_life < 0) { particleList[i] = new smokeParticle(); } } } function showFire(canvas, particleListFire, particleListSmoke, hBearing) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "source-over"; if (hBearing == true) { //rotate the context ctx.translate(canvas.width / 2, canvas.height / 2); //move to origin first so it rotate along the center ctx.rotate(Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); //move it back } ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleListFire.length; i++) { var p = particleListFire[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100 var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); gradient.addColorStop(0, "rgba(" + p.colorStop1.r + ", " + p.colorStop1.g + ", " + p.colorStop1.b + ", " + p.opacity + ")"); gradient.addColorStop(0.4, "rgba(" + p.colorStop2.r + ", " + p.colorStop2.g + ", " + p.colorStop2.b + ", " + p.opacity + ")"); gradient.addColorStop(0.6, "rgba(" + p.colorStop3.r + ", " + p.colorStop3.g + ", " + p.colorStop3.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.colorStop1.r + ", " + p.colorStop1.g + ", " + p.colorStop1.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; if (p.remaining_life < 0) { particleListFire[i] = new fireParticle(); } } for (var i = 0; i < particleListSmoke.length; i++) { var p = particleListSmoke[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100; var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); //TODO better effects by randomizing the colorstop size gradient.addColorStop(0, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(0.5, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; if (p.remaining_life < 0) { particleListSmoke[i] = new smokeParticle(); } } } function showExplosion(canvas, particleListFire) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "lighter"; ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleListFire.length; i++) { var p = particleListFire[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100; var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); gradient.addColorStop(0, "rgba(" + p.colorStop1.r + ", " + p.colorStop1.g + ", " + p.colorStop1.b + ", " + p.opacity + ")"); gradient.addColorStop(0.4, "rgba(" + p.colorStop2.r + ", " + p.colorStop2.g + ", " + p.colorStop2.b + ", " + p.opacity + ")"); gradient.addColorStop(0.6, "rgba(" + p.colorStop3.r + ", " + p.colorStop3.g + ", " + p.colorStop3.b + ", " + p.opacity + ")"); gradient.addColorStop(0.8, "rgba(" + p.colorStop4.r + ", " + p.colorStop4.g + ", " + p.colorStop4.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.colorStop4.r + ", " + p.colorStop4.g + ", " + p.colorStop4.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; } } function showWaterSplash(canvas, particleListWater, hBearing) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "source-over"; if (hBearing == true) { //rotate the context ctx.translate(canvas.width / 2, canvas.height / 2); ctx.rotate(Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); } ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleListWater.length; i++) { var p = particleListWater[i]; ctx.beginPath(); ctx.fillStyle = "rgb(" + p.color.r + ", " + p.color.g + ", " + p.color.b + ")"; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.location.x += p.speed.x; p.location.y += p.speed.y; p.speed.y = p.speed.y - p.gravityPull; } } function smokeParticle() { this.speed = { x: -0.5 + Math.random() * 1, y: -2 + Math.random() * 2 }; this.location = { x: grid_size / 2, y: grid_size / 2 }; this.radius = 9; this.life = 18 + Math.random() * 5; this.remaining_life = this.life; var cc = Math.round(60 + Math.random() * 40); this.r = cc; this.g = cc; this.b = cc; } function fireParticle() { this.speed = { x: -0.7 + Math.random() * 1, y: -0.5 + Math.random() * 0.5 }; this.location = { x: grid_size / 2, y: grid_size / 2 }; this.radius = 8; this.life = 8 + Math.random() * 3; this.remaining_life = this.life; this.colorStop1 = { r: 255, g: 255, b: 255 }; this.colorStop2 = { r: 255, g: 255, b: Math.round(200 + Math.random() * 30) }; this.colorStop3 = { r: 255, g: 235, b: Math.round(90 + Math.random() * 30) }; } function explosionParticle() { this.speed = { x: -0.5 + Math.random() * 1, y: -0.5 + Math.random() * 1 }; this.location = { x: grid_size / 2, y: grid_size / 2 }; this.radius = 8; this.life = 15 + Math.random() * 5; this.remaining_life = this.life; this.colorStop1 = { r: 255, g: 255, b: 255 }; this.colorStop2 = { r: 255, g: 255, b: Math.round(200 + Math.random() * 30) }; this.colorStop3 = { r: 255, g: 235, b: Math.round(90 + Math.random() * 30) }; this.colorStop4 = { r: 255, g: 204, b: Math.round(0 + Math.random() * 10) }; } function waterParticle() { this.speed = { x: (-0.25 + Math.random() * 0.5) / DEFAULT_GRID_SIZE * grid_size, y: (-2.5 + Math.random() * 3) / DEFAULT_GRID_SIZE * grid_size }; this.gravityPull = -0.2; this.location = { x: grid_size / 2 - 1.5 + Math.random() * (3 / DEFAULT_GRID_SIZE * grid_size), y: grid_size - 1 }; this.radius = 1; this.color = { r: 160, g: 210, b: Math.round(200 + Math.random() * 30) }; } function clearCanvas(canvas) { var ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, grid_size, grid_size); } //given a coordinate, check if the ship is destroyed. function shipDestroyed(map, x, y) { var tGrid = document.getElementById(map).querySelector("[y='" + y + "'][x='" + x + "']"); var tx = parseInt(tGrid.getAttribute("head-x")); var ty = parseInt(tGrid.getAttribute("head-y")); var sClass = parseInt(tGrid.getAttribute("ship-class")); var bearing = parseInt(tGrid.getAttribute("ship-bearing")); var ship_size; var criticalDamage; switch (sClass) { case SHIP_CLASS_BB: ship_size = 4; if (game_mode == GAME_MODE_CLASSIC) { criticalDamage = 1; } else { criticalDamage = 2; } break; case SHIP_CLASS_CV: ship_size = 4; criticalDamage = 1; break; case SHIP_CLASS_CA: ship_size = 3; criticalDamage = 1; break; case SHIP_CLASS_DD: ship_size = 2; criticalDamage = 1; break; case SHIP_CLASS_AP: ship_size = 3; criticalDamage = 1; break; } if (bearing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById(map).querySelector("[x='" + (tx + i) + "'][y='" + ty + "']"); if (Grid.hasAttribute("hit_count")) { if (parseInt(Grid.getAttribute("hit_count")) >= criticalDamage) { if (i == (ship_size - 1)) { return true; } } else { return false; } } else { return false; } } } else if (bearing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById(map).querySelector("[y='" + (ty + i) + "'][x='" + tx + "']"); if (Grid.hasAttribute("hit_count")) { if (parseInt(Grid.getAttribute("hit_count")) >= criticalDamage) { if (i == (ship_size - 1)) { return true; } } else { return false; } } else { return false; } } } } function lockOnSector(evt) { var targetGrid = evt.target; var sIcon = document.createElement('img'); sIcon.setAttribute('src', img_url.crosshair); sIcon.setAttribute('class', "Crosshair"); targetGrid.appendChild(sIcon); } function unLockOnSector(evt) { var targetGrid = evt.target; if (targetGrid.childNodes[targetGrid.childNodes.length - 1].getAttribute("class") == "Crosshair") { targetGrid.removeChild(targetGrid.childNodes[targetGrid.childNodes.length - 1]); } } function stopTargeting() { hideActionPrompt(); document.getElementById("counterLeft").innerHTML = getPlayerShipCount(PLAYER_1); document.getElementById("counterLabelLeft").innerHTML = string.ship_placement_remaining; var grids = document.getElementById("monitorRight").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', fire, false); grids[i].removeEventListener('mouseover', lockOnSector, false); //grids[i].removeEventListener('mouseout', unLockOnSector, false); } } function promptAction() { var ap; if (acting_player == PLAYER_1) { document.getElementById("apRight").style.visibility = "visible"; } else { document.getElementById("apLeft").style.visibility = "visible"; } } function hideActionPrompt() { if (acting_player == PLAYER_1) { document.getElementById("apRight").style.visibility = "hidden"; } else { document.getElementById("apLeft").style.visibility = "hidden"; } } //refredh the number of ship displayed for player function refreshPlayerPanel() { document.getElementById("counterLeft").innerHTML = getPlayerShipCount(PLAYER_1); var labels = document.getElementById("dataPanelContentLeft").querySelectorAll('.ShipClassLabel'); for (var i = 0; i < labels.length; i++) { switch (i) { case SHIP_CLASS_BB: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_BB]; break; case SHIP_CLASS_CV: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_CV]; break; case SHIP_CLASS_CA: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_CA]; break; case SHIP_CLASS_DD: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_DD]; break; } } } function refreshEnemyPanel() { document.getElementById("counterRight").innerHTML = getPlayerShipCount(PLAYER_2); var labels = document.getElementById("dataPanelContentRight").querySelectorAll('.ShipClassLabel'); for (var i = 0; i < labels.length; i++) { switch (i) { case SHIP_CLASS_BB: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_BB]; break; case SHIP_CLASS_CV: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_CV]; break; case SHIP_CLASS_CA: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_CA]; break; case SHIP_CLASS_DD: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_DD]; break; } } } function nextPlayer() { if (gameEnded()) { refreshPlayerPanel(); refreshEnemyPanel(); hideActionPrompt(); var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.new_game; mainButton.removeEventListener('click', surrender, false); mainButton.addEventListener('click', newGame, false); } else if (acting_player == PLAYER_1) { hideActionPrompt(); acting_player = PLAYER_2; promptAction(); switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_CONVOY: case GAME_MODE_BREAKTHROUGH: if (game_phase == GAME_PAHSE_AERIAL_COMBAT) { player_1_acted = true; player_2_attack_count = player_2_ships_count[SHIP_CLASS_CV] * 2; if (player_2_attack_count > 0 && !player_2_acted) { attackMain(); } else { //well both acted. let's move to next stage. startFleetCombat(); } } else if (game_phase == GAME_PHASE_COMBAT) { if (!player_2_first_act_complete) { if (player_2_turn_counter >= getPlayerShipCount(PLAYER_2)) { player_2_first_act_complete = true; } if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_2_attack_count = BB_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_BB]) { //the opponent still have BBs yet.skip this turn directly. nextPlayer(); } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_2_attack_count = CA_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } else { //extra code for cCA under t-dis(0 atk chance) player_2_turn_counter = player_2_turn_counter + 1; nextPlayer(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_2_attack_count = DD_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } else { //extra code for cCA under t-dis(0 atk chance) player_2_turn_counter = player_2_turn_counter + 1; nextPlayer(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CV] + player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_2_attack_count = CV_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CV] + player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else { nextPlayer(); } } else { if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_2_attack_count = BB_ATTACK_COUNT[player_2_engagement_form]; } else if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_2_attack_count = CA_ATTACK_COUNT[player_2_engagement_form]; } else if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_2_attack_count = DD_ATTACK_COUNT[player_2_engagement_form]; } else if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_CV] + player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_2_attack_count = CV_ATTACK_COUNT[player_2_engagement_form]; } player_2_turn_counter = player_2_turn_counter + 1; if (player_2_turn_counter > getPlayerShipCount(PLAYER_2) - player_2_ships_count[SHIP_CLASS_AP]) { player_2_acted = true; } if (player_2_acted && player_1_acted) { player_2_turn_counter = 0; player_1_turn_counter = 0; total_turn_counter = total_turn_counter + 1; if (game_mode == GAME_MODE_INTERCEPT || game_mode == GAME_MODE_CONVOY || game_mode == GAME_MODE_BREAKTHROUGH) { updateTurnCounter(); } player_2_acted = false; player_1_acted = false; } if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } } } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_2) > 0) { player_2_attack_count = 1; } if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } else { nextPlayer(); } break; } } else { hideActionPrompt(); acting_player = PLAYER_1; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_CONVOY: case GAME_MODE_BREAKTHROUGH: if (game_phase == GAME_PAHSE_AERIAL_COMBAT) { player_2_acted = true; player_1_attack_count = player_1_ships_count[SHIP_CLASS_CV] * 2; if (player_1_attack_count > 0 && !player_1_acted) { beginTargeting(); } else { startFleetCombat(); } } else if (game_phase == GAME_PHASE_COMBAT) { if (!player_1_first_act_complete) { if (player_1_turn_counter >= getPlayerShipCount(PLAYER_1) - player_1_ships_count[SHIP_CLASS_AP]) { player_1_first_act_complete = true; } if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_1_attack_count = BB_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_BB]) { //the opponent still have BBs yet.skip this turn directly. nextPlayer(); } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_1_attack_count = CA_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { //extra code for CA under t-dis(0 atk chance) player_1_turn_counter = player_1_turn_counter + 1; nextPlayer(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_1_attack_count = DD_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { //extra code for DD under t-dis(0 atk chance) player_1_turn_counter = player_1_turn_counter + 1; nextPlayer(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CV] + player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_1_attack_count = CV_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CV] + player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else { nextPlayer(); } } else { if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_1_attack_count = BB_ATTACK_COUNT[player_1_engagement_form]; } else if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_1_attack_count = CA_ATTACK_COUNT[player_1_engagement_form]; } else if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_1_attack_count = DD_ATTACK_COUNT[player_1_engagement_form]; } else if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_CV] + player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_1_attack_count = CV_ATTACK_COUNT[player_1_engagement_form]; } player_1_turn_counter = player_1_turn_counter + 1; if (player_1_turn_counter > getPlayerShipCount(PLAYER_1) - player_1_ships_count[SHIP_CLASS_AP]) { player_1_acted = true; } if (player_2_acted && player_1_acted) { player_2_turn_counter = 0; player_1_turn_counter = 0; total_turn_counter = total_turn_counter + 1; if (game_mode == GAME_MODE_INTERCEPT || game_mode == GAME_MODE_CONVOY || game_mode == GAME_MODE_BREAKTHROUGH) { updateTurnCounter(); } player_2_acted = false; player_1_acted = false; } if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } } } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_1) > 0) { player_1_attack_count = 1; } if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { nextPlayer(); } break; } } } function updateTurnCounter() { document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); } function gameEnded() { //see if any one fleet lose all their ships if (getPlayerShipCount(PLAYER_1) <= 0) { //TODO maybe using graphics to display the dialog? showEndGameDialog(string.defeat, string.defeat_description_standard); return true; } else if (getPlayerShipCount(PLAYER_2) <= 0) { showEndGameDialog(string.victory, string.victory_description_standard); return true; } else if (game_mode == GAME_MODE_INTERCEPT) { if (total_turn_counter >= max_turn_intercept_breakthrough) { showEndGameDialog(string.defeat, string.defeat_description_intercept); return true; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_2_ships_count[ship_class_target] <= 0) { showEndGameDialog(string.victory, string.victory_description_intercept); return true; } } } else if (game_mode == GAME_MODE_BREAKTHROUGH) { if (total_turn_counter >= max_turn_intercept_breakthrough) { showEndGameDialog(string.victory, string.victory_description_breakthrough); return true; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_1_ships_count[ship_class_target] <= 0) { showEndGameDialog(string.defeat, string.defeat_description_breakthrough); return true; } } } else if (game_mode == GAME_MODE_CONVOY) { if (total_turn_counter >= max_turn_intercept_breakthrough) { showEndGameDialog(string.victory, string.victory_description_convoy); return true; } if (player_1_ships_count[SHIP_CLASS_AP] <= 0) { showEndGameDialog(string.defeat, string.defeat_description_convoy); return true; } //TODO Destruction of marked target } else { return false; } } function showEndGameDialog(title, description) { document.getElementById('EndingTitle').innerHTML = title; document.getElementById('EndingDescription').innerHTML = description; document.getElementById('endGameBox').style.display = "table"; setTimeout(function () { window.onclick = function (event) { document.getElementById('endGameBox').style.display = "none"; } }, 3000); } function surrender(evt) { //TODO replace confirm with html 5 dialog if (confirm(string.surrender_confirm)) { //scuttle all ships to trigger lose effect for (var i = 0; i < player_1_ships_count.length; i++) { player_1_ships_count[i] = 0; } nextPlayer(); } else { //do nothing } } function newGame(evt) { //TODO replace confirm with html 5 dialog if (confirm(string.new_game_confirm)) { location.reload(); } else { //do nothing } }
script/game-core.js
var counter_text_left; var counter_label_left; var counter_text_right; var counter_label_right; var game_phase = 0; var GAME_PHASE_SHIP_PLACEMENT = 0; var GAME_PAHSE_AERIAL_COMBAT = 1; var GAME_PHASE_COMBAT = 2; var grid_size; var map_size; var SHIP_COURSE_VERTICAL = 0; var SHIP_COURSE_HORIZONTAL = 1; var FLEET_SPEED_FAST = 0; var FLEET_SPEED_SLOW = 1; var ENGAGEMENT_FORM_PARALLEL = 0; var ENGAGEMENT_FORM_HEADON = 1; var ENGAGEMENT_FORM_T_ADV = 2; var ENGAGEMENT_FORM_T_DIS = 3; var SHIP_CLASS_BB = 0; var SHIP_CLASS_CV = 1; var SHIP_CLASS_CA = 2; var SHIP_CLASS_DD = 3; var SHIP_CLASS_AP = 4; var max_ship_count; var max_bb_count; var max_cv_count; var max_ca_count; var max_dd_count; var max_ap_count; var ship_class_placing; var ship_course_placing = 0; var ship_size_placing; var ship_class_target; var ship_class_acting; var acting_player; var PLAYER_1 = 0; var PLAYER_2 = 1; var player_1_first_act_complete = false; var player_2_first_act_complete = false; var total_turn_counter = 0; var max_turn_intercept_breakthrough; //game stats field for each player var player_1_ship_set = 0; var player_1_ships_count = [0, 0, 0, 0, 0]; var player_1_fleet_course = 0; var player_1_fleet_speed; var player_1_engagement_form; //Form Of Engagement var player_1_attack_count; var player_1_turn_counter = 0; var player_1_acted = false; var player_2_ship_set = 0; var player_2_ships_count = [0, 0, 0, 0, 0]; var player_2_fleet_course = 0; var player_2_fleet_speed; var player_2_engagement_form; var player_2_attack_count; var player_2_turn_counter = 0; var player_2_acted = false; //SFXs var gun_fire_sound; var plane_attack_sound; var attack_hit_sound; var attack_miss_sound; var attack_hit_sound_distant; /** * Set up the basic ui for the game */ function readyGame() { //load the sound first if (SOUND_ENABLED) { gun_fire_sound = new Audio(sfx_url.gun_fire); plane_attack_sound = new Audio(sfx_url.plane_attack); attack_hit_sound = new Audio(sfx_url.explosion); attack_miss_sound = new Audio(sfx_url.explosion_water); attack_hit_sound_distant = new Audio(sfx_url.explosion_distant); } document.getElementById("gameTitle").innerHTML = string.game_title; //set up the main moniters var monitors = document.querySelectorAll('.Monitor'); if (game_mode == GAME_MODE_CLASSIC) { map_size = 10; grid_size = Math.floor(DEFAULT_GRID_SIZE * DEFAULT_MAP_SIZE / map_size); } else { if (RANDOM_MAP_SIZE) { map_size = RNG(RANDOM_MAP_SIZE_MIN, RANDOM_MAP_SIZE_MAX); grid_size = Math.floor(DEFAULT_GRID_SIZE * DEFAULT_MAP_SIZE / map_size); } else { map_size = DEFAULT_MAP_SIZE; grid_size = DEFAULT_GRID_SIZE; } } if (game_mode == GAME_MODE_INTERCEPT || game_mode == GAME_MODE_BREAKTHROUGH || game_mode == GAME_MODE_CONVOY) { if (RANDOM_TIME_INTERCEPT_BREAKTHROUGH) { max_turn_intercept_breakthrough = RNG(MAX_TURN_INTERCEPT_MIN, MAX_TURN_INTERCEPT_MAX) } else { max_turn_intercept_breakthrough = MAX_TURN_INTERCEPT_DEFAULT; } } for (var i = 0; i < monitors.length; i++) { //set the map size monitors[i].style.width = grid_size * map_size + 2 + "px"; monitors[i].style.height = grid_size * map_size + 2 + "px"; //create a grid of map_size * map_size for (var j = 0; j < map_size; j++) { for (var k = 0; k < map_size; k++) { var grid = document.createElement('div'); grid.style.height = grid_size + 'px'; grid.style.width = grid_size + 'px'; grid.setAttribute('x', j); grid.setAttribute('y', k); grid.setAttribute('class', 'MonitorGrid'); var topPosition = j * grid_size; var leftPosition = k * grid_size; grid.style.top = topPosition + 'px'; grid.style.left = leftPosition + 'px'; var grid_canvas = document.createElement('canvas'); grid_canvas.style.height = grid_size + 'px'; grid_canvas.style.width = grid_size + 'px'; grid_canvas.setAttribute('c-x', j); grid_canvas.setAttribute('c-y', k); grid_canvas.setAttribute('class', 'GridCanvas'); grid_canvas.style.top = topPosition + 'px'; grid_canvas.style.left = leftPosition + 'px'; grid.appendChild(grid_canvas); monitors[i].appendChild(grid); } } } //upper panel document.getElementById("objective").innerHTML = string.game_objective_label; var objective = document.getElementById("objectiveList"); var game_mode_label = document.getElementById("gameModeLabel"); game_mode_label.innerHTML = string.game_mode_label; var game_mode_display = document.getElementById("gameMode"); game_mode_display.innerHTML = string.game_mode[game_mode]; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_BREAKTHROUGH: var o = document.createElement('li'); o.innerHTML = string.game_objective_loading; objective.appendChild(o); max_ship_count = MAX_SHIP_COUNT_STANDARD; max_cv_count = MAX_CV_COUNT_STANDARD; max_bb_count = MAX_BB_COUNT_STANDARD; max_ca_count = MAX_CA_COUNT_STANDARD; max_dd_count = MAX_DD_COUNT_STANDARD; break; case GAME_MODE_CLASSIC: var o = document.createElement('li'); o.innerHTML = string.game_objective_standard; objective.appendChild(o); max_ship_count = MAX_SHIP_COUNT_CLASSIC; max_cv_count = MAX_CV_COUNT_CLASSIC; max_bb_count = MAX_BB_COUNT_CLASSIC; max_ca_count = MAX_CA_COUNT_CLASSIC; max_dd_count = MAX_DD_COUNT_CLASSIC; break; case GAME_MODE_CONVOY: var o = document.createElement('li'); o.innerHTML = string.game_objective_loading; objective.appendChild(o); max_ship_count = MAX_SHIP_COUNT_STANDARD; max_cv_count = MAX_CV_COUNT_STANDARD; max_bb_count = MAX_BB_COUNT_STANDARD; max_ca_count = MAX_CA_COUNT_STANDARD; max_dd_count = MAX_DD_COUNT_STANDARD; max_ap_count = AP_COUNT_CONVOY; break; } //set up the data Panel document.getElementById("dataPanelLeft").style.height = grid_size * map_size + 2 + "px"; document.getElementById("dataPanelRight").style.height = grid_size * map_size + 2 + "px"; //left panel var rButton = document.getElementById('rbutton'); rButton.innerHTML = string.rotate; //rButton.setAttribute('class', 'Button'); rButton.style.display = 'none'; var label = document.createElement('p'); label.innerHTML = string.ship_placement_remaining; label.setAttribute('id', 'counterLabelLeft'); counter_label_left = label; document.getElementById("dataPanelContentLeft").appendChild(label); var counter = document.createElement('p'); counter.innerHTML = max_ship_count; counter.setAttribute('class', 'Counter'); counter.setAttribute('id', 'counterLeft'); counter_text_left = counter; document.getElementById("dataPanelContentLeft").appendChild(counter); //determine the ship iocn set to be used by each player var shipset = RNG(0, 3); player_1_ship_set = shipset; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_BREAKTHROUGH: case GAME_MODE_CLASSIC: for (var i = 0; i <= SHIP_CLASS_DD; i++) { var sLabel = document.createElement('p'); sLabel.setAttribute('class', 'ShipClassLabel'); sLabel.innerHTML = string.ship_classes[i]; document.getElementById("dataPanelContentLeft").appendChild(sLabel); var sIcon = document.createElement('img'); var classes; switch (i) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: classes = 'ShipIcons'; break; case SHIP_CLASS_CA: classes = 'ShipIcons ShipIconsCA'; break; case SHIP_CLASS_DD: classes = 'ShipIcons ShipIconsDD'; break; } sIcon.setAttribute('class', classes); sIcon.setAttribute('id', i); sIcon.setAttribute('src', img_url.ship_icons[player_1_ship_set][i]); document.getElementById("dataPanelContentLeft").appendChild(sIcon); } break; case GAME_MODE_CONVOY: for (var i = 0; i <= SHIP_CLASS_AP; i++) { var sLabel = document.createElement('p'); sLabel.setAttribute('class', 'ShipClassLabel'); sLabel.innerHTML = string.ship_classes[i]; document.getElementById("dataPanelContentLeft").appendChild(sLabel); var sIcon = document.createElement('img'); var classes; switch (i) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: classes = 'ShipIcons'; break; case SHIP_CLASS_CA: classes = 'ShipIcons ShipIconsCA'; break; case SHIP_CLASS_DD: classes = 'ShipIcons ShipIconsDD'; break; case SHIP_CLASS_AP: classes = 'ShipIcons ShipIconsCA'; break; } sIcon.setAttribute('class', classes); sIcon.setAttribute('id', i); sIcon.setAttribute('src', img_url.ship_icons[player_1_ship_set][i]); document.getElementById("dataPanelContentLeft").appendChild(sIcon); } break; } document.getElementById("apLeft").innerHTML = string.action_prompt_enemy; //right Panel var label2 = document.createElement('p'); label2.innerHTML = string.ship_placement_remaining; counter_label_right = label2; document.getElementById("dataPanelContentRight").appendChild(label2); var counter2 = document.createElement('p'); counter2.innerHTML = max_ship_count; counter2.setAttribute('class', 'Counter'); counter2.setAttribute('id', 'counterRight'); counter_text_right = counter2; document.getElementById("dataPanelContentRight").appendChild(counter2); //use a different ship icon set than player 1 while (player_2_ship_set == player_1_ship_set) { var shipset = RNG(0, 2); player_2_ship_set = shipset; } for (var i = 0; i <= SHIP_CLASS_DD; i++) { var sLabel2 = document.createElement('p'); sLabel2.setAttribute('class', 'ShipClassLabel'); sLabel2.innerHTML = string.ship_classes[i]; document.getElementById("dataPanelContentRight").appendChild(sLabel2); var sIcon2 = document.createElement('img'); var classes; switch (i) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: classes = 'ShipIconsEnemy ShipIcons'; break; case SHIP_CLASS_CA: classes = 'ShipIconsEnemy ShipIcons ShipIconsCA'; break; case SHIP_CLASS_DD: classes = 'ShipIconsEnemy ShipIcons ShipIconsDD'; break; } sIcon2.setAttribute('class', classes); sIcon2.setAttribute('src', img_url.ship_icons[player_2_ship_set][i]); document.getElementById("dataPanelContentRight").appendChild(sIcon2); } document.getElementById("apRight").innerHTML = string.action_prompt_player; //main button var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.assemble_fleet; mainButton.addEventListener('click', startShipPlacement, false); //show all stuff document.getElementById("content").style.visibility = "visible"; document.getElementById('settingBox').style.display = "none"; } function startShipPlacement() { //hide the panel for player 2 first document.getElementById("dataPanelContentRight").style.display = 'none'; var p = document.createElement('p'); p.innerHTML = string.pending; p.setAttribute('class', 'DataPanelOverlay'); p.setAttribute('id', 'pending'); document.getElementById("dataPanelRight").appendChild(p); //add onclicklistener for the ship icons var ships = document.getElementById("dataPanelContentLeft").querySelectorAll('.ShipIcons'); for (var i = 0; i < ships.length; i++) { var classes = ships[i].getAttribute('class'); classes = classes + " ShipIconsSelectable"; ships[i].setAttribute('class', classes); } var ships = document.querySelectorAll('.ShipIconsSelectable'); for (var i = 0; i < ships.length; i++) { var t = i; ships[i].addEventListener("click", onShipIconSelected, false); } document.getElementById('rbutton').addEventListener('click', function () { if (ship_course_placing == SHIP_COURSE_VERTICAL) { ship_course_placing = SHIP_COURSE_HORIZONTAL; } else { ship_course_placing = SHIP_COURSE_VERTICAL; } }, false); //prepare button for next page var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.start_battle; mainButton.removeEventListener('click', startShipPlacement, false); mainButton.addEventListener('click', startGame, false); } function onShipIconSelected(evt) { ship_class_placing = parseInt(evt.target.id); //set eventlistener for all the moniter grids var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].addEventListener('click', placeShip, false); grids[i].addEventListener('mouseover', projectShip, false); grids[i].addEventListener('mouseout', unProjectShip, false); grids[i].addEventListener('contextmenu', changeShipCourse, false); } window.oncontextmenu = function () { return false; }; document.getElementById("rbutton").style.display = 'inline'; } /** * Check if a ship can be placed in the given coordinate */ function shipPlaceable(x, y) { switch (ship_class_placing) { case SHIP_CLASS_BB: case SHIP_CLASS_CV: ship_size_placing = 4; break; case SHIP_CLASS_CA: case SHIP_CLASS_AP: ship_size_placing = 3; break; case SHIP_CLASS_DD: ship_size_placing = 2; break; } if (ship_course_placing == SHIP_COURSE_VERTICAL) { //check if over edge of map if ((x + ship_size_placing) <= map_size && y <= map_size) { //check if another ship already exist for (var i = 0; i < ship_size_placing; i++) { if (document.querySelector("[x='" + (x + i) + "'][y='" + y + "']").hasAttribute("placed")) { return false; } } return true; } else { return false; } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { if ((y + ship_size_placing) <= map_size && x <= map_size) { for (var i = 0; i < ship_size_placing; i++) { if (document.querySelector("[y='" + (y + i) + "'][x='" + x + "']").hasAttribute("placed")) { return false; } } return true; } else { return false; } } } /** * creates a "projection" of a ship on the moniter to indicate this is possible to place a ship */ function projectShip(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (shipPlaceable(targetX, targetY)) { if (ship_course_placing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[x='" + (targetX + i) + "'][y='" + targetY + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[y='" + (targetY + i) + "'][x='" + targetX + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; tGrid.classList.add("ShipsTileHorizontal"); } } } } /** * remove the ship projection left by player */ function unProjectShip(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (shipPlaceable(targetX, targetY)) { if (ship_course_placing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[x='" + (targetX + i) + "'][y='" + targetY + "']"); tGrid.style.backgroundImage = ""; } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[y='" + (targetY + i) + "'][x='" + targetX + "']"); tGrid.style.backgroundImage = ""; tGrid.classList.remove("ShipsTileHorizontal"); } } } } function changeShipCourse(evt) { unProjectShip(evt); if (ship_course_placing == SHIP_COURSE_VERTICAL) { ship_course_placing = SHIP_COURSE_HORIZONTAL; } else { ship_course_placing = SHIP_COURSE_VERTICAL; } projectShip(evt); } function placeShip(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (shipPlaceable(targetX, targetY)) { if (ship_course_placing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[x='" + (targetX + i) + "'][y='" + targetY + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; var classes = tGrid.getAttribute('class'); classes = classes + " ShipsTile"; tGrid.setAttribute('class', classes); tGrid.setAttribute("placed", "true"); tGrid.setAttribute("ship-class", ship_class_placing); tGrid.setAttribute("ship-bearing", ship_course_placing); tGrid.setAttribute("sector", i); tGrid.setAttribute("head-x", targetX); tGrid.setAttribute("head-y", targetY); tGrid.style.backgroundColor = ''; tGrid.removeEventListener('click', placeShip, false); tGrid.removeEventListener('mouseover', projectShip, false); tGrid.removeEventListener('mouseout', unProjectShip, false); } } else if (ship_course_placing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size_placing; i++) { var tGrid = document.querySelector("[y='" + (targetY + i) + "'][x='" + targetX + "']"); tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[ship_class_placing][0][i] + "')"; var classes = tGrid.getAttribute('class'); classes = classes + " ShipsTileHorizontal"; tGrid.setAttribute('class', classes); tGrid.removeEventListener('click', placeShip, false); tGrid.setAttribute("placed", "true"); tGrid.setAttribute("ship-class", ship_class_placing); tGrid.setAttribute("ship-bearing", ship_course_placing); tGrid.setAttribute("sector", i); tGrid.setAttribute("head-x", targetX); tGrid.setAttribute("head-y", targetY); tGrid.style.backgroundColor = ''; tGrid.removeEventListener('mouseover', projectShip, false); tGrid.removeEventListener('mouseout', unProjectShip, false); } } player_1_fleet_course = player_1_fleet_course + ship_course_placing; document.getElementById("counterLeft").innerHTML = parseInt(counter_text_left.innerHTML) - 1; //check for ship class limit switch (ship_class_placing) { case SHIP_CLASS_BB: player_1_ships_count[SHIP_CLASS_BB] = player_1_ships_count[SHIP_CLASS_BB] + 1; if (player_1_ships_count[SHIP_CLASS_BB] >= max_bb_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); //stops player from placing more ships for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_CV: player_1_ships_count[SHIP_CLASS_CV] = player_1_ships_count[SHIP_CLASS_CV] + 1; if (player_1_ships_count[SHIP_CLASS_CV] >= max_cv_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_CA: player_1_ships_count[SHIP_CLASS_CA] = player_1_ships_count[SHIP_CLASS_CA] + 1; if (player_1_ships_count[SHIP_CLASS_CA] >= max_ca_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_DD: player_1_ships_count[SHIP_CLASS_DD] = player_1_ships_count[SHIP_CLASS_DD] + 1; if (player_1_ships_count[SHIP_CLASS_DD] >= max_dd_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; case SHIP_CLASS_AP: player_1_ships_count[SHIP_CLASS_AP] = player_1_ships_count[SHIP_CLASS_AP] + 1; if (player_1_ships_count[SHIP_CLASS_AP] >= max_ap_count) { var ships = document.querySelectorAll('.ShipIcons'); var classes = ships[ship_class_placing].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); ships[ship_class_placing].setAttribute('class', classes); ships[ship_class_placing].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } break; } if (getPlayerShipCount(PLAYER_1) >= max_ship_count) { stopPlayerShipPlacement(); } //enforce total number of transports if (game_mode == GAME_MODE_CONVOY) { if ((max_ship_count - getPlayerShipCount(PLAYER_1)) <= (max_ap_count - player_1_ships_count[SHIP_CLASS_AP]) && getPlayerShipCount(PLAYER_1) < max_ship_count && ship_class_placing != SHIP_CLASS_AP) { var allShips = document.querySelectorAll('.ShipIcons'); for (var n = 0; n < allShips.length; n++) { if (n != SHIP_CLASS_AP) { var c = allShips[n].getAttribute('class'); c = c.replace(' ShipIconsSelectable', ' ShipIconsUnSelectable'); allShips[n].setAttribute('class', c); allShips[n].removeEventListener("click", onShipIconSelected, false); var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var m = 0; m < grids.length; m++) { grids[m].removeEventListener('click', placeShip, false); grids[m].removeEventListener('mouseover', projectShip, false); grids[m].removeEventListener('mouseout', unProjectShip, false); grids[i].removeEventListener('contextmenu', changeShipCourse, false); } document.getElementById("rbutton").style.display = 'none'; } } } } } } /** * end the ship placing and prompt ai to place ship if possible */ function stopPlayerShipPlacement() { //disable ship selector var ships = document.querySelectorAll('.ShipIcons'); window.oncontextmenu = function () { return true; }; for (var i = 0; i < ships.length; i++) { var t = i; ships[i].removeEventListener("click", onShipIconSelected, false); //remove hover effect var classes = ships[i].getAttribute('class'); classes = classes.replace(' ShipIconsSelectable', ''); classes = classes.replace(' ShipIconsUnSelectable', ''); ships[i].setAttribute('class', classes); } //disable grids var grids = document.getElementById("monitorLeft").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', placeShip, false); grids[i].removeEventListener('mouseover', projectShip, false); grids[i].removeEventListener('mouseout', unProjectShip, false); } //delete the button if it still exsists if (document.getElementById("rbutton") != null) { var button = document.getElementById("rbutton"); button.parentNode.removeChild(button); } if (getPlayerShipCount(PLAYER_2) < max_ship_count) { shipPlacementMain(); } } function getPlayerShipCount(player) { if (player == PLAYER_1) { return player_1_ships_count.reduce(function (a, b) { return a + b; }, 0); } else { return player_2_ships_count.reduce(function (a, b) { return a + b; }, 0); } } function startGame() { if (getPlayerShipCount(PLAYER_1) <= 0) { //TODO change this to html overl;ay dialog alert(string.no_ship_prompt); } else if (game_mode == GAME_MODE_CONVOY && player_1_ships_count[SHIP_CLASS_AP] < max_ap_count) { alert(string.no_ap_prompt); } else { stopPlayerShipPlacement(); //just in case var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.surrender; mainButton.removeEventListener('click', startGame, false); mainButton.addEventListener('click', surrender, false); //display info for both players var labels = document.getElementById("dataPanelContentLeft").querySelectorAll('.ShipClassLabel'); for (var i = 0; i < labels.length; i++) { labels[i].innerHTML = labels[i].innerHTML + " : " + player_1_ships_count[i]; } document.getElementById("counterLeft").innerHTML = getPlayerShipCount(PLAYER_1); //player 2 //unhide the panel document.getElementById("dataPanelContentRight").style.display = ''; var overlay = document.getElementById('pending'); overlay.parentNode.removeChild(overlay); var labels = document.getElementById("dataPanelContentRight").querySelectorAll('.ShipClassLabel'); if (!FOG_OF_WAR) { //show number of enemy ships by class for (var i = 0; i < labels.length; i++) { labels[i].innerHTML = labels[i].innerHTML + " : " + player_2_ships_count[i]; } } else { for (var i = 0; i < labels.length; i++) { labels[i].innerHTML = labels[i].innerHTML + " : " + "???"; } } document.getElementById("counterRight").innerHTML = getPlayerShipCount(PLAYER_2); switch (game_mode) { case GAME_MODE_SKIRMISH: //calculate the stats for each fleet //speed if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); o.innerHTML = string.game_objective_standard; objective.innerHTML = ""; objective.appendChild(o); aerialCombat(); break; case GAME_MODE_INTERCEPT: //ditto if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_2_ships_count[SHIP_CLASS_CV] > 0 && player_2_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = RNG(SHIP_CLASS_BB, SHIP_CLASS_CV); } else if (player_2_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = SHIP_CLASS_BB; } else if (player_2_ships_count[SHIP_CLASS_CV] > 0) { ship_class_target = SHIP_CLASS_CV; } else { //nothing of interest. SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH = false;//kill'em all. } } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (ship_class_target == SHIP_CLASS_BB) { o.innerHTML = string.game_objective_intercept_bb; } else { o.innerHTML = string.game_objective_intercept_cv; } } else { o.innerHTML = string.game_objective_standard; } objective.innerHTML = ""; objective.appendChild(o); document.getElementById("TurnCounterField").style.visibility = "visible"; document.getElementById("TurnCounterLabel").innerHTML = string.turn_counter_label; document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); aerialCombat(); break; case GAME_MODE_BREAKTHROUGH: //ditto if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_1_ships_count[SHIP_CLASS_CV] > 0 && player_1_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = RNG(SHIP_CLASS_BB, SHIP_CLASS_CV); } else if (player_1_ships_count[SHIP_CLASS_BB] > 0) { ship_class_target = SHIP_CLASS_BB; } else if (player_1_ships_count[SHIP_CLASS_CV] > 0) { ship_class_target = SHIP_CLASS_CV; } else { //nothing of interest. SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH = false;//kill'em all. } } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (ship_class_target == SHIP_CLASS_BB) { o.innerHTML = string.game_objective_breakthrough_bb; } else { o.innerHTML = string.game_objective_breakthrough_cv } } else { o.innerHTML = string.game_objective_breakthrough; } objective.innerHTML = ""; objective.appendChild(o); document.getElementById("TurnCounterField").style.visibility = "visible"; document.getElementById("TurnCounterLabel").innerHTML = string.turn_counter_label; document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); aerialCombat(); break; case GAME_MODE_CONVOY: //ditto if (player_1_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_speed = FLEET_SPEED_SLOW; } else { player_1_fleet_speed = FLEET_SPEED_FAST; } if (player_2_ships_count[SHIP_CLASS_BB] >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_speed = FLEET_SPEED_SLOW; } else { player_2_fleet_speed = FLEET_SPEED_FAST; } //course if (player_1_fleet_course >= Math.round(getPlayerShipCount(PLAYER_1) / 2)) { player_1_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_1_fleet_course = SHIP_COURSE_VERTICAL; } if (player_2_fleet_course >= Math.round(getPlayerShipCount(PLAYER_2) / 2)) { player_2_fleet_course = SHIP_COURSE_HORIZONTAL; } else { player_2_fleet_course = SHIP_COURSE_VERTICAL; } var objective = document.getElementById("objectiveList"); var o = document.createElement('li'); o.innerHTML = string.game_objective_convoy; objective.innerHTML = ""; objective.appendChild(o); document.getElementById("TurnCounterField").style.visibility = "visible"; document.getElementById("TurnCounterLabel").innerHTML = string.turn_counter_label; document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); aerialCombat(); break; case GAME_MODE_CLASSIC: //DO NOTHING //no aerial combat, too. startFleetCombat(); break; } } } /** * start the aerial combat phase */ function aerialCombat() { game_phase = GAME_PAHSE_AERIAL_COMBAT; ship_class_acting = SHIP_CLASS_CV; document.getElementById("stage").innerHTML = string.game_stage_aerial; //determine who will go first var first = RNG(PLAYER_1, PLAYER_2); if (first == PLAYER_1) { acting_player = PLAYER_1; promptAction(); player_1_attack_count = player_1_ships_count[SHIP_CLASS_CV] * 2; if (player_1_attack_count > 0) { beginTargeting(); } else { //no CVs nextPlayer(); } } else { acting_player = PLAYER_2; promptAction(); player_2_attack_count = player_2_ships_count[SHIP_CLASS_CV] * 2; if (player_2_attack_count > 0) { attackMain(); } else { //no CVs nextPlayer(); } } } function startFleetCombat() { game_phase = GAME_PHASE_COMBAT; document.getElementById("stage").innerHTML = string.game_stage_artillery; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_BREAKTHROUGH: case GAME_MODE_CONVOY: //first decide the engagement form if (player_1_fleet_course == player_2_fleet_course) { player_1_engagement_form = RNG(ENGAGEMENT_FORM_PARALLEL, ENGAGEMENT_FORM_HEADON); player_2_engagement_form = player_1_engagement_form; } else { if (player_1_fleet_speed != player_2_fleet_speed) { if (player_1_fleet_speed == FLEET_SPEED_SLOW) { player_1_engagement_form = ENGAGEMENT_FORM_T_DIS; player_2_engagement_form = ENGAGEMENT_FORM_T_ADV; } else if (player_2_fleet_speed == FLEET_SPEED_SLOW) { player_1_engagement_form = ENGAGEMENT_FORM_T_ADV; player_2_engagement_form = ENGAGEMENT_FORM_T_DIS; } } else { player_1_engagement_form = RNG(ENGAGEMENT_FORM_T_ADV, ENGAGEMENT_FORM_T_DIS); if (player_1_engagement_form == ENGAGEMENT_FORM_T_DIS) { player_2_engagement_form = ENGAGEMENT_FORM_T_ADV; } else { player_2_engagement_form = ENGAGEMENT_FORM_T_DIS; } } } break; case GAME_MODE_CLASSIC: //DO NOTHING break; } //TODO sound fx and animation if (!FOG_OF_WAR) { document.getElementById("FoELabel").innerHTML = string.form_of_engagement_label; document.getElementById("FoE").innerHTML = string.form_of_engagement[player_1_engagement_form]; } player_1_acted = false; player_2_acted = false; //determine who will go first var first = RNG(PLAYER_1, PLAYER_2); if (first == PLAYER_1) { acting_player = PLAYER_1; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: //let's see what type of ships we have. if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_1_attack_count = BB_ATTACK_COUNT[player_1_engagement_form]; } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_1) > 0) { player_1_attack_count = 1; } break; } if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { nextPlayer(); } } else { acting_player = PLAYER_2; switch (game_mode) { case GAME_MODE_SKIRMISH: //let's see what type of ships we have. if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_2_attack_count = BB_ATTACK_COUNT[player_2_engagement_form]; } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_2) > 0) { player_2_attack_count = 1; } break; } if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; promptAction(); attackMain(); } else { nextPlayer(); } } } /** * allow the player to select a squre to fire on */ function beginTargeting() { promptAction(); document.getElementById("counterLeft").innerHTML = player_1_attack_count; document.getElementById("counterLabelLeft").innerHTML = string.attack_remaining; var grids = document.getElementById("monitorRight").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { if (!grids[i].hasAttribute("sunk")) { grids[i].addEventListener('click', fire, false); } if (!grids[i].hasAttribute("sunk") && !grids[i].hasAttribute("hit_count")) { grids[i].addEventListener('mouseover', lockOnSector, false); grids[i].addEventListener('mouseout', unLockOnSector, false); } } } function fire(evt) { var targetGrid = evt.target; var targetX = parseInt(targetGrid.getAttribute('x')); var targetY = parseInt(targetGrid.getAttribute('y')); if (acting_player == PLAYER_1) { player_1_attack_count = player_1_attack_count - 1; document.getElementById("counterLeft").innerHTML = player_1_attack_count; } else if (acting_player == PLAYER_2) { player_2_attack_count = player_2_attack_count - 1; } stopTargeting(); if (ship_class_acting == SHIP_CLASS_CV) { airStrike(targetX, targetY); } else { artilleryStrike(targetX, targetY); } } function airStrike(x, y) { if (SOUND_ENABLED) { plane_attack_sound.play(); setTimeout(function () { onAttackLanded(x, y); }, plane_attack_sound.duration * 1000 + 800); } else { onAttackLanded(x, y); } } function artilleryStrike(x, y) { if (SOUND_ENABLED && acting_player == PLAYER_1) { gun_fire_sound.play(); setTimeout(function () { onAttackLanded(x, y); }, gun_fire_sound.duration * 1000 + 800); } else { onAttackLanded(x, y); } } //determine if the attack hit and its consequences function onAttackLanded(x, y) { if (acting_player == PLAYER_1) { var tGrid = document.getElementById("monitorRight").querySelector("[y='" + y + "'][x='" + x + "']"); if (tGrid.hasAttribute("hit_count")) { var hit = parseInt(tGrid.getAttribute("hit_count")); tGrid.setAttribute("hit_count", hit + 1); } else { tGrid.setAttribute("hit_count", "1"); } tGrid.style.backgroundColor = 'navy'; tGrid.style.backgroundImage = ""; //see if we hit a ship if (tGrid.hasAttribute("placed")) { tGrid.style.backgroundColor = ''; tGrid.style.backgroundImage = ""; if (tGrid.hasAttribute("effectId")) { //stop all previous effects var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); } //show explosion effect var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 8; i++) { particles.push(new explosionParticle()); } var eid = setInterval(function () { showExplosion(canvas, particles, true); }, 40); setTimeout(function () { clearInterval(eid); if (!tGrid.hasAttribute("sunk")) { var hc = parseInt(tGrid.getAttribute("hit_count")); if (hc <= 1) { var canvas = tGrid.firstElementChild; var particles = []; var particle_count = 8; for (var i = 0; i < particle_count; i++) { particles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showSmoke(canvas, particles, true); }, 40); } else { var id = setInterval(function () { showSmoke(canvas, particles, false); }, 40); } tGrid.setAttribute("effectId", id); } else { //clear the old effect first var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); var canvas = tGrid.firstElementChild; var fireParticles = []; var smokeParticles = []; for (var i = 0; i < 10; i++) { fireParticles.push(new fireParticle()); } for (var i = 0; i < 5; i++) { smokeParticles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, true); }, 40); } else { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, false); }, 40); } tGrid.setAttribute("effectId", id); } } }, 1200); //see if we sunk it if (shipDestroyed("monitorRight", x, y)) { //TODO add instant win determiner //mark the ships as destroyed var tx = parseInt(tGrid.getAttribute("head-x")); var ty = parseInt(tGrid.getAttribute("head-y")); var tclass = parseInt(tGrid.getAttribute("ship-class")); var tbearing = parseInt(tGrid.getAttribute("ship-bearing")); var ship_size; switch (tclass) { case SHIP_CLASS_BB: ship_size = 4; player_2_ships_count[SHIP_CLASS_BB] = player_2_ships_count[SHIP_CLASS_BB] - 1; break; case SHIP_CLASS_CV: ship_size = 4; player_2_ships_count[SHIP_CLASS_CV] = player_2_ships_count[SHIP_CLASS_CV] - 1; break; case SHIP_CLASS_CA: ship_size = 3; player_2_ships_count[SHIP_CLASS_CA] = player_2_ships_count[SHIP_CLASS_CA] - 1; break; case SHIP_CLASS_DD: ship_size = 2; player_2_ships_count[SHIP_CLASS_DD] = player_2_ships_count[SHIP_CLASS_DD] - 1; break; } if (!FOG_OF_WAR) { refreshEnemyPanel(); } else { document.getElementById("counterRight").innerHTML = getPlayerShipCount(PLAYER_2); } if (tbearing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorRight").querySelector("[x='" + (tx + i) + "'][y='" + ty + "']"); if (!FOG_OF_WAR) { Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; } else { Grid.style.backgroundColor = "#990000"; } Grid.setAttribute("sunk", "true"); var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.removeEventListener('click', fire, false); } } else if (tbearing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorRight").querySelector("[y='" + (ty + i) + "'][x='" + tx + "']"); if (!FOG_OF_WAR) { Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; } else { Grid.style.backgroundColor = "#990000"; } Grid.setAttribute("sunk", "true"); var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.removeEventListener('click', fire, false); } } } if (SOUND_ENABLED) { attack_hit_sound_distant.play(); setTimeout(function () { if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, attack_hit_sound_distant.duration * 1000 + 800); } else { setTimeout(function () { if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, 1200); } } else { var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 340; i++) { particles.push(new waterParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var sid = setInterval(function () { showWaterSplash(canvas, particles, true); }, 60); } else { var sid = setInterval(function () { showWaterSplash(canvas, particles, false); }, 60); } if (SOUND_ENABLED) { attack_miss_sound.play(); setTimeout(function () { clearInterval(sid); if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, attack_miss_sound.duration * 1000 + 800); } else { setTimeout(function () { clearInterval(sid); if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } }, 3000); } } } else if (acting_player == PLAYER_2) { var tGrid = document.getElementById("monitorLeft").querySelector("[y='" + y + "'][x='" + x + "']"); if (tGrid.hasAttribute("hit_count")) { var hit = parseInt(tGrid.getAttribute("hit_count")); tGrid.setAttribute("hit_count", hit + 1); } else { tGrid.setAttribute("hit_count", "1"); } tGrid.style.backgroundColor = 'navy'; //see if we hit a ship if (tGrid.hasAttribute("placed")) { tGrid.style.backgroundColor = ''; //tGrid.style.backgroundImage = "url('" + img_url.ship_tiles[parseInt(tGrid.getAttribute("ship-class"))][1][parseInt(tGrid.getAttribute("sector"))] + "')"; if (tGrid.hasAttribute("effectId")) { //stop all previous effects var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); } //show explosion effect var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 8; i++) { particles.push(new explosionParticle()); } var eid = setInterval(function () { showExplosion(canvas, particles, true); }, 40); setTimeout(function () { clearInterval(eid); if (!tGrid.hasAttribute("sunk")) { var hc = parseInt(tGrid.getAttribute("hit_count")); if (hc <= 1) { var canvas = tGrid.firstElementChild; var particles = []; var particle_count = 8; for (var i = 0; i < particle_count; i++) { particles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showSmoke(canvas, particles, true); }, 40); } else { var id = setInterval(function () { showSmoke(canvas, particles, false); }, 40); } tGrid.setAttribute("effectId", id); } else { //clear the old effect first var effectId = parseInt(tGrid.getAttribute("effectId")); clearInterval(effectId); var canvas = tGrid.firstElementChild; var fireParticles = []; var smokeParticles = []; for (var i = 0; i < 10; i++) { fireParticles.push(new fireParticle()); } for (var i = 0; i < 5; i++) { smokeParticles.push(new smokeParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, true); }, 40); } else { var id = setInterval(function () { showFire(canvas, fireParticles, smokeParticles, false); }, 40); } tGrid.setAttribute("effectId", id); } } }, 1200); //see if we sunk it if (shipDestroyed("monitorLeft", x, y)) { var tx = parseInt(tGrid.getAttribute("head-x")); var ty = parseInt(tGrid.getAttribute("head-y")); var tclass = parseInt(tGrid.getAttribute("ship-class")); var tbearing = parseInt(tGrid.getAttribute("ship-bearing")); //mark the ships as destroyed var ship_size; switch (tclass) { case SHIP_CLASS_BB: ship_size = 4; player_1_ships_count[SHIP_CLASS_BB] = player_1_ships_count[SHIP_CLASS_BB] - 1; break; case SHIP_CLASS_CV: ship_size = 4; player_1_ships_count[SHIP_CLASS_CV] = player_1_ships_count[SHIP_CLASS_CV] - 1; break; case SHIP_CLASS_CA: ship_size = 3; player_1_ships_count[SHIP_CLASS_CA] = player_1_ships_count[SHIP_CLASS_CA] - 1; break; case SHIP_CLASS_DD: ship_size = 2; player_1_ships_count[SHIP_CLASS_DD] = player_1_ships_count[SHIP_CLASS_DD] - 1; break; } refreshPlayerPanel(); if (tbearing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorLeft").querySelector("[x='" + (tx + i) + "'][y='" + ty + "']"); Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.setAttribute("sunk", "true"); } } else if (tbearing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById("monitorLeft").querySelector("[y='" + (ty + i) + "'][x='" + tx + "']"); Grid.style.backgroundImage = "url('" + img_url.ship_tiles[tclass][2][i] + "')"; var effectId = parseInt(Grid.getAttribute("effectId")); clearInterval(effectId); var c = Grid.firstElementChild; //stop displaying effect for submerged ships clearCanvas(c); Grid.setAttribute("sunk", "true"); } } } onAttackResult(true); if (SOUND_ENABLED) { attack_hit_sound.play(); setTimeout(function () { if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, attack_hit_sound.duration * 1000 + 800); } else { setTimeout(function () { clearInterval(sid); if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, 1200); } } else { var canvas = tGrid.firstElementChild; var particles = []; for (var i = 0; i < 340; i++) { particles.push(new waterParticle()); } if (tGrid.classList.contains("ShipsTileHorizontal")) { var sid = setInterval(function () { showWaterSplash(canvas, particles, true); }, 60); } else { var sid = setInterval(function () { showWaterSplash(canvas, particles, false); }, 60); } onAttackResult(false); if (SOUND_ENABLED) { attack_miss_sound.play(); setTimeout(function () { clearInterval(sid); if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, attack_miss_sound.duration * 1000 + 800); } else { setTimeout(function () { clearInterval(sid); if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } }, 3000); } } } } //effects when a ship is hit //TODO maybe putting these into a separate "game-graphic.js" file? function showSmoke(canvas, particleList, hBearing) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "source-over"; if (hBearing == true) { //rotate the context ctx.translate(canvas.width / 2, canvas.height / 2); ctx.rotate(Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); } ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleList.length; i++) { var p = particleList[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100; var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); gradient.addColorStop(0, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(0.5, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; if (p.remaining_life < 0) { particleList[i] = new smokeParticle(); } } } function showFire(canvas, particleListFire, particleListSmoke, hBearing) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "source-over"; if (hBearing == true) { //rotate the context ctx.translate(canvas.width / 2, canvas.height / 2); //move to origin first so it rotate along the center ctx.rotate(Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); //move it back } ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleListFire.length; i++) { var p = particleListFire[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100 var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); gradient.addColorStop(0, "rgba(" + p.colorStop1.r + ", " + p.colorStop1.g + ", " + p.colorStop1.b + ", " + p.opacity + ")"); gradient.addColorStop(0.4, "rgba(" + p.colorStop2.r + ", " + p.colorStop2.g + ", " + p.colorStop2.b + ", " + p.opacity + ")"); gradient.addColorStop(0.6, "rgba(" + p.colorStop3.r + ", " + p.colorStop3.g + ", " + p.colorStop3.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.colorStop1.r + ", " + p.colorStop1.g + ", " + p.colorStop1.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; if (p.remaining_life < 0) { particleListFire[i] = new fireParticle(); } } for (var i = 0; i < particleListSmoke.length; i++) { var p = particleListSmoke[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100; var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); //TODO better effects by randomizing the colorstop size gradient.addColorStop(0, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(0.5, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.r + ", " + p.g + ", " + p.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; if (p.remaining_life < 0) { particleListSmoke[i] = new smokeParticle(); } } } function showExplosion(canvas, particleListFire) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "lighter"; ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleListFire.length; i++) { var p = particleListFire[i]; ctx.beginPath(); p.opacity = Math.round(p.remaining_life / p.life * 100) / 100; var gradient = ctx.createRadialGradient(p.location.x, p.location.y, 0, p.location.x, p.location.y, p.radius); gradient.addColorStop(0, "rgba(" + p.colorStop1.r + ", " + p.colorStop1.g + ", " + p.colorStop1.b + ", " + p.opacity + ")"); gradient.addColorStop(0.4, "rgba(" + p.colorStop2.r + ", " + p.colorStop2.g + ", " + p.colorStop2.b + ", " + p.opacity + ")"); gradient.addColorStop(0.6, "rgba(" + p.colorStop3.r + ", " + p.colorStop3.g + ", " + p.colorStop3.b + ", " + p.opacity + ")"); gradient.addColorStop(0.8, "rgba(" + p.colorStop4.r + ", " + p.colorStop4.g + ", " + p.colorStop4.b + ", " + p.opacity + ")"); gradient.addColorStop(1, "rgba(" + p.colorStop4.r + ", " + p.colorStop4.g + ", " + p.colorStop4.b + ", 0)"); ctx.fillStyle = gradient; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.remaining_life--; p.location.x += p.speed.x; p.location.y += p.speed.y; } } function showWaterSplash(canvas, particleListWater, hBearing) { var ctx = canvas.getContext("2d"); canvas.width = grid_size; canvas.height = grid_size; ctx.globalCompositeOperation = "source-over"; if (hBearing == true) { //rotate the context ctx.translate(canvas.width / 2, canvas.height / 2); ctx.rotate(Math.PI / 2); ctx.translate(-canvas.width / 2, -canvas.height / 2); } ctx.clearRect(0, 0, grid_size, grid_size); for (var i = 0; i < particleListWater.length; i++) { var p = particleListWater[i]; ctx.beginPath(); ctx.fillStyle = "rgb(" + p.color.r + ", " + p.color.g + ", " + p.color.b + ")"; ctx.arc(p.location.x, p.location.y, p.radius, Math.PI * 2, false); ctx.fill(); p.location.x += p.speed.x; p.location.y += p.speed.y; p.speed.y = p.speed.y - p.gravityPull; } } function smokeParticle() { this.speed = { x: -0.5 + Math.random() * 1, y: -2 + Math.random() * 2 }; this.location = { x: grid_size / 2, y: grid_size / 2 }; this.radius = 9; this.life = 18 + Math.random() * 5; this.remaining_life = this.life; var cc = Math.round(60 + Math.random() * 40); this.r = cc; this.g = cc; this.b = cc; } function fireParticle() { this.speed = { x: -0.7 + Math.random() * 1, y: -0.5 + Math.random() * 0.5 }; this.location = { x: grid_size / 2, y: grid_size / 2 }; this.radius = 8; this.life = 8 + Math.random() * 3; this.remaining_life = this.life; this.colorStop1 = { r: 255, g: 255, b: 255 }; this.colorStop2 = { r: 255, g: 255, b: Math.round(200 + Math.random() * 30) }; this.colorStop3 = { r: 255, g: 235, b: Math.round(90 + Math.random() * 30) }; } function explosionParticle() { this.speed = { x: -0.5 + Math.random() * 1, y: -0.5 + Math.random() * 1 }; this.location = { x: grid_size / 2, y: grid_size / 2 }; this.radius = 8; this.life = 15 + Math.random() * 5; this.remaining_life = this.life; this.colorStop1 = { r: 255, g: 255, b: 255 }; this.colorStop2 = { r: 255, g: 255, b: Math.round(200 + Math.random() * 30) }; this.colorStop3 = { r: 255, g: 235, b: Math.round(90 + Math.random() * 30) }; this.colorStop4 = { r: 255, g: 204, b: Math.round(0 + Math.random() * 10) }; } function waterParticle() { this.speed = { x: (-0.25 + Math.random() * 0.5) / DEFAULT_GRID_SIZE * grid_size, y: (-2.5 + Math.random() * 3) / DEFAULT_GRID_SIZE * grid_size }; this.gravityPull = -0.2; this.location = { x: grid_size / 2 - 1.5 + Math.random() * (3 / DEFAULT_GRID_SIZE * grid_size), y: grid_size - 1 }; this.radius = 1; this.color = { r: 160, g: 210, b: Math.round(200 + Math.random() * 30) }; } function clearCanvas(canvas) { var ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, grid_size, grid_size); } //given a coordinate, check if the ship is destroyed. function shipDestroyed(map, x, y) { var tGrid = document.getElementById(map).querySelector("[y='" + y + "'][x='" + x + "']"); var tx = parseInt(tGrid.getAttribute("head-x")); var ty = parseInt(tGrid.getAttribute("head-y")); var sClass = parseInt(tGrid.getAttribute("ship-class")); var bearing = parseInt(tGrid.getAttribute("ship-bearing")); var ship_size; var criticalDamage; switch (sClass) { case SHIP_CLASS_BB: ship_size = 4; if (game_mode == GAME_MODE_CLASSIC) { criticalDamage = 1; } else { criticalDamage = 2; } break; case SHIP_CLASS_CV: ship_size = 4; criticalDamage = 1; break; case SHIP_CLASS_CA: ship_size = 3; criticalDamage = 1; break; case SHIP_CLASS_DD: ship_size = 2; criticalDamage = 1; break; } if (bearing == SHIP_COURSE_VERTICAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById(map).querySelector("[x='" + (tx + i) + "'][y='" + ty + "']"); if (Grid.hasAttribute("hit_count")) { if (parseInt(Grid.getAttribute("hit_count")) >= criticalDamage) { if (i == (ship_size - 1)) { return true; } } else { return false; } } else { return false; } } } else if (bearing == SHIP_COURSE_HORIZONTAL) { for (var i = 0; i < ship_size; i++) { var Grid = document.getElementById(map).querySelector("[y='" + (ty + i) + "'][x='" + tx + "']"); if (Grid.hasAttribute("hit_count")) { if (parseInt(Grid.getAttribute("hit_count")) >= criticalDamage) { if (i == (ship_size - 1)) { return true; } } else { return false; } } else { return false; } } } } function lockOnSector(evt) { var targetGrid = evt.target; var sIcon = document.createElement('img'); sIcon.setAttribute('src', img_url.crosshair); sIcon.setAttribute('class', "Crosshair"); targetGrid.appendChild(sIcon); } function unLockOnSector(evt) { var targetGrid = evt.target; if (targetGrid.childNodes[targetGrid.childNodes.length - 1].getAttribute("class") == "Crosshair") { targetGrid.removeChild(targetGrid.childNodes[targetGrid.childNodes.length - 1]); } } function stopTargeting() { hideActionPrompt(); document.getElementById("counterLeft").innerHTML = getPlayerShipCount(PLAYER_1); document.getElementById("counterLabelLeft").innerHTML = string.ship_placement_remaining; var grids = document.getElementById("monitorRight").getElementsByClassName("MonitorGrid"); for (var i = 0; i < grids.length; i++) { grids[i].removeEventListener('click', fire, false); grids[i].removeEventListener('mouseover', lockOnSector, false); //grids[i].removeEventListener('mouseout', unLockOnSector, false); } } function promptAction() { var ap; if (acting_player == PLAYER_1) { document.getElementById("apRight").style.visibility = "visible"; } else { document.getElementById("apLeft").style.visibility = "visible"; } } function hideActionPrompt() { if (acting_player == PLAYER_1) { document.getElementById("apRight").style.visibility = "hidden"; } else { document.getElementById("apLeft").style.visibility = "hidden"; } } //refredh the number of ship displayed for player function refreshPlayerPanel() { document.getElementById("counterLeft").innerHTML = getPlayerShipCount(PLAYER_1); var labels = document.getElementById("dataPanelContentLeft").querySelectorAll('.ShipClassLabel'); for (var i = 0; i < labels.length; i++) { switch (i) { case SHIP_CLASS_BB: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_BB]; break; case SHIP_CLASS_CV: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_CV]; break; case SHIP_CLASS_CA: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_CA]; break; case SHIP_CLASS_DD: labels[i].innerHTML = string.ship_classes[i] + " : " + player_1_ships_count[SHIP_CLASS_DD]; break; } } } function refreshEnemyPanel() { document.getElementById("counterRight").innerHTML = getPlayerShipCount(PLAYER_2); var labels = document.getElementById("dataPanelContentRight").querySelectorAll('.ShipClassLabel'); for (var i = 0; i < labels.length; i++) { switch (i) { case SHIP_CLASS_BB: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_BB]; break; case SHIP_CLASS_CV: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_CV]; break; case SHIP_CLASS_CA: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_CA]; break; case SHIP_CLASS_DD: labels[i].innerHTML = string.ship_classes[i] + " : " + player_2_ships_count[SHIP_CLASS_DD]; break; } } } function nextPlayer() { if (gameEnded()) { refreshPlayerPanel(); refreshEnemyPanel(); hideActionPrompt(); var mainButton = document.getElementById("mainButton"); mainButton.innerHTML = string.new_game; mainButton.removeEventListener('click', surrender, false); mainButton.addEventListener('click', newGame, false); } else if (acting_player == PLAYER_1) { hideActionPrompt(); acting_player = PLAYER_2; promptAction(); switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_CONVOY: case GAME_MODE_BREAKTHROUGH: if (game_phase == GAME_PAHSE_AERIAL_COMBAT) { player_1_acted = true; player_2_attack_count = player_2_ships_count[SHIP_CLASS_CV] * 2; if (player_2_attack_count > 0 && !player_2_acted) { attackMain(); } else { //well both acted. let's move to next stage. startFleetCombat(); } } else if (game_phase == GAME_PHASE_COMBAT) { if (!player_2_first_act_complete) { if (player_2_turn_counter >= getPlayerShipCount(PLAYER_2)) { player_2_first_act_complete = true; } if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_2_attack_count = BB_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_BB]) { //the opponent still have BBs yet.skip this turn directly. nextPlayer(); } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_2_attack_count = CA_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } else { //extra code for cCA under t-dis(0 atk chance) player_2_turn_counter = player_2_turn_counter + 1; nextPlayer(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_2_attack_count = DD_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } else { //extra code for cCA under t-dis(0 atk chance) player_2_turn_counter = player_2_turn_counter + 1; nextPlayer(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CV] + player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_2_attack_count = CV_ATTACK_COUNT[player_2_engagement_form]; if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CV] + player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else { nextPlayer(); } } else { if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_2_attack_count = BB_ATTACK_COUNT[player_2_engagement_form]; } else if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_2_attack_count = CA_ATTACK_COUNT[player_2_engagement_form]; } else if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_2_attack_count = DD_ATTACK_COUNT[player_2_engagement_form]; } else if (player_2_turn_counter <= player_2_ships_count[SHIP_CLASS_CV] + player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_2_attack_count = CV_ATTACK_COUNT[player_2_engagement_form]; } player_2_turn_counter = player_2_turn_counter + 1; if (player_2_turn_counter > getPlayerShipCount(PLAYER_2) - player_2_ships_count[SHIP_CLASS_AP]) { player_2_acted = true; } if (player_2_acted && player_1_acted) { player_2_turn_counter = 0; player_1_turn_counter = 0; total_turn_counter = total_turn_counter + 1; if (game_mode == GAME_MODE_INTERCEPT || game_mode == GAME_MODE_CONVOY || game_mode == GAME_MODE_BREAKTHROUGH) { updateTurnCounter(); } player_2_acted = false; player_1_acted = false; } if (player_2_attack_count > 0) { attackMain(); } else { nextPlayer(); } } } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_2) > 0) { player_2_attack_count = 1; } if (player_2_attack_count > 0) { player_2_turn_counter = player_2_turn_counter + 1; attackMain(); } else { nextPlayer(); } break; } } else { hideActionPrompt(); acting_player = PLAYER_1; switch (game_mode) { case GAME_MODE_SKIRMISH: case GAME_MODE_INTERCEPT: case GAME_MODE_CONVOY: case GAME_MODE_BREAKTHROUGH: if (game_phase == GAME_PAHSE_AERIAL_COMBAT) { player_2_acted = true; player_1_attack_count = player_1_ships_count[SHIP_CLASS_CV] * 2; if (player_1_attack_count > 0 && !player_1_acted) { beginTargeting(); } else { startFleetCombat(); } } else if (game_phase == GAME_PHASE_COMBAT) { if (!player_1_first_act_complete) { if (player_1_turn_counter >= getPlayerShipCount(PLAYER_1) - player_1_ships_count[SHIP_CLASS_AP]) { player_1_first_act_complete = true; } if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_1_attack_count = BB_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_BB]) { //the opponent still have BBs yet.skip this turn directly. nextPlayer(); } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_1_attack_count = CA_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { //extra code for CA under t-dis(0 atk chance) player_1_turn_counter = player_1_turn_counter + 1; nextPlayer(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_1_attack_count = DD_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { //extra code for DD under t-dis(0 atk chance) player_1_turn_counter = player_1_turn_counter + 1; nextPlayer(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else if (player_1_turn_counter < player_1_ships_count[SHIP_CLASS_CV] + player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_1_attack_count = CV_ATTACK_COUNT[player_1_engagement_form]; if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } } else if (player_2_turn_counter < player_2_ships_count[SHIP_CLASS_CV] + player_2_ships_count[SHIP_CLASS_DD] + player_2_ships_count[SHIP_CLASS_CA] + player_2_ships_count[SHIP_CLASS_BB]) { //ditto nextPlayer(); } else { nextPlayer(); } } else { if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_BB; player_1_attack_count = BB_ATTACK_COUNT[player_1_engagement_form]; } else if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CA; player_1_attack_count = CA_ATTACK_COUNT[player_1_engagement_form]; } else if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_DD; player_1_attack_count = DD_ATTACK_COUNT[player_1_engagement_form]; } else if (player_1_turn_counter <= player_1_ships_count[SHIP_CLASS_CV] + player_1_ships_count[SHIP_CLASS_DD] + player_1_ships_count[SHIP_CLASS_CA] + player_1_ships_count[SHIP_CLASS_BB]) { ship_class_acting = SHIP_CLASS_CV; player_1_attack_count = CV_ATTACK_COUNT[player_1_engagement_form]; } player_1_turn_counter = player_1_turn_counter + 1; if (player_1_turn_counter > getPlayerShipCount(PLAYER_1) - player_1_ships_count[SHIP_CLASS_AP]) { player_1_acted = true; } if (player_2_acted && player_1_acted) { player_2_turn_counter = 0; player_1_turn_counter = 0; total_turn_counter = total_turn_counter + 1; if (game_mode == GAME_MODE_INTERCEPT || game_mode == GAME_MODE_CONVOY || game_mode == GAME_MODE_BREAKTHROUGH) { updateTurnCounter(); } player_2_acted = false; player_1_acted = false; } if (player_1_attack_count > 0) { beginTargeting(); } else { nextPlayer(); } } } break; case GAME_MODE_CLASSIC: if (getPlayerShipCount(PLAYER_1) > 0) { player_1_attack_count = 1; } if (player_1_attack_count > 0) { player_1_turn_counter = player_1_turn_counter + 1; beginTargeting(); } else { nextPlayer(); } break; } } } function updateTurnCounter() { document.getElementById("TurnCounter").innerHTML = (max_turn_intercept_breakthrough - total_turn_counter); } function gameEnded() { //see if any one fleet lose all their ships if (getPlayerShipCount(PLAYER_1) <= 0) { //TODO maybe using graphics to display the dialog? showEndGameDialog(string.defeat, string.defeat_description_standard); return true; } else if (getPlayerShipCount(PLAYER_2) <= 0) { showEndGameDialog(string.victory, string.victory_description_standard); return true; } else if (game_mode == GAME_MODE_INTERCEPT) { if (total_turn_counter >= max_turn_intercept_breakthrough) { showEndGameDialog(string.defeat, string.defeat_description_intercept); return true; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_2_ships_count[ship_class_target] <= 0) { showEndGameDialog(string.victory, string.victory_description_intercept); return true; } } } else if (game_mode == GAME_MODE_BREAKTHROUGH) { if (total_turn_counter >= max_turn_intercept_breakthrough) { showEndGameDialog(string.victory, string.victory_description_breakthrough); return true; } if (SPECIFIC_CLASS_INTERCEPT_BREAKTHROUGH) { if (player_1_ships_count[ship_class_target] <= 0) { showEndGameDialog(string.defeat, string.defeat_description_breakthrough); return true; } } } else if (game_mode == GAME_MODE_CONVOY) { if (total_turn_counter >= max_turn_intercept_breakthrough) { showEndGameDialog(string.victory, string.victory_description_convoy); return true; } if (player_1_ships_count[SHIP_CLASS_AP] <= 0) { showEndGameDialog(string.defeat, string.defeat_description_convoy); return true; } //TODO Destruction of marked target } else { return false; } } function showEndGameDialog(title, description) { document.getElementById('EndingTitle').innerHTML = title; document.getElementById('EndingDescription').innerHTML = description; document.getElementById('endGameBox').style.display = "table"; setTimeout(function () { window.onclick = function (event) { document.getElementById('endGameBox').style.display = "none"; } }, 3000); } function surrender(evt) { //TODO replace confirm with html 5 dialog if (confirm(string.surrender_confirm)) { //scuttle all ships to trigger lose effect for (var i = 0; i < player_1_ships_count.length; i++) { player_1_ships_count[i] = 0; } nextPlayer(); } else { //do nothing } } function newGame(evt) { //TODO replace confirm with html 5 dialog if (confirm(string.new_game_confirm)) { location.reload(); } else { //do nothing } }
Bug Fix - Fixed unsinkable transport ship (cherry picked from commit 12cc878)
script/game-core.js
Bug Fix - Fixed unsinkable transport ship
<ide><path>cript/game-core.js <ide> break; <ide> case SHIP_CLASS_DD: <ide> ship_size = 2; <add> criticalDamage = 1; <add> break; <add> case SHIP_CLASS_AP: <add> ship_size = 3; <ide> criticalDamage = 1; <ide> break; <ide> }
Java
lgpl-2.1
7e086b91777e7b52a10dc83d79f31af939d755b2
0
lucee/Lucee,jzuijlek/Lucee,jzuijlek/Lucee,lucee/Lucee,lucee/Lucee,lucee/Lucee,jzuijlek/Lucee
/** * Copyright (c) 2014, the Railo Company Ltd. * Copyright (c) 2015, Lucee Assosication Switzerland * * 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, see <http://www.gnu.org/licenses/>. * */ package lucee.runtime.type.scope; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import lucee.commons.lang.ExceptionUtil; import lucee.loader.engine.CFMLEngine; import lucee.runtime.ComponentScope; import lucee.runtime.PageContext; import lucee.runtime.PageContextImpl; import lucee.runtime.config.Config; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.NullSupportHelper; import lucee.runtime.dump.DumpData; import lucee.runtime.dump.DumpProperties; import lucee.runtime.exp.ExpressionException; import lucee.runtime.exp.PageException; import lucee.runtime.op.Duplicator; import lucee.runtime.type.Collection; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.Query; import lucee.runtime.type.QueryColumn; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.UDF; import lucee.runtime.type.UDFPlus; import lucee.runtime.type.dt.DateTime; import lucee.runtime.type.util.CollectionUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.StructSupport; import lucee.runtime.util.QueryStack; import lucee.runtime.util.QueryStackImpl; /** * Undefined Scope */ public final class UndefinedImpl extends StructSupport implements Undefined { private static final long serialVersionUID = -5626787508494702023L; private Scope[] scopes; private QueryStackImpl qryStack=new QueryStackImpl(); private Variables variable; private boolean allowImplicidQueryCall; private boolean checkArguments; private boolean localAlways; private short type; private boolean isInit; private Local local; private Argument argument; private PageContextImpl pc; private boolean debug; /** * constructor of the class * @param pageContextImpl * @param type type of the undefined scope (ServletConfigImpl.SCOPE_STRICT;ServletConfigImpl.SCOPE_SMALL;ServletConfigImpl.SCOPE_STANDART) */ public UndefinedImpl(PageContextImpl pc, short type) { this.type=type; this.pc=pc; } @Override public Local localScope() { return local; } @Override public Argument argumentsScope() { return argument; } @Override public Variables variablesScope() { return variable; } @Override public int setMode(int mode) { int m=Undefined.MODE_NO_LOCAL_AND_ARGUMENTS; if(checkArguments) { if(localAlways)m=Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS; else m=Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS; } checkArguments=mode!=Undefined.MODE_NO_LOCAL_AND_ARGUMENTS; localAlways=mode==Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS; return m; } @Override public boolean getLocalAlways(){ return localAlways; } @Override public void setFunctionScopes(Local local, Argument argument) { this.local=local; this.argument=argument; } @Override public QueryStack getQueryStack() { return qryStack; } @Override public void setQueryStack(QueryStack qryStack) { this.qryStack=(QueryStackImpl) qryStack; } @Override public void addQuery(Query qry) { if(allowImplicidQueryCall) qryStack.addQuery(qry); } @Override public void removeQuery() { if(allowImplicidQueryCall) qryStack.removeQuery(); } @Override public int size() { return variable.size(); } @Override public Collection.Key[] keys() { return CollectionUtil.keys(variable); } @Override public Object remove(Collection.Key key) throws PageException { if(checkArguments && local.containsKey(key)) return local.remove(key); return variable.remove(key); } @Override public Object removeEL(Collection.Key key) { if(checkArguments && local.containsKey(key)) return local.removeEL(key); return variable.removeEL(key); } @Override public void clear() { variable.clear(); } @Override public Object get(Collection.Key key) throws PageException { //print.e(); Object rtn; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return rtn; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,argument.getTypeAsString(), key); return rtn; } } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getDataFromACollection(pc,key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"query", key); if(!NullSupportHelper.full() && rtn==null) return ""; return rtn; } } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,variable,rtn, key); return rtn; } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"thread", key); return rtn; } } // get a scope value (only CFML is searching additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,scopes[i].getTypeAsString(),key); return rtn; } } } if(pc.getConfig().debug()) throw new ExpressionException(ExceptionUtil.similarKeyMessage(this, key.getString(), "key", "keys",null,false)); throw new ExpressionException("variable ["+key.getString()+"] doesn't exist"); } public static void debugCascadedAccess(PageContext pc,Variables var, Object value, Collection.Key key) { if(var instanceof ComponentScope){ if(key.equals(KeyConstants._THIS) || key.equals(KeyConstants._SUPER) || key.equals(KeyConstants._STATIC)) return; if(value instanceof UDF) { return; } } debugCascadedAccess(pc,"variables", key); } public static void debugCascadedAccess(PageContext pc,String name, Collection.Key key) { if(pc!=null)pc.getDebugger().addImplicitAccess(name,key.getString()); } @Override public Object getCollection(String key) throws PageException { return getCollection(KeyImpl.init(key)); } @Override public Struct getScope(Collection.Key key) { Object rtn=null; Struct sct=new StructImpl(Struct.TYPE_LINKED); if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) sct.setEL(KeyConstants._local, rtn); rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) sct.setEL(KeyConstants._arguments, rtn); } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getColumnFromACollection(key); if(rtn!=null) sct.setEL(KeyConstants._query, rtn); } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { sct.setEL(KeyConstants._variables, rtn); } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) sct.setEL(KeyConstants._thread, rtn); } // get a scope value (only cfml is searching addional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { sct.setEL(KeyImpl.init(scopes[i].getTypeAsString()), rtn); } } } return sct; } /** * returns the scope that contains a specific key * @param key * @return */ public Collection getScopeFor(Collection.Key key, Scope defaultValue) { Object rtn=null; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return local; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return argument; } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { QueryColumn qc = qryStack.getColumnFromACollection(key); if(qc!=null) return (Query)qc.getParent(); } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { return variable; } // thread scopes if(pc.hasFamily()) { Threads t = (Threads) pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return t; } // get a scope value (only cfml is searcing additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { return scopes[i]; } } } return defaultValue; } /** * return a list of String with the scope names * @param key * @return */ @Override public List<String> getScopeNames() { List<String> scopeNames=new ArrayList<String>(); if(checkArguments) { scopeNames.add("local"); scopeNames.add("arguments"); } scopeNames.add("variables"); // thread scopes if(pc.hasFamily()) { String[] names = pc.getThreadScopeNames(); for(int i=0;i<names.length;i++)scopeNames.add(i,names[i]); } for(int i=0;i<scopes.length;i++) { scopeNames.add((scopes[i]).getTypeAsString()); } return scopeNames; } @Override public Object getCollection(Key key) throws PageException { Object rtn=null; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return rtn; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug)debugCascadedAccess(pc,argument.getTypeAsString(), key); return rtn; } } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getColumnFromACollection(key); if(rtn!=null) { if(debug)debugCascadedAccess(pc,"query", key); return rtn; } } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,variable,rtn, key); return rtn; } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"thread", key); return rtn; } } // get a scope value (only CFML is searching addioanl scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug)debugCascadedAccess(pc,scopes[i].getTypeAsString(),key); return rtn; } } } throw new ExpressionException("variable ["+key.getString()+"] doesn't exist"); } @Override public Object get(Collection.Key key, Object defaultValue) { Object rtn=null; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return rtn; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,argument.getTypeAsString(), key); return rtn; } } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getDataFromACollection(pc,key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"query", key); return rtn; } } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,variable, rtn, key); return rtn; } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,"thread", key); return rtn; } } // get a scope value (only CFML is searching additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,scopes[i].getTypeAsString(), key); return rtn; } } } return defaultValue; } @Override public Object getCascading(Collection.Key key) { throw new RuntimeException("this method is no longer supported, use getCascading(Collection.Key key, Object defaultValue) instead"); } @Override public Object getCascading(Collection.Key key, Object defaultValue) { Object rtn; // get a scope value (only CFML is searching additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { return rtn; } } } return defaultValue; } @Override public Object setEL(Collection.Key key, Object value) { if(checkArguments) { if(localAlways || local.containsKey(key)) return local.setEL(key,value); if(argument.containsFunctionArgumentKey(key)) { if(debug)debugCascadedAccess(pc,argument.getTypeAsString(), key); return argument.setEL(key,value); } } if(debug && checkArguments)debugCascadedAccess(pc,variable.getTypeAsString(), key); return variable.setEL(key,value); } @Override public Object set(Collection.Key key, Object value) throws PageException { if(checkArguments) { if(localAlways || local.containsKey(key)) return local.set(key,value); if(argument.containsFunctionArgumentKey(key)) { if(debug)debugCascadedAccess(pc,argument.getTypeAsString(), key); return argument.set(key,value); } } if(debug && checkArguments)debugCascadedAccess(pc,variable.getTypeAsString(), key); return variable.set(key,value); } @Override public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { return variable.toDumpData(pageContext, maxlevel,dp); } @Override public Iterator<Collection.Key> keyIterator() { return variable.keyIterator(); } @Override public Iterator<String> keysAsStringIterator() { return variable.keysAsStringIterator(); } @Override public Iterator<Entry<Key, Object>> entryIterator() { return variable.entryIterator(); } @Override public Iterator<Object> valueIterator() { return variable.valueIterator(); } @Override public boolean isInitalized() { return isInit; } @Override public void initialize(PageContext pc) { //if(isInitalized()) return; isInit=true; variable=pc.variablesScope(); argument=pc.argumentsScope(); local=pc.localScope(); allowImplicidQueryCall=pc.getConfig().allowImplicidQueryCall(); type=((PageContextImpl)pc).getScopeCascadingType(); debug=pc.getConfig().debug() && ((ConfigImpl)pc.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_IMPLICIT_ACCESS); // Strict if(type==Config.SCOPE_STRICT) { //print.ln("strict"); scopes=new Scope[] {}; } // small else if(type==Config.SCOPE_SMALL) { //print.ln("small"); if(pc.getConfig().mergeFormAndURL()) { scopes=new Scope[] { pc.formScope() }; } else { scopes=new Scope[] { pc.urlScope(), pc.formScope() }; } } // standard else { reinitialize( pc); } } @Override public void reinitialize(PageContext pc) { if(type!=Config.SCOPE_STANDARD) return; Client cs = pc.clientScopeEL(); // print.ln("standard"); if(pc.getConfig().mergeFormAndURL()) { scopes=new Scope[cs==null?3:4]; scopes[0]=pc.cgiScope(); scopes[1]=pc.formScope(); scopes[2]=pc.cookieScope(); if(cs!=null)scopes[3]=cs; } else { scopes=new Scope[cs==null?4:5]; scopes[0]=pc.cgiScope(); scopes[1]=pc.urlScope(); scopes[2]=pc.formScope(); scopes[3]=pc.cookieScope(); if(cs!=null)scopes[4]=cs; } } @Override public final void release(PageContext pc) { isInit=false; argument=null; local=null; variable=null; scopes=null; checkArguments=false; localAlways=false; if(allowImplicidQueryCall)qryStack.clear(); } @Override public Collection duplicate(boolean deepCopy) { UndefinedImpl dupl = new UndefinedImpl(pc, type); dupl.allowImplicidQueryCall=allowImplicidQueryCall; dupl.checkArguments=checkArguments; dupl.argument=deepCopy?(Argument)Duplicator.duplicate(argument,deepCopy):argument; dupl.isInit=isInit; dupl.local=deepCopy?(Local)Duplicator.duplicate(local,deepCopy):local; dupl.localAlways=localAlways; dupl.qryStack= (deepCopy?(QueryStackImpl)Duplicator.duplicate(qryStack,deepCopy):qryStack); dupl.variable=deepCopy?(Variables)Duplicator.duplicate(variable,deepCopy):variable; dupl.pc=pc; dupl.debug=debug; // scopes if(deepCopy) { dupl.scopes=new Scope[scopes.length]; for(int i=0;i<scopes.length;i++) { dupl.scopes[i]=(Scope)Duplicator.duplicate(scopes[i],deepCopy); } } else dupl.scopes=scopes; return dupl; } @Override public boolean containsKey(Key key) { return get(key,null)!=null; } @Override public String castToString() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to String", "Use Built-In-Function \"serialize(Struct):String\" to create a String from Struct"); } @Override public String castToString(String defaultValue) { return defaultValue; } @Override public boolean castToBooleanValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to a boolean value"); } @Override public Boolean castToBoolean(Boolean defaultValue) { return defaultValue; } @Override public double castToDoubleValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to a number value"); } @Override public double castToDoubleValue(double defaultValue) { return defaultValue; } @Override public DateTime castToDateTime() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to a Date"); } @Override public DateTime castToDateTime(DateTime defaultValue) { return defaultValue; } @Override public int compareTo(boolean b) throws ExpressionException { throw new ExpressionException("can't compare Complex Object Type Struct with a boolean value"); } @Override public int compareTo(DateTime dt) throws PageException { throw new ExpressionException("can't compare Complex Object Type Struct with a DateTime Object"); } @Override public int compareTo(double d) throws PageException { throw new ExpressionException("can't compare Complex Object Type Struct with a numeric value"); } @Override public int compareTo(String str) throws PageException { throw new ExpressionException("can't compare Complex Object Type Struct with a String"); } @Override public void setVariableScope(Variables scope) { variable=scope; } @Override public int getType() { return SCOPE_UNDEFINED; } @Override public String getTypeAsString() { return "undefined"; } /** * @return the allowImplicidQueryCall */ public boolean isAllowImplicidQueryCall() { return allowImplicidQueryCall; } /** * @param allowImplicidQueryCall the allowImplicidQueryCall to set */ @Override public boolean setAllowImplicidQueryCall(boolean allowImplicidQueryCall) { boolean old=this.allowImplicidQueryCall; this.allowImplicidQueryCall = allowImplicidQueryCall; return old; } /** * @return the checkArguments */ @Override public boolean getCheckArguments() { return checkArguments; } @Override public Object call(PageContext pc, Key methodName, Object[] args) throws PageException { Object obj = get(methodName,null); // every none UDF value is fine as default argument if(obj instanceof UDFPlus) { return ((UDFPlus)obj).call(pc,methodName,args,false); } throw new ExpressionException("No matching function ["+methodName+"] found"); } @Override public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException { Object obj = get(methodName,null); if(obj instanceof UDFPlus) { return ((UDFPlus)obj).callWithNamedValues(pc,methodName,args,false); } throw new ExpressionException("No matching function ["+methodName+"] found"); } public short getScopeCascadingType() { return type; } }
core/src/main/java/lucee/runtime/type/scope/UndefinedImpl.java
/** * Copyright (c) 2014, the Railo Company Ltd. * Copyright (c) 2015, Lucee Assosication Switzerland * * 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, see <http://www.gnu.org/licenses/>. * */ package lucee.runtime.type.scope; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import lucee.commons.lang.ExceptionUtil; import lucee.loader.engine.CFMLEngine; import lucee.runtime.ComponentScope; import lucee.runtime.PageContext; import lucee.runtime.PageContextImpl; import lucee.runtime.config.Config; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.NullSupportHelper; import lucee.runtime.dump.DumpData; import lucee.runtime.dump.DumpProperties; import lucee.runtime.exp.ExpressionException; import lucee.runtime.exp.PageException; import lucee.runtime.op.Duplicator; import lucee.runtime.type.Collection; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.Query; import lucee.runtime.type.QueryColumn; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.UDF; import lucee.runtime.type.UDFPlus; import lucee.runtime.type.dt.DateTime; import lucee.runtime.type.util.CollectionUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.StructSupport; import lucee.runtime.util.QueryStack; import lucee.runtime.util.QueryStackImpl; /** * Undefined Scope */ public final class UndefinedImpl extends StructSupport implements Undefined { private static final long serialVersionUID = -5626787508494702023L; private Scope[] scopes; private QueryStackImpl qryStack=new QueryStackImpl(); private Variables variable; private boolean allowImplicidQueryCall; private boolean checkArguments; private boolean localAlways; private short type; private boolean isInit; private Local local; private Argument argument; private PageContextImpl pc; private boolean debug; /** * constructor of the class * @param pageContextImpl * @param type type of the undefined scope (ServletConfigImpl.SCOPE_STRICT;ServletConfigImpl.SCOPE_SMALL;ServletConfigImpl.SCOPE_STANDART) */ public UndefinedImpl(PageContextImpl pc, short type) { this.type=type; this.pc=pc; } @Override public Local localScope() { return local; } @Override public Argument argumentsScope() { return argument; } @Override public Variables variablesScope() { return variable; } @Override public int setMode(int mode) { int m=Undefined.MODE_NO_LOCAL_AND_ARGUMENTS; if(checkArguments) { if(localAlways)m=Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS; else m=Undefined.MODE_LOCAL_OR_ARGUMENTS_ONLY_WHEN_EXISTS; } checkArguments=mode!=Undefined.MODE_NO_LOCAL_AND_ARGUMENTS; localAlways=mode==Undefined.MODE_LOCAL_OR_ARGUMENTS_ALWAYS; return m; } @Override public boolean getLocalAlways(){ return localAlways; } @Override public void setFunctionScopes(Local local, Argument argument) { this.local=local; this.argument=argument; } @Override public QueryStack getQueryStack() { return qryStack; } @Override public void setQueryStack(QueryStack qryStack) { this.qryStack=(QueryStackImpl) qryStack; } @Override public void addQuery(Query qry) { if(allowImplicidQueryCall) qryStack.addQuery(qry); } @Override public void removeQuery() { if(allowImplicidQueryCall) qryStack.removeQuery(); } @Override public int size() { return variable.size(); } @Override public Collection.Key[] keys() { return CollectionUtil.keys(variable); } @Override public Object remove(Collection.Key key) throws PageException { if(checkArguments && local.containsKey(key)) return local.remove(key); return variable.remove(key); } @Override public Object removeEL(Collection.Key key) { if(checkArguments && local.containsKey(key)) return local.removeEL(key); return variable.removeEL(key); } @Override public void clear() { variable.clear(); } @Override public Object get(Collection.Key key) throws PageException { //print.e(); Object rtn; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return rtn; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,argument.getTypeAsString(), key); return rtn; } } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getDataFromACollection(pc,key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"query", key); if(!NullSupportHelper.full() && rtn==null) return ""; return rtn; } } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,variable,rtn, key); return rtn; } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"thread", key); return rtn; } } // get a scope value (only CFML is searching additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,scopes[i].getTypeAsString(),key); return rtn; } } } if(pc.getConfig().debug()) throw new ExpressionException(ExceptionUtil.similarKeyMessage(this, key.getString(), "key", "keys",null,false)); throw new ExpressionException("variable ["+key.getString()+"] doesn't exist"); } public static void debugCascadedAccess(PageContext pc,Variables var, Object value, Collection.Key key) { if(var instanceof ComponentScope){ if(key.equals(KeyConstants._THIS) || key.equals(KeyConstants._SUPER) || key.equals(KeyConstants._STATIC)) return; if(value instanceof UDF) { return; } } debugCascadedAccess(pc,"variables", key); } public static void debugCascadedAccess(PageContext pc,String name, Collection.Key key) { if(pc!=null)pc.getDebugger().addImplicitAccess(name,key.getString()); } @Override public Object getCollection(String key) throws PageException { return getCollection(KeyImpl.init(key)); } @Override public Struct getScope(Collection.Key key) { Object rtn=null; Struct sct=new StructImpl(Struct.TYPE_LINKED); if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) sct.setEL(KeyConstants._local, rtn); rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) sct.setEL(KeyConstants._arguments, rtn); } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getColumnFromACollection(key); if(rtn!=null) sct.setEL(KeyConstants._query, rtn); } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { sct.setEL(KeyConstants._variables, rtn); } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) sct.setEL(KeyConstants._thread, rtn); } // get a scope value (only cfml is searching addional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { sct.setEL(KeyImpl.init(scopes[i].getTypeAsString()), rtn); } } } return sct; } /** * returns the scope that contains a specific key * @param key * @return */ public Collection getScopeFor(Collection.Key key, Scope defaultValue) { Object rtn=null; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return local;; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return argument; } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { QueryColumn qc = qryStack.getColumnFromACollection(key); if(qc!=null) return (Query)qc.getParent(); } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { return variable; } // thread scopes if(pc.hasFamily()) { Threads t = (Threads) pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return t; } // get a scope value (only cfml is searcing additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { return scopes[i]; } } } return defaultValue; } /** * return a list of String with the scope names * @param key * @return */ @Override public List<String> getScopeNames() { List<String> scopeNames=new ArrayList<String>(); if(checkArguments) { scopeNames.add("local"); scopeNames.add("arguments"); } scopeNames.add("variables"); // thread scopes if(pc.hasFamily()) { String[] names = pc.getThreadScopeNames(); for(int i=0;i<names.length;i++)scopeNames.add(i,names[i]); } for(int i=0;i<scopes.length;i++) { scopeNames.add((scopes[i]).getTypeAsString()); } return scopeNames; } @Override public Object getCollection(Key key) throws PageException { Object rtn=null; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return rtn; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug)debugCascadedAccess(pc,argument.getTypeAsString(), key); return rtn; } } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getColumnFromACollection(key); if(rtn!=null) { if(debug)debugCascadedAccess(pc,"query", key); return rtn; } } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,variable,rtn, key); return rtn; } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"thread", key); return rtn; } } // get a scope value (only CFML is searching addioanl scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug)debugCascadedAccess(pc,scopes[i].getTypeAsString(),key); return rtn; } } } throw new ExpressionException("variable ["+key.getString()+"] doesn't exist"); } @Override public Object get(Collection.Key key, Object defaultValue) { Object rtn=null; if(checkArguments) { rtn=local.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) return rtn; rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,argument.getTypeAsString(), key); return rtn; } } // get data from queries if(allowImplicidQueryCall && pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML && !qryStack.isEmpty()) { rtn=qryStack.getDataFromACollection(pc,key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,"query", key); return rtn; } } // variable rtn=variable.get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,variable, rtn, key); return rtn; } // thread scopes if(pc.hasFamily()) { rtn = pc.getThreadScope(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug && checkArguments) debugCascadedAccess(pc,"thread", key); return rtn; } } // get a scope value (only CFML is searching additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { if(debug) debugCascadedAccess(pc,scopes[i].getTypeAsString(), key); return rtn; } } } return defaultValue; } @Override public Object getCascading(Collection.Key key) { throw new RuntimeException("this method is no longer supported, use getCascading(Collection.Key key, Object defaultValue) instead"); } @Override public Object getCascading(Collection.Key key, Object defaultValue) { Object rtn; // get a scope value (only CFML is searching additional scopes) if(pc.getCurrentTemplateDialect()==CFMLEngine.DIALECT_CFML) { for(int i=0;i<scopes.length;i++) { rtn=scopes[i].get(key,NullSupportHelper.NULL()); if(rtn!=NullSupportHelper.NULL()) { return rtn; } } } return defaultValue; } @Override public Object setEL(Collection.Key key, Object value) { if(checkArguments) { if(localAlways || local.containsKey(key)) return local.setEL(key,value); if(argument.containsFunctionArgumentKey(key)) { if(debug)debugCascadedAccess(pc,argument.getTypeAsString(), key); return argument.setEL(key,value); } } if(debug && checkArguments)debugCascadedAccess(pc,variable.getTypeAsString(), key); return variable.setEL(key,value); } @Override public Object set(Collection.Key key, Object value) throws PageException { if(checkArguments) { if(localAlways || local.containsKey(key)) return local.set(key,value); if(argument.containsFunctionArgumentKey(key)) { if(debug)debugCascadedAccess(pc,argument.getTypeAsString(), key); return argument.set(key,value); } } if(debug && checkArguments)debugCascadedAccess(pc,variable.getTypeAsString(), key); return variable.set(key,value); } @Override public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { return variable.toDumpData(pageContext, maxlevel,dp); } @Override public Iterator<Collection.Key> keyIterator() { return variable.keyIterator(); } @Override public Iterator<String> keysAsStringIterator() { return variable.keysAsStringIterator(); } @Override public Iterator<Entry<Key, Object>> entryIterator() { return variable.entryIterator(); } @Override public Iterator<Object> valueIterator() { return variable.valueIterator(); } @Override public boolean isInitalized() { return isInit; } @Override public void initialize(PageContext pc) { //if(isInitalized()) return; isInit=true; variable=pc.variablesScope(); argument=pc.argumentsScope(); local=pc.localScope(); allowImplicidQueryCall=pc.getConfig().allowImplicidQueryCall(); type=((PageContextImpl)pc).getScopeCascadingType(); debug=pc.getConfig().debug() && ((ConfigImpl)pc.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_IMPLICIT_ACCESS); // Strict if(type==Config.SCOPE_STRICT) { //print.ln("strict"); scopes=new Scope[] {}; } // small else if(type==Config.SCOPE_SMALL) { //print.ln("small"); if(pc.getConfig().mergeFormAndURL()) { scopes=new Scope[] { pc.formScope() }; } else { scopes=new Scope[] { pc.urlScope(), pc.formScope() }; } } // standard else { reinitialize( pc); } } @Override public void reinitialize(PageContext pc) { if(type!=Config.SCOPE_STANDARD) return; Client cs = pc.clientScopeEL(); // print.ln("standard"); if(pc.getConfig().mergeFormAndURL()) { scopes=new Scope[cs==null?3:4]; scopes[0]=pc.cgiScope(); scopes[1]=pc.formScope(); scopes[2]=pc.cookieScope(); if(cs!=null)scopes[3]=cs; } else { scopes=new Scope[cs==null?4:5]; scopes[0]=pc.cgiScope(); scopes[1]=pc.urlScope(); scopes[2]=pc.formScope(); scopes[3]=pc.cookieScope(); if(cs!=null)scopes[4]=cs; } } @Override public final void release(PageContext pc) { isInit=false; argument=null; local=null; variable=null; scopes=null; checkArguments=false; localAlways=false; if(allowImplicidQueryCall)qryStack.clear(); } @Override public Collection duplicate(boolean deepCopy) { UndefinedImpl dupl = new UndefinedImpl(pc, type); dupl.allowImplicidQueryCall=allowImplicidQueryCall; dupl.checkArguments=checkArguments; dupl.argument=deepCopy?(Argument)Duplicator.duplicate(argument,deepCopy):argument; dupl.isInit=isInit; dupl.local=deepCopy?(Local)Duplicator.duplicate(local,deepCopy):local; dupl.localAlways=localAlways; dupl.qryStack= (deepCopy?(QueryStackImpl)Duplicator.duplicate(qryStack,deepCopy):qryStack); dupl.variable=deepCopy?(Variables)Duplicator.duplicate(variable,deepCopy):variable; dupl.pc=pc; dupl.debug=debug; // scopes if(deepCopy) { dupl.scopes=new Scope[scopes.length]; for(int i=0;i<scopes.length;i++) { dupl.scopes[i]=(Scope)Duplicator.duplicate(scopes[i],deepCopy); } } else dupl.scopes=scopes; return dupl; } @Override public boolean containsKey(Key key) { return get(key,null)!=null; } @Override public String castToString() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to String", "Use Built-In-Function \"serialize(Struct):String\" to create a String from Struct"); } @Override public String castToString(String defaultValue) { return defaultValue; } @Override public boolean castToBooleanValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to a boolean value"); } @Override public Boolean castToBoolean(Boolean defaultValue) { return defaultValue; } @Override public double castToDoubleValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to a number value"); } @Override public double castToDoubleValue(double defaultValue) { return defaultValue; } @Override public DateTime castToDateTime() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Struct to a Date"); } @Override public DateTime castToDateTime(DateTime defaultValue) { return defaultValue; } @Override public int compareTo(boolean b) throws ExpressionException { throw new ExpressionException("can't compare Complex Object Type Struct with a boolean value"); } @Override public int compareTo(DateTime dt) throws PageException { throw new ExpressionException("can't compare Complex Object Type Struct with a DateTime Object"); } @Override public int compareTo(double d) throws PageException { throw new ExpressionException("can't compare Complex Object Type Struct with a numeric value"); } @Override public int compareTo(String str) throws PageException { throw new ExpressionException("can't compare Complex Object Type Struct with a String"); } @Override public void setVariableScope(Variables scope) { variable=scope; } @Override public int getType() { return SCOPE_UNDEFINED; } @Override public String getTypeAsString() { return "undefined"; } /** * @return the allowImplicidQueryCall */ public boolean isAllowImplicidQueryCall() { return allowImplicidQueryCall; } /** * @param allowImplicidQueryCall the allowImplicidQueryCall to set */ @Override public boolean setAllowImplicidQueryCall(boolean allowImplicidQueryCall) { boolean old=this.allowImplicidQueryCall; this.allowImplicidQueryCall = allowImplicidQueryCall; return old; } /** * @return the checkArguments */ @Override public boolean getCheckArguments() { return checkArguments; } @Override public Object call(PageContext pc, Key methodName, Object[] args) throws PageException { Object obj = get(methodName,null); // every none UDF value is fine as default argument if(obj instanceof UDFPlus) { return ((UDFPlus)obj).call(pc,methodName,args,false); } throw new ExpressionException("No matching function ["+methodName+"] found"); } @Override public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException { Object obj = get(methodName,null); if(obj instanceof UDFPlus) { return ((UDFPlus)obj).callWithNamedValues(pc,methodName,args,false); } throw new ExpressionException("No matching function ["+methodName+"] found"); } public short getScopeCascadingType() { return type; } }
clean up
core/src/main/java/lucee/runtime/type/scope/UndefinedImpl.java
clean up
<ide><path>ore/src/main/java/lucee/runtime/type/scope/UndefinedImpl.java <ide> <ide> if(checkArguments) { <ide> rtn=local.get(key,NullSupportHelper.NULL()); <del> if(rtn!=NullSupportHelper.NULL()) return local;; <add> if(rtn!=NullSupportHelper.NULL()) return local; <ide> rtn=argument.getFunctionArgument(key,NullSupportHelper.NULL()); <ide> if(rtn!=NullSupportHelper.NULL()) return argument; <ide> }
Java
mit
be1971d715599cf8965bd3dfcdf9377e2b65d769
0
emilhuseynli/file-leak-detector,kohsuke/file-leak-detector,mpuajari80/file-leak-detector
package org.kohsuke.file_leak_detecter; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.RandomAccessFile; import java.io.PrintStream; import java.util.Map; import java.util.HashMap; import java.util.Date; /** * Intercepted JDK calls land here. * * @author Kohsuke Kawaguchi */ public class Listener { private static final class Record { public final File file; public final Exception stackTrace = new Exception(); public final String threadName; public final long time; private Record(File file) { this.file = file; // keeping a Thread would potentially leak a thread, so let's just do a name this.threadName = Thread.currentThread().getName(); this.time = System.currentTimeMillis(); } public void dump(String prefix, PrintStream ps) { ps.println(prefix+file+" by thread:"+threadName+" on "+new Date(time)); StackTraceElement[] trace = stackTrace.getStackTrace(); int i=0; // skip until we find the Method.invoke() that called us for (; i<trace.length; i++) if(trace[i].getClassName().equals("java.lang.reflect.Method")) { i++; break; } // print the rest for (; i < trace.length; i++) ps.println("\tat " + trace[i]); } } /** * Files that are currently open. */ private static final Map<Object,Record> TABLE = new HashMap<Object,Record>(); /** * Trace the open/close op */ public static boolean TRACE = false; /** * Tracing may cause additional files to be opened. * In such a case, avoid infinite recursion. */ private static boolean tracing = false; /** * Called when a new file is opened. * * @param _this * {@link FileInputStream}, {@link FileOutputStream}, or {@link RandomAccessFile}. * @param f * File being opened. */ public static synchronized void open(Object _this, File f) { Record r = new Record(f); TABLE.put(_this, r); if(TRACE && !tracing) { tracing = true; r.dump("Opened ",System.err); tracing = false; } } /** * Called when a file is closed. * * @param _this * {@link FileInputStream}, {@link FileOutputStream}, or {@link RandomAccessFile}. */ public static synchronized void close(Object _this) { Record r = TABLE.remove(_this); if(r!=null && TRACE && !tracing) { tracing = true; r.dump("Closed ",System.err); tracing = false; } } /** * Dumps all files that are currently open. */ public static synchronized void dump(PrintStream ps) { ps.println(TABLE.size()+" files are open"); for (Record r : TABLE.values()) r.dump("",ps); } }
src/main/java/org/kohsuke/file_leak_detecter/Listener.java
package org.kohsuke.file_leak_detecter; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.RandomAccessFile; import java.io.PrintStream; import java.util.Map; import java.util.HashMap; import java.util.Date; /** * Intercepted JDK calls land here. * * @author Kohsuke Kawaguchi */ public class Listener { private static final class Record { public final File file; public final Exception stackTrace = new Exception(); public final String threadName; public final long time; private Record(File file) { this.file = file; // keeping a Thread would potentially leak a thread, so let's just do a name this.threadName = Thread.currentThread().getName(); this.time = System.currentTimeMillis(); } public void dump(String prefix, PrintStream ps) { ps.println(prefix+file+" by thread:"+threadName+" on "+new Date(time)); StackTraceElement[] trace = stackTrace.getStackTrace(); int i=0; // skip until we find the Method.invoke() that called us for (; i<trace.length; i++) if(trace[i].getClassName().equals("java.lang.reflect.Method")) { i++; break; } // print the rest for (; i < trace.length; i++) ps.println("\tat " + trace[i]); } } /** * Files that are currently open. */ private static final Map<Object,Record> TABLE = new HashMap<Object,Record>(); /** * Trace the open/close op */ public static boolean TRACE = false; /** * Tracing may cause additional files to be opened. * In such a case, avoid infinite recursion. */ private static boolean tracing = false; /** * Called when a new file is opened. * * @param _this * {@link FileInputStream}, {@link FileOutputStream}, or {@link RandomAccessFile}. * @param f * File being opened. */ public static synchronized void open(Object _this, File f) { Record r = new Record(f); TABLE.put(_this, r); if(TRACE && !tracing) { tracing = true; r.dump("Opened ",System.err); tracing = false; } } /** * Called when a file is closed. * * @param _this * {@link FileInputStream}, {@link FileOutputStream}, or {@link RandomAccessFile}. */ public static synchronized void close(Object _this) { Record r = TABLE.remove(_this); if(r!=null && TRACE && !tracing) { r.dump("Closed ",System.err); tracing = true; r.dump("Opened ",System.err); tracing = false; } } /** * Dumps all files that are currently open. */ public static synchronized void dump(PrintStream ps) { ps.println(TABLE.size()+" files are open"); for (Record r : TABLE.values()) r.dump("",ps); } }
bug fix
src/main/java/org/kohsuke/file_leak_detecter/Listener.java
bug fix
<ide><path>rc/main/java/org/kohsuke/file_leak_detecter/Listener.java <ide> public static synchronized void close(Object _this) { <ide> Record r = TABLE.remove(_this); <ide> if(r!=null && TRACE && !tracing) { <add> tracing = true; <ide> r.dump("Closed ",System.err); <del> tracing = true; <del> r.dump("Opened ",System.err); <ide> tracing = false; <ide> } <ide> }
JavaScript
apache-2.0
3cae09ab7d4700e10f6914dd0d017dacc45035ed
0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name assert * @memberof ns * @readonly * @type {Namespace} * @see {@link module:@stdlib/ndarray/base/assert} */ setReadOnly( ns, 'assert', require( '@stdlib/ndarray/base/assert' ) ); /** * @name bind2vind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/bind2vind} */ setReadOnly( ns, 'bind2vind', require( '@stdlib/ndarray/base/bind2vind' ) ); /** * @name broadcastArray * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/broadcast-array} */ setReadOnly( ns, 'broadcastArray', require( '@stdlib/ndarray/base/broadcast-array' ) ); /** * @name broadcastShapes * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/broadcast-shapes} */ setReadOnly( ns, 'broadcastShapes', require( '@stdlib/ndarray/base/broadcast-shapes' ) ); /** * @name buffer * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer} */ setReadOnly( ns, 'buffer', require( '@stdlib/ndarray/base/buffer' ) ); /** * @name bufferCtors * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer-ctors} */ setReadOnly( ns, 'bufferCtors', require( '@stdlib/ndarray/base/buffer-ctors' ) ); /** * @name bufferDataType * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer-dtype} */ setReadOnly( ns, 'bufferDataType', require( '@stdlib/ndarray/base/buffer-dtype' ) ); /** * @name bufferDataTypeEnum * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer-dtype-enum} */ setReadOnly( ns, 'bufferDataTypeEnum', require( '@stdlib/ndarray/base/buffer-dtype-enum' ) ); /** * @name bytesPerElement * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/bytes-per-element} */ setReadOnly( ns, 'bytesPerElement', require( '@stdlib/ndarray/base/bytes-per-element' ) ); /** * @name char2dtype * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/char2dtype} */ setReadOnly( ns, 'char2dtype', require( '@stdlib/ndarray/base/char2dtype' ) ); /** * @name clampIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/clamp-index} */ setReadOnly( ns, 'clampIndex', require( '@stdlib/ndarray/base/clamp-index' ) ); /** * @name ndarray * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/ctor} */ setReadOnly( ns, 'ndarray', require( '@stdlib/ndarray/base/ctor' ) ); /** * @name dtypeChar * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-char} */ setReadOnly( ns, 'dtypeChar', require( '@stdlib/ndarray/base/dtype-char' ) ); /** * @name dtypeDesc * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-desc} */ setReadOnly( ns, 'dtypeDesc', require( '@stdlib/ndarray/base/dtype-desc' ) ); /** * @name dtypeEnum2Str * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-enum2str} */ setReadOnly( ns, 'dtypeEnum2Str', require( '@stdlib/ndarray/base/dtype-enum2str' ) ); /** * @name dtypeResolveEnum * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-resolve-enum} */ setReadOnly( ns, 'dtypeResolveEnum', require( '@stdlib/ndarray/base/dtype-resolve-enum' ) ); /** * @name dtypeResolveStr * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-resolve-str} */ setReadOnly( ns, 'dtypeResolveStr', require( '@stdlib/ndarray/base/dtype-resolve-str' ) ); /** * @name dtypeStr2Enum * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-str2enum} */ setReadOnly( ns, 'dtypeStr2Enum', require( '@stdlib/ndarray/base/dtype-str2enum' ) ); /** * @name dtype2c * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype2c} */ setReadOnly( ns, 'dtype2c', require( '@stdlib/ndarray/base/dtype2c' ) ); /** * @name dtypes2signatures * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtypes2signatures} */ setReadOnly( ns, 'dtypes2signatures', require( '@stdlib/ndarray/base/dtypes2signatures' ) ); /** * @name ind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/ind} */ setReadOnly( ns, 'ind', require( '@stdlib/ndarray/base/ind' ) ); /** * @name ind2sub * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/ind2sub} */ setReadOnly( ns, 'ind2sub', require( '@stdlib/ndarray/base/ind2sub' ) ); /** * @name iterationOrder * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/iteration-order} */ setReadOnly( ns, 'iterationOrder', require( '@stdlib/ndarray/base/iteration-order' ) ); /** * @name maxViewBufferIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/max-view-buffer-index} */ setReadOnly( ns, 'maxViewBufferIndex', require( '@stdlib/ndarray/base/max-view-buffer-index' ) ); /** * @name metaDataProps * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/meta-data-props} */ setReadOnly( ns, 'metaDataProps', require( '@stdlib/ndarray/base/meta-data-props' ) ); /** * @name minViewBufferIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/min-view-buffer-index} */ setReadOnly( ns, 'minViewBufferIndex', require( '@stdlib/ndarray/base/min-view-buffer-index' ) ); /** * @name minmaxViewBufferIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/minmax-view-buffer-index} */ setReadOnly( ns, 'minmaxViewBufferIndex', require( '@stdlib/ndarray/base/minmax-view-buffer-index' ) ); /** * @name nonsingletonDimensions * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/nonsingleton-dimensions} */ setReadOnly( ns, 'nonsingletonDimensions', require( '@stdlib/ndarray/base/nonsingleton-dimensions' ) ); /** * @name numel * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/numel} */ setReadOnly( ns, 'numel', require( '@stdlib/ndarray/base/numel' ) ); /** * @name serializeMetaData * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/serialize-meta-data} */ setReadOnly( ns, 'serializeMetaData', require( '@stdlib/ndarray/base/serialize-meta-data' ) ); /** * @name shape2strides * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/shape2strides} */ setReadOnly( ns, 'shape2strides', require( '@stdlib/ndarray/base/shape2strides' ) ); /** * @name singletonDimensions * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/singleton-dimensions} */ setReadOnly( ns, 'singletonDimensions', require( '@stdlib/ndarray/base/singleton-dimensions' ) ); /** * @name strides2offset * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/strides2offset} */ setReadOnly( ns, 'strides2offset', require( '@stdlib/ndarray/base/strides2offset' ) ); /** * @name strides2order * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/strides2order} */ setReadOnly( ns, 'strides2order', require( '@stdlib/ndarray/base/strides2order' ) ); /** * @name sub2ind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/sub2ind} */ setReadOnly( ns, 'sub2ind', require( '@stdlib/ndarray/base/sub2ind' ) ); /** * @name ndarray2array * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/to-array} */ setReadOnly( ns, 'ndarray2array', require( '@stdlib/ndarray/base/to-array' ) ); /** * @name vind2bind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/vind2bind} */ setReadOnly( ns, 'vind2bind', require( '@stdlib/ndarray/base/vind2bind' ) ); /** * @name wrapIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/wrap-index} */ setReadOnly( ns, 'wrapIndex', require( '@stdlib/ndarray/base/wrap-index' ) ); // EXPORTS // module.exports = ns;
lib/node_modules/@stdlib/ndarray/base/lib/index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name assert * @memberof ns * @readonly * @type {Namespace} * @see {@link module:@stdlib/ndarray/base/assert} */ setReadOnly( ns, 'assert', require( '@stdlib/ndarray/base/assert' ) ); /** * @name bind2vind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/bind2vind} */ setReadOnly( ns, 'bind2vind', require( '@stdlib/ndarray/base/bind2vind' ) ); /** * @name broadcastArray * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/broadcast-array} */ setReadOnly( ns, 'broadcastArray', require( '@stdlib/ndarray/base/broadcast-array' ) ); /** * @name broadcastShapes * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/broadcast-shapes} */ setReadOnly( ns, 'broadcastShapes', require( '@stdlib/ndarray/base/broadcast-shapes' ) ); /** * @name buffer * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer} */ setReadOnly( ns, 'buffer', require( '@stdlib/ndarray/base/buffer' ) ); /** * @name bufferCtors * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer-ctors} */ setReadOnly( ns, 'bufferCtors', require( '@stdlib/ndarray/base/buffer-ctors' ) ); /** * @name bufferDataType * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer-dtype} */ setReadOnly( ns, 'bufferDataType', require( '@stdlib/ndarray/base/buffer-dtype' ) ); /** * @name bufferDataTypeEnum * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/buffer-dtype-enum} */ setReadOnly( ns, 'bufferDataTypeEnum', require( '@stdlib/ndarray/base/buffer-dtype-enum' ) ); /** * @name bytesPerElement * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/bytes-per-element} */ setReadOnly( ns, 'bytesPerElement', require( '@stdlib/ndarray/base/bytes-per-element' ) ); /** * @name char2dtype * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/char2dtype} */ setReadOnly( ns, 'char2dtype', require( '@stdlib/ndarray/base/char2dtype' ) ); /** * @name clampIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/clamp-index} */ setReadOnly( ns, 'clampIndex', require( '@stdlib/ndarray/base/clamp-index' ) ); /** * @name ndarray * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/ctor} */ setReadOnly( ns, 'ndarray', require( '@stdlib/ndarray/base/ctor' ) ); /** * @name dtypeChar * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-char} */ setReadOnly( ns, 'dtypeChar', require( '@stdlib/ndarray/base/dtype-char' ) ); /** * @name dtypeEnum2Str * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-enum2str} */ setReadOnly( ns, 'dtypeEnum2Str', require( '@stdlib/ndarray/base/dtype-enum2str' ) ); /** * @name dtypeResolveEnum * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-resolve-enum} */ setReadOnly( ns, 'dtypeResolveEnum', require( '@stdlib/ndarray/base/dtype-resolve-enum' ) ); /** * @name dtypeResolveStr * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-resolve-str} */ setReadOnly( ns, 'dtypeResolveStr', require( '@stdlib/ndarray/base/dtype-resolve-str' ) ); /** * @name dtypeStr2Enum * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype-str2enum} */ setReadOnly( ns, 'dtypeStr2Enum', require( '@stdlib/ndarray/base/dtype-str2enum' ) ); /** * @name dtype2c * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtype2c} */ setReadOnly( ns, 'dtype2c', require( '@stdlib/ndarray/base/dtype2c' ) ); /** * @name dtypes2signatures * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/dtypes2signatures} */ setReadOnly( ns, 'dtypes2signatures', require( '@stdlib/ndarray/base/dtypes2signatures' ) ); /** * @name ind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/ind} */ setReadOnly( ns, 'ind', require( '@stdlib/ndarray/base/ind' ) ); /** * @name ind2sub * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/ind2sub} */ setReadOnly( ns, 'ind2sub', require( '@stdlib/ndarray/base/ind2sub' ) ); /** * @name iterationOrder * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/iteration-order} */ setReadOnly( ns, 'iterationOrder', require( '@stdlib/ndarray/base/iteration-order' ) ); /** * @name maxViewBufferIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/max-view-buffer-index} */ setReadOnly( ns, 'maxViewBufferIndex', require( '@stdlib/ndarray/base/max-view-buffer-index' ) ); /** * @name metaDataProps * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/meta-data-props} */ setReadOnly( ns, 'metaDataProps', require( '@stdlib/ndarray/base/meta-data-props' ) ); /** * @name minViewBufferIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/min-view-buffer-index} */ setReadOnly( ns, 'minViewBufferIndex', require( '@stdlib/ndarray/base/min-view-buffer-index' ) ); /** * @name minmaxViewBufferIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/minmax-view-buffer-index} */ setReadOnly( ns, 'minmaxViewBufferIndex', require( '@stdlib/ndarray/base/minmax-view-buffer-index' ) ); /** * @name nonsingletonDimensions * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/nonsingleton-dimensions} */ setReadOnly( ns, 'nonsingletonDimensions', require( '@stdlib/ndarray/base/nonsingleton-dimensions' ) ); /** * @name numel * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/numel} */ setReadOnly( ns, 'numel', require( '@stdlib/ndarray/base/numel' ) ); /** * @name serializeMetaData * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/serialize-meta-data} */ setReadOnly( ns, 'serializeMetaData', require( '@stdlib/ndarray/base/serialize-meta-data' ) ); /** * @name shape2strides * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/shape2strides} */ setReadOnly( ns, 'shape2strides', require( '@stdlib/ndarray/base/shape2strides' ) ); /** * @name singletonDimensions * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/singleton-dimensions} */ setReadOnly( ns, 'singletonDimensions', require( '@stdlib/ndarray/base/singleton-dimensions' ) ); /** * @name strides2offset * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/strides2offset} */ setReadOnly( ns, 'strides2offset', require( '@stdlib/ndarray/base/strides2offset' ) ); /** * @name strides2order * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/strides2order} */ setReadOnly( ns, 'strides2order', require( '@stdlib/ndarray/base/strides2order' ) ); /** * @name sub2ind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/sub2ind} */ setReadOnly( ns, 'sub2ind', require( '@stdlib/ndarray/base/sub2ind' ) ); /** * @name ndarray2array * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/to-array} */ setReadOnly( ns, 'ndarray2array', require( '@stdlib/ndarray/base/to-array' ) ); /** * @name vind2bind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/vind2bind} */ setReadOnly( ns, 'vind2bind', require( '@stdlib/ndarray/base/vind2bind' ) ); /** * @name wrapIndex * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/base/wrap-index} */ setReadOnly( ns, 'wrapIndex', require( '@stdlib/ndarray/base/wrap-index' ) ); // EXPORTS // module.exports = ns;
Update namespace
lib/node_modules/@stdlib/ndarray/base/lib/index.js
Update namespace
<ide><path>ib/node_modules/@stdlib/ndarray/base/lib/index.js <ide> setReadOnly( ns, 'dtypeChar', require( '@stdlib/ndarray/base/dtype-char' ) ); <ide> <ide> /** <add>* @name dtypeDesc <add>* @memberof ns <add>* @readonly <add>* @type {Function} <add>* @see {@link module:@stdlib/ndarray/base/dtype-desc} <add>*/ <add>setReadOnly( ns, 'dtypeDesc', require( '@stdlib/ndarray/base/dtype-desc' ) ); <add> <add>/** <ide> * @name dtypeEnum2Str <ide> * @memberof ns <ide> * @readonly
Java
apache-2.0
61b3efdd0408a4d3ab9d41b6808d9bfd15407c14
0
gorzell/metrics,ind9/metrics,valery1707/dropwizard-metrics,mattnelson/metrics,mtakaki/metrics,slovdahl/metrics,mspiegel/metrics,rexren/metrics,dropwizard/metrics,maciej/metrics-scala,tempredirect/metrics,gburton1/metrics,ohr/metrics,jplock/metrics,kevintvh/metrics,gorzell/metrics,jasw/metrics,thelastpickle/metrics,ChetnaChaudhari/metrics,fcrepo4-archive/metrics,egymgmbh/metrics,fcrepo4-archive/metrics,Banno/metrics,signalfx/metrics,erikvanoosten/metrics-scala,dropwizard/metrics,gburton1/metrics,dropwizard/metrics,randomstatistic/metrics,wfxiang08/metrics,mt0803/metrics,chenxianghua2014/metrics,timezra/metrics,mnuessler/metrics,infusionsoft/yammer-metrics,infusionsoft/yammer-metrics,cirrus-dev/metrics,box/metrics,mveitas/metrics,mveitas/metrics,box/metrics,wickedshimmy/metrics-scala,unitsofmeasurement/metrics,gorzell/metrics,AltitudeDigital/metrics,slachiewicz/metrics,bentatham/metrics,scullxbones/metrics-scala
package com.yammer.metrics.reporting; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.*; import com.yammer.metrics.util.Utils; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.Thread.State; import java.net.Socket; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.yammer.metrics.core.VirtualMachineMetrics.*; /** * A simple reporter which sends out application metrics to a * <a href="http://graphite.wikidot.com/faq">Graphite</a> server periodically. * * @author Mahesh Tiyyagura <[email protected]> */ public class GraphiteReporter implements Runnable { private static final ScheduledExecutorService TICK_THREAD = Utils.newScheduledThreadPool(1, "graphite-reporter"); private static final Logger log = LoggerFactory.getLogger(GraphiteReporter.class); private final String host; private final int port; private Writer writer; private final String prefix; /** * Enables the graphite reporter to send data to graphite server with the * specified period. * * @param period the period between successive outputs * @param unit the time unit of {@code period} * @param host the host name of graphite server (carbon-cache agent) * @param port the port number on which the graphite server is listening */ public static void enable(long period, TimeUnit unit, String host, int port) { enable(period, unit, host, port, null); } /** * Enables the graphite reporter to send data to graphite server with the * specified period. * * @param period the period between successive outputs * @param unit the time unit of {@code period} * @param host the host name of graphite server (carbon-cache agent) * @param port the port number on which the graphite server is listening * @param prefix the string which is prepended to all metric names */ public static void enable(long period, TimeUnit unit, String host, int port, String prefix) { try { final GraphiteReporter reporter = new GraphiteReporter(host, port, prefix); reporter.start(period, unit); } catch (Exception e) { log.error("Error creating/starting Graphite reporter:", e); } } /** * Creates a new {@link GraphiteReporter}. * * @param host is graphite server * @param port is port on which graphite server is running * @param prefix is prepended to all names reported to graphite * @throws IOException if there is an error connecting to the Graphite server */ public GraphiteReporter(String host, int port, String prefix) throws IOException { this.host = host; this.port = port; if (prefix != null) { // Pre-append the "." so that we don't need to make anything conditional later. this.prefix = prefix + "."; } else { this.prefix = ""; } } /** * Starts sending output to graphite server. * * @param period the period between successive displays * @param unit the time unit of {@code period} */ public void start(long period, TimeUnit unit) { TICK_THREAD.scheduleAtFixedRate(this, period, period, unit); } @Override public void run() { Socket socket = null; try { socket = new Socket(host, port); writer = new OutputStreamWriter(socket.getOutputStream()); long epoch = System.currentTimeMillis() / 1000; printVmMetrics(epoch); printRegularMetrics(epoch); writer.flush(); } catch (Exception e) { log.error("Error:", e); if (writer != null) { try { writer.flush(); } catch (IOException e1) { log.error("Error while flushing writer:", e1); } } } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { log.error("Error while closing socket:", e); } } writer = null; } } private void printRegularMetrics(long epoch) { for (Entry<String, Map<String, Metric>> entry : Utils.sortMetrics(Metrics.allMetrics()).entrySet()) { for (Entry<String, Metric> subEntry : entry.getValue().entrySet()) { final String simpleName = (entry.getKey() + "." + subEntry.getKey()).replaceAll(" ", "_"); final Metric metric = subEntry.getValue(); if (metric != null) { try { if (metric instanceof GaugeMetric<?>) { printGauge((GaugeMetric<?>) metric, simpleName, epoch); } else if (metric instanceof CounterMetric) { printCounter((CounterMetric) metric, simpleName, epoch); } else if (metric instanceof HistogramMetric) { printHistogram((HistogramMetric) metric, simpleName, epoch); } else if (metric instanceof MeterMetric) { printMetered((MeterMetric) metric, simpleName, epoch); } else if (metric instanceof TimerMetric) { printTimer((TimerMetric) metric, simpleName, epoch); } } catch (Exception ignored) { log.error("Error printing regular metrics:", ignored); } } } } } private void sendToGraphite(String data) { try { writer.write(data); } catch (IOException e) { log.error("Error sending to Graphite:", e); } } private void printGauge(GaugeMetric<?> gauge, String name, long epoch) { sendToGraphite(String.format("%s%s.%s %s %d\n", prefix, name, "value", gauge.value(), epoch)); } private void printCounter(CounterMetric counter, String name, long epoch) { sendToGraphite(String.format("%s%s.%s %d %d\n", prefix, name, "count", counter.count(), epoch)); } private void printMetered(Metered meter, String name, long epoch) { StringBuffer lines = new StringBuffer(); lines.append(String.format("%s%s.%s %d %d\n", prefix, name, "count", meter.count(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "meanRate", meter.meanRate(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "1MinuteRate", meter.oneMinuteRate(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "5MinuteRate", meter.fiveMinuteRate(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "15MinuteRate", meter.fifteenMinuteRate(), epoch)); sendToGraphite(lines.toString()); } private void printHistogram(HistogramMetric histogram, String name, long epoch) { final double[] percentiles = histogram.percentiles(0.5, 0.75, 0.95, 0.98, 0.99, 0.999); StringBuffer lines = new StringBuffer(); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "min", histogram.min(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "max", histogram.max(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "mean", histogram.mean(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "stddev", histogram.stdDev(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "median", percentiles[0], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "75percentile", percentiles[1], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "95percentile", percentiles[2], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "98percentile", percentiles[3], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "99percentile", percentiles[4], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "999percentile", percentiles[5], epoch)); sendToGraphite(lines.toString()); } private void printTimer(TimerMetric timer, String name, long epoch) { printMetered(timer, name, epoch); final double[] percentiles = timer.percentiles(0.5, 0.75, 0.95, 0.98, 0.99, 0.999); StringBuffer lines = new StringBuffer(); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "min", timer.min(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "max", timer.max(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "mean", timer.mean(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "stddev", timer.stdDev(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "median", percentiles[0], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "75percentile", percentiles[1], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "95percentile", percentiles[2], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "98percentile", percentiles[3], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "99percentile", percentiles[4], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "999percentile", percentiles[5], epoch)); sendToGraphite(lines.toString()); } private void printDoubleField(String name, double value, long epoch) { sendToGraphite(String.format("%s%s %2.2f %d\n", prefix, name, value, epoch)); } private void printVmMetrics(long epoch) throws IOException { printDoubleField("jvm.memory.heap_usage", heapUsage(), epoch); printDoubleField("jvm.memory.non_heap_usage", nonHeapUsage(), epoch); for (Entry<String, Double> pool : memoryPoolUsage().entrySet()) { printDoubleField("jvm.memory.memory_pool_usages." + pool.getKey(), pool.getValue(), epoch); } printDoubleField("jvm.daemon_thread_count", daemonThreadCount(), epoch); printDoubleField("jvm.thread_count", threadCount(), epoch); printDoubleField("jvm.uptime", uptime(), epoch); printDoubleField("jvm.fd_usage", fileDescriptorUsage(), epoch); for (Entry<State, Double> entry : threadStatePercentages().entrySet()) { printDoubleField("jvm.thread-states." + entry.getKey().toString().toLowerCase(), entry.getValue(), epoch); } for (Entry<String, TimerMetric> entry : gcDurations().entrySet()) { printTimer(entry.getValue(), "jvm.gc.duration." + entry.getKey(), epoch); } for (Entry<String, MeterMetric> entry : gcThroughputs().entrySet()) { printMetered(entry.getValue(), "jvm.gc.throughput." + entry.getKey(), epoch); } } }
metrics-graphite/src/main/java/com/yammer/metrics/reporting/GraphiteReporter.java
package com.yammer.metrics.reporting; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.*; import com.yammer.metrics.util.Utils; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.Thread.State; import java.net.Socket; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.yammer.metrics.core.VirtualMachineMetrics.*; /** * A simple reporter which sends out application metrics to a * <a href="http://graphite.wikidot.com/faq">Graphite</a> server periodically. * * @author Mahesh Tiyyagura <[email protected]> */ public class GraphiteReporter implements Runnable { private static final ScheduledExecutorService TICK_THREAD = Utils.newScheduledThreadPool(1, "graphite-reporter"); private static final Logger log = LoggerFactory.getLogger(GraphiteReporter.class); private final String host; private final int port; private Writer writer; private final String prefix; /** * Enables the graphite reporter to send data to graphite server with the * specified period. * * @param period the period between successive outputs * @param unit the time unit of {@code period} * @param host the host name of graphite server (carbon-cache agent) * @param port the port number on which the graphite server is listening */ public static void enable(long period, TimeUnit unit, String host, int port) { enable(period, unit, host, port, null); } /** * Enables the graphite reporter to send data to graphite server with the * specified period. * * @param period the period between successive outputs * @param unit the time unit of {@code period} * @param host the host name of graphite server (carbon-cache agent) * @param port the port number on which the graphite server is listening * @param prefix the string which is prepended to all metric names */ public static void enable(long period, TimeUnit unit, String host, int port, String prefix) { try { final GraphiteReporter reporter = new GraphiteReporter(host, port, prefix); reporter.start(period, unit); } catch (Exception e) { log.error("Error creating/starting Graphite reporter:", e); } } /** * Creates a new {@link GraphiteReporter}. * * @param host is graphite server * @param port is port on which graphite server is running * @param prefix is prepended to all names reported to graphite * @throws IOException if there is an error connecting to the Graphite server */ public GraphiteReporter(String host, int port, String prefix) throws IOException { this.host = host; this.port = port; if (prefix != null) { // Pre-append the "." so that we don't need to make anything conditional later. this.prefix = prefix + "."; } else { this.prefix = ""; } } /** * Starts sending output to graphite server. * * @param period the period between successive displays * @param unit the time unit of {@code period} */ public void start(long period, TimeUnit unit) { TICK_THREAD.scheduleAtFixedRate(this, period, period, unit); } @Override public void run() { Socket socket = null; try { socket = new Socket(host, port); writer = new OutputStreamWriter(socket.getOutputStream()); long epoch = System.currentTimeMillis() / 1000; printVmMetrics(epoch); printRegularMetrics(epoch); writer.flush(); } catch (Exception e) { log.error("Error:", e); if (writer != null) { try { writer.flush(); } catch (IOException e1) { log.error("Error while flushing writer:", e1); } } } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { log.error("Error while closing socket:", e); } } writer = null; } } private void printRegularMetrics(long epoch) { for (Entry<String, Map<String, Metric>> entry : Utils.sortMetrics(Metrics.allMetrics()).entrySet()) { for (Entry<String, Metric> subEntry : entry.getValue().entrySet()) { final String simpleName = entry.getKey() + "." + subEntry.getKey(); final Metric metric = subEntry.getValue(); if (metric != null) { try { if (metric instanceof GaugeMetric<?>) { printGauge((GaugeMetric<?>) metric, simpleName, epoch); } else if (metric instanceof CounterMetric) { printCounter((CounterMetric) metric, simpleName, epoch); } else if (metric instanceof HistogramMetric) { printHistogram((HistogramMetric) metric, simpleName, epoch); } else if (metric instanceof MeterMetric) { printMetered((MeterMetric) metric, simpleName, epoch); } else if (metric instanceof TimerMetric) { printTimer((TimerMetric) metric, simpleName, epoch); } } catch (Exception ignored) { log.error("Error printing regular metrics:", ignored); } } } } } private void sendToGraphite(String data) { try { writer.write(data); } catch (IOException e) { log.error("Error sending to Graphite:", e); } } private void printGauge(GaugeMetric<?> gauge, String name, long epoch) { sendToGraphite(String.format("%s%s.%s %s %d\n", prefix, name, "value", gauge.value(), epoch)); } private void printCounter(CounterMetric counter, String name, long epoch) { sendToGraphite(String.format("%s%s.%s %d %d\n", prefix, name, "count", counter.count(), epoch)); } private void printMetered(Metered meter, String name, long epoch) { StringBuffer lines = new StringBuffer(); lines.append(String.format("%s%s.%s %d %d\n", prefix, name, "count", meter.count(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "meanRate", meter.meanRate(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "1MinuteRate", meter.oneMinuteRate(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "5MinuteRate", meter.fiveMinuteRate(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "15MinuteRate", meter.fifteenMinuteRate(), epoch)); sendToGraphite(lines.toString()); } private void printHistogram(HistogramMetric histogram, String name, long epoch) { final double[] percentiles = histogram.percentiles(0.5, 0.75, 0.95, 0.98, 0.99, 0.999); StringBuffer lines = new StringBuffer(); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "min", histogram.min(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "max", histogram.max(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "mean", histogram.mean(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "stddev", histogram.stdDev(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "median", percentiles[0], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "75percentile", percentiles[1], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "95percentile", percentiles[2], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "98percentile", percentiles[3], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "99percentile", percentiles[4], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "999percentile", percentiles[5], epoch)); sendToGraphite(lines.toString()); } private void printTimer(TimerMetric timer, String name, long epoch) { printMetered(timer, name, epoch); final double[] percentiles = timer.percentiles(0.5, 0.75, 0.95, 0.98, 0.99, 0.999); StringBuffer lines = new StringBuffer(); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "min", timer.min(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "max", timer.max(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "mean", timer.mean(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "stddev", timer.stdDev(), epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "median", percentiles[0], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "75percentile", percentiles[1], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "95percentile", percentiles[2], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "98percentile", percentiles[3], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "99percentile", percentiles[4], epoch)); lines.append(String.format("%s%s.%s %2.2f %d\n", prefix, name, "999percentile", percentiles[5], epoch)); sendToGraphite(lines.toString()); } private void printDoubleField(String name, double value, long epoch) { sendToGraphite(String.format("%s%s %2.2f %d\n", prefix, name, value, epoch)); } private void printVmMetrics(long epoch) throws IOException { printDoubleField("jvm.memory.heap_usage", heapUsage(), epoch); printDoubleField("jvm.memory.non_heap_usage", nonHeapUsage(), epoch); for (Entry<String, Double> pool : memoryPoolUsage().entrySet()) { printDoubleField("jvm.memory.memory_pool_usages." + pool.getKey(), pool.getValue(), epoch); } printDoubleField("jvm.daemon_thread_count", daemonThreadCount(), epoch); printDoubleField("jvm.thread_count", threadCount(), epoch); printDoubleField("jvm.uptime", uptime(), epoch); printDoubleField("jvm.fd_usage", fileDescriptorUsage(), epoch); for (Entry<State, Double> entry : threadStatePercentages().entrySet()) { printDoubleField("jvm.thread-states." + entry.getKey().toString().toLowerCase(), entry.getValue(), epoch); } for (Entry<String, TimerMetric> entry : gcDurations().entrySet()) { printTimer(entry.getValue(), "jvm.gc.duration." + entry.getKey(), epoch); } for (Entry<String, MeterMetric> entry : gcThroughputs().entrySet()) { printMetered(entry.getValue(), "jvm.gc.throughput." + entry.getKey(), epoch); } } }
Apply s/ /_/g to the metric name, to not break the line format
metrics-graphite/src/main/java/com/yammer/metrics/reporting/GraphiteReporter.java
Apply s/ /_/g to the metric name, to not break the line format
<ide><path>etrics-graphite/src/main/java/com/yammer/metrics/reporting/GraphiteReporter.java <ide> private void printRegularMetrics(long epoch) { <ide> for (Entry<String, Map<String, Metric>> entry : Utils.sortMetrics(Metrics.allMetrics()).entrySet()) { <ide> for (Entry<String, Metric> subEntry : entry.getValue().entrySet()) { <del> final String simpleName = entry.getKey() + "." + subEntry.getKey(); <add> final String simpleName = (entry.getKey() + "." + subEntry.getKey()).replaceAll(" ", "_"); <ide> final Metric metric = subEntry.getValue(); <ide> if (metric != null) { <ide> try {
JavaScript
apache-2.0
479932fb1e9b60b9d6e2b9e677c0ca9cee618f20
0
orionrobots/Bounce,orionrobots/Bounce
var workspace; var mcu_console; var is_preparing = false; var ui; /** * Create a console to output data in visible in the UI. * @param output_element A DOM element to use for output. * @constructor */ var OutputConsole = function (output_element) { /** * Write some data to the output. HTML is escaped. * @param data Data to write. */ this.write = function(data) { var safe_data = goog.string.htmlEscape(data); safe_data = goog.string.newLineToBr(safe_data); output_element.append(output_element, safe_data); }; /** * Write a line of data. * @param line */ this.writeLine = function(line) { this.write(line + '\n') }; this.writeLine('Console initialised'); }; /** * * @constructor Prompt for a filename - use "display(ok_callback, cancel_callback)" to prompt. */ function AskForFilename() { var main_div = $("#filename_dlg"); var ok_button = main_div.find("#ok"); var cancel_button = main_div.find("#cancel"); var _lb = this; function _ok_clicked() { _lb.hide(); var filename = main_div.find("#filename").val(); _lb.ok_call(filename); } /** * * @param ok_call - Call this with the filename when this dialog is ok'd. * @param cancel_call - Call this if it's cancelled. May be empty. */ this.display = function(ok_call, cancel_call) { $(main_div).removeClass("lightbox-hidden"); this.ok_call = ok_call; ok_button.click(_ok_clicked); cancel_button.click(function() { _lb.hide(); if(cancel_call) { cancel_call(); } }); }; /** * Hide the popup. */ this.hide = function () { $(main_div).addClass("lightbox-hidden"); } } function prepare_blockly_workspace() { var blocklyArea = document.getElementById('blocklyArea'); var blocklyDiv = document.getElementById('blocklyDiv'); workspace = Blockly.inject(blocklyDiv, {toolbox: goog.dom.$('toolbox'), media: "blockly-nodemcu/media/" }); var onresize = function() { // Compute the absolute coordinates and dimensions of blocklyArea. var element = blocklyArea; var x = 0; var y = 0; do { x += element.offsetLeft; y += element.offsetTop; element = element.offsetParent; } while (element); // Position blocklyDiv over blocklyArea. blocklyDiv.style.left = x + 'px'; blocklyDiv.style.top = y + 'px'; blocklyDiv.style.width = blocklyArea.offsetWidth + 'px'; blocklyDiv.style.height = blocklyArea.offsetHeight + 'px'; Blockly.svgResize(workspace); }; window.addEventListener('resize', onresize, false); onresize(); } /** * Send the code directly to the mcu repl. * @param mcu */ function run(mcu) { var code = Blockly.Lua.workspaceToCode(workspace); mcu.send_multiline_data(code, function() {}); } function export_document() { var xml = Blockly.Xml.workspaceToDom(workspace); return Blockly.Xml.domToPrettyText(xml); } function load_document(text) { is_preparing = true; var xml = Blockly.Xml.textToDom(text); Blockly.Xml.domToWorkspace(workspace, xml); } function new_document() { is_preparing = true; Blockly.mainWorkspace.clear(); } function BounceUI() { var toolbar; var currentMcu; var connectMenu, fileMenu; var _ui = this; var _currentFileEntry; var _modified = false; /** * Upload the file as init.lua. * * Later: Implement choosing the filename, and dofile. * * @param mcu */ function _upload_as_init(mcu) { var filename="init.lua"; var code = Blockly.Lua.workspaceToCode(workspace); mcu.send_as_file(code, filename, function() { mcu_console.writeLine("Completed upload"); }); } function _upload(mcu) { var fndlg = new AskForFilename(); fndlg.display(function(filename) { var code = Blockly.Lua.workspaceToCode(workspace); mcu.send_as_file(code, filename, function() { mcu_console.writeLine("Completed upload"); }); }); } /** * Open a file from the filesystem. Load into blockly workspace. * * @private */ function _open_file() { var accepts = [{ mimeTypes: ['text/*'], extensions: ['xml', 'node'] }]; // Show a file open chrome.fileSystem.chooseEntry({type: 'openFile', accepts: accepts}, function(theEntry) { if (!theEntry) { mcu_console.writeLine('No file selected.'); return; } // On ok // use local storage to retain access to this file //chrome.storage.local.set({'chosenFile': chrome.fileSystem.retainEntry(theEntry)}); // Inject that code. console.log("turning entry into file"); theEntry.file(function(file) { console.log("opening file"); var reader = new FileReader(); reader.onloadend = function(e) { new_document(); load_document(e.target.result); }; reader.readAsText(file); }); _currentFileEntry = theEntry; }); } function _save() { _currentFileEntry.createWriter(function(writer) { writer.onwriteend = function(e) { console.log('write complete'); }; writer.write(new Blob([export_document()], {type: 'text/plain'})); }) } function _save_as() { var accepts = [{ mimeTypes: ['text/*'], extensions: ['xml', 'node'] }]; chrome.fileSystem.chooseEntry({type: 'saveFile', accepts:accepts}, function(writableFileEntry) { _currentFileEntry = writableFileEntry; _save(); }); } toolbar = new goog.ui.Toolbar(); toolbar.decorate(goog.dom.getElement('toolbar')); connectMenu = new goog.ui.Menu(); connectMenu.decorate(goog.dom.getElement('connect_menu')); fileMenu = new goog.ui.Menu(); fileMenu.decorate(goog.dom.getElement('file_menu')); $("#run_button").click(function() { run(currentMcu); }); $("#open_button").click(_open_file); $("#saveas_button").click(_save_as); $("#save_button").click(_save); $("#upload_as_init").click(function() { _upload_as_init(currentMcu); }); $("#upload").click(function() { _upload(currentMcu); }); // Callback to add found items to the menu. var found_item = function(mcu) { mcu_console.writeLine('Adding found item...'); var connectItem = new goog.ui.MenuItem(mcu.port); connectItem.setCheckable(true); connectMenu.addItem(connectItem); $(connectItem.getContentElement()).click(function() { _connect_menu_item_clicked(connectItem, mcu); }); }; // When the scanButton is clicked, scan for mcu's to add. $("#scan_button").click(function() { bounce.Nodemcu.scan(mcu_console, found_item); }); /** * * @param connectItem Menu item that was clicked * @param mcu The associated NodeMCU device * @private */ function _connect_menu_item_clicked(connectItem, mcu) { mcu.connect(function() { // We've now connected the mcu. Update the UI mcu_console.writeLine("Connected"); currentMcu = mcu; _ui.currentMcu = mcu; // Add a tick (Check) to the connection menu item connectItem.setChecked(true); // disconnect any others // Enable the run menu toolbar.getChild("run_button").setEnabled(true); toolbar.getChild("upload").setEnabled(true); toolbar.getChild("upload_as_init").setEnabled(true); /* stopButton.setEnabled(true); */ }); } this.changed = function () { console.log("Workspace changed"); if (is_preparing) { is_preparing = false; _modified = true; } else { fileMenu.getChild("saveas_button").setEnabled(true); if (_currentFileEntry) { fileMenu.getChild("save_button").setEnabled(true); } } } } $(function () { prepare_blockly_workspace(); mcu_console = new OutputConsole($('#output')); ui = new BounceUI(); workspace.addChangeListener(ui.changed); });
Bounce/app/start.js
var workspace; var mcu_console; var is_preparing = false; var ui; /** * Create a console to output data in visible in the UI. * @param output_element A DOM element to use for output. * @constructor */ var OutputConsole = function (output_element) { /** * Write some data to the output. HTML is escaped. * @param data Data to write. */ this.write = function(data) { var safe_data = goog.string.htmlEscape(data); safe_data = goog.string.newLineToBr(safe_data); output_element.append(output_element, safe_data); }; /** * Write a line of data. * @param line */ this.writeLine = function(line) { this.write(line + '\n') }; this.writeLine('Console initialised'); }; /** * * @constructor Prompt for a filename - use "display(ok_callback, cancel_callback)" to prompt. */ function AskForFilename() { var main_div = $("#filename_dlg"); var ok_button = main_div.find("#ok"); var cancel_button = main_div.find("#cancel"); var _lb = this; function _ok_clicked() { _lb.hide(); var filename = main_div.find("#filename").val(); _lb.ok_call(filename); } /** * * @param ok_call - Call this with the filename when this dialog is ok'd. * @param cancel_call - Call this if it's cancelled. May be empty. */ this.display = function(ok_call, cancel_call) { $(main_div).removeClass("lightbox-hidden"); this.ok_call = ok_call; this.cancel_call= cancel_call; ok_button.click(_ok_clicked); cancel_button.click(function() { _lb.hide(); if(cancel_call) { cancel_call(); } }); }; /** * Hide the popup. */ this.hide = function () { $(main_div).addClass("lightbox-hidden"); } } function prepare_blockly_workspace() { var blocklyArea = document.getElementById('blocklyArea'); var blocklyDiv = document.getElementById('blocklyDiv'); workspace = Blockly.inject(blocklyDiv, {toolbox: goog.dom.$('toolbox'), media: "blockly-nodemcu/media/" }); var onresize = function(e) { // Compute the absolute coordinates and dimensions of blocklyArea. var element = blocklyArea; var x = 0; var y = 0; do { x += element.offsetLeft; y += element.offsetTop; element = element.offsetParent; } while (element); // Position blocklyDiv over blocklyArea. blocklyDiv.style.left = x + 'px'; blocklyDiv.style.top = y + 'px'; blocklyDiv.style.width = blocklyArea.offsetWidth + 'px'; blocklyDiv.style.height = blocklyArea.offsetHeight + 'px'; Blockly.svgResize(workspace); }; window.addEventListener('resize', onresize, false); onresize(); } /** * Send the code directly to the mcu repl. * @param mcu */ function run(mcu) { var code = Blockly.Lua.workspaceToCode(workspace); mcu.send_multiline_data(code, function() {}); } function export_document() { var xml = Blockly.Xml.workspaceToDom(workspace); var xml_text = Blockly.Xml.domToPrettyText(xml); return xml_text; } function load_document(text) { is_preparing = true; var xml = Blockly.Xml.textToDom(text); Blockly.Xml.domToWorkspace(workspace, xml); } function new_document() { is_preparing = true; Blockly.mainWorkspace.clear(); } function BounceUI() { var toolbar, runButton, stopButton, saveButton, saveAsButton; var currentMcu; var connectMenu, fileMenu; var _ui = this; var _currentFileEntry; var _modified = false; /** * Upload the file as init.lua. * * Later: Implement choosing the filename, and dofile. * * @param mcu */ function _upload_as_init(mcu) { var filename="init.lua"; var code = Blockly.Lua.workspaceToCode(workspace); mcu.send_as_file(code, filename, function() { mcu_console.writeLine("Completed upload"); }); } function _upload(mcu) { var fndlg = new AskForFilename(); fndlg.display(function(filename) { var code = Blockly.Lua.workspaceToCode(workspace); mcu.send_as_file(code, filename, function() { mcu_console.writeLine("Completed upload"); }); }); } /** * Open a file from the filesystem. Load into blockly workspace. * * @private */ function _open_file() { var accepts = [{ mimeTypes: ['text/*'], extensions: ['xml', 'node'] }]; // Show a file open chrome.fileSystem.chooseEntry({type: 'openFile', accepts: accepts}, function(theEntry) { if (!theEntry) { mcu_console.writeLine('No file selected.'); return; } // On ok // use local storage to retain access to this file //chrome.storage.local.set({'chosenFile': chrome.fileSystem.retainEntry(theEntry)}); // Inject that code. console.log("turning entry into file"); theEntry.file(function(file) { console.log("opening file"); var reader = new FileReader(); reader.onloadend = function(e) { new_document(); load_document(e.target.result); }; reader.readAsText(file); }); _currentFileEntry = theEntry; }); } function _save() { _currentFileEntry.createWriter(function(writer) { writer.onwriteend = function(e) { console.log('write complete'); }; writer.write(new Blob([export_document()], {type: 'text/plain'})); }) } function _save_as() { var accepts = [{ mimeTypes: ['text/*'], extensions: ['xml', 'node'] }]; chrome.fileSystem.chooseEntry({type: 'saveFile', accepts:accepts}, function(writableFileEntry) { _currentFileEntry = writableFileEntry; _save(); }); } toolbar = new goog.ui.Toolbar(); toolbar.decorate(goog.dom.getElement('toolbar')); connectMenu = new goog.ui.Menu(); connectMenu.decorate(goog.dom.getElement('connect_menu')); fileMenu = new goog.ui.Menu(); fileMenu.decorate(goog.dom.getElement('file_menu')); saveAsButton = goog.dom.getElement("saveas_button"); saveButton = goog.dom.getElement("save_button"); runButton = goog.dom.getElement("run_button"); $(runButton).click(function() { run(currentMcu); }); $("#open_button").click(_open_file); $(saveAsButton).click(_save_as); $(saveButton).click(_save); $("#upload_as_init").click(function() {_upload_as_init(currentMcu);}); $("#upload").click(function() {_upload(currentMcu);}); // Callback to add found items to the menu. var found_item = function(mcu) { mcu_console.writeLine('Adding found item...'); var connectItem = new goog.ui.MenuItem(mcu.port); connectItem.setCheckable(true); connectMenu.addItem(connectItem); goog.events.listen(connectItem.getContentElement(), goog.events.EventType.CLICK, function(e) { _connect_menu_item_clicked(connectItem, mcu); } ); }; // When the scanButton is clicked, scan for mcu's to add. $("#scan_button").click(function(e) { bounce.Nodemcu.scan(mcu_console, found_item); }); /** * * @param connectItem Menu item that was clicked * @param mcu The associated NodeMCU device * @private */ function _connect_menu_item_clicked(connectItem, mcu) { mcu.connect(function() { // We've now connected the mcu. Update the UI mcu_console.writeLine("Connected"); currentMcu = mcu; _ui.currentMcu = mcu; // Add a tick (Check) to the connection menu item connectItem.setChecked(true); // disconnect any others // Enable the run menu toolbar.getChild("run_button").setEnabled(true); toolbar.getChild("upload").setEnabled(true); toolbar.getChild("upload_as_init").setEnabled(true); /* stopButton.setEnabled(true); */ }); } this.changed = function () { console.log("Workspace changed"); if (is_preparing) { is_preparing = false; } else { fileMenu.getChild("saveas_button").setEnabled(true); if (_currentFileEntry) { fileMenu.getChild("save_button").setEnabled(true); } } } } $(function () { prepare_blockly_workspace(); mcu_console = new OutputConsole($('#output')); ui = new BounceUI(); workspace.addChangeListener(ui.changed); });
Simplify
Bounce/app/start.js
Simplify
<ide><path>ounce/app/start.js <ide> this.display = function(ok_call, cancel_call) { <ide> $(main_div).removeClass("lightbox-hidden"); <ide> this.ok_call = ok_call; <del> this.cancel_call= cancel_call; <ide> ok_button.click(_ok_clicked); <ide> cancel_button.click(function() { <ide> _lb.hide(); <ide> var blocklyDiv = document.getElementById('blocklyDiv'); <ide> workspace = Blockly.inject(blocklyDiv, <ide> {toolbox: goog.dom.$('toolbox'), media: "blockly-nodemcu/media/" }); <del> var onresize = function(e) { <add> var onresize = function() { <ide> // Compute the absolute coordinates and dimensions of blocklyArea. <ide> var element = blocklyArea; <ide> var x = 0; <ide> function export_document() { <ide> var xml = Blockly.Xml.workspaceToDom(workspace); <ide> <del> var xml_text = Blockly.Xml.domToPrettyText(xml); <del> return xml_text; <add> return Blockly.Xml.domToPrettyText(xml); <ide> } <ide> <ide> <ide> } <ide> <ide> function BounceUI() { <del> var toolbar, runButton, stopButton, saveButton, saveAsButton; <add> var toolbar; <ide> var currentMcu; <ide> var connectMenu, fileMenu; <ide> var _ui = this; <ide> <ide> fileMenu = new goog.ui.Menu(); <ide> fileMenu.decorate(goog.dom.getElement('file_menu')); <del> saveAsButton = goog.dom.getElement("saveas_button"); <del> saveButton = goog.dom.getElement("save_button"); <del> runButton = goog.dom.getElement("run_button"); <del> <del> $(runButton).click(function() { <del> run(currentMcu); <del> }); <del> <add> <add> $("#run_button").click(function() { run(currentMcu); }); <ide> $("#open_button").click(_open_file); <del> $(saveAsButton).click(_save_as); <del> $(saveButton).click(_save); <del> $("#upload_as_init").click(function() {_upload_as_init(currentMcu);}); <del> $("#upload").click(function() {_upload(currentMcu);}); <add> $("#saveas_button").click(_save_as); <add> $("#save_button").click(_save); <add> $("#upload_as_init").click(function() { _upload_as_init(currentMcu); }); <add> $("#upload").click(function() { _upload(currentMcu); }); <ide> // Callback to add found items to the menu. <ide> var found_item = function(mcu) { <ide> mcu_console.writeLine('Adding found item...'); <ide> connectItem.setCheckable(true); <ide> connectMenu.addItem(connectItem); <ide> <del> goog.events.listen(connectItem.getContentElement(), <del> goog.events.EventType.CLICK, <del> function(e) { <del> _connect_menu_item_clicked(connectItem, mcu); <del> } <del> ); <add> $(connectItem.getContentElement()).click(function() { <add> _connect_menu_item_clicked(connectItem, mcu); <add> }); <ide> }; <ide> <ide> // When the scanButton is clicked, scan for mcu's to add. <del> $("#scan_button").click(function(e) { <add> $("#scan_button").click(function() { <ide> bounce.Nodemcu.scan(mcu_console, found_item); <ide> }); <ide> <ide> console.log("Workspace changed"); <ide> if (is_preparing) { <ide> is_preparing = false; <add> _modified = true; <ide> } else { <ide> fileMenu.getChild("saveas_button").setEnabled(true); <ide> if (_currentFileEntry) {
JavaScript
bsd-3-clause
1b6ad50b31f550db61a324afa3645ccff8fb601e
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
'use strict'; var app = angular.module('angularApp') .controller('IndSampleCtrl', function (sampleService,navigationService, groupService, $rootScope,$scope,$http,$filter,$location,$routeParams) { $rootScope.tabs = navigationService.query(); $rootScope.groups = groupService.get(); $scope.sampleData = sampleService.sampleData; // $scope.sampleData = {"sampleId":27131906,"sampleName":"UMC_HSTVAMC_NCL_NB-NChandaNNBM2010-01","pointOfContact":null,"composition":null,"functions":null,"characterizations":null,"dataAvailability":null,"createdDate":1275683278000,"keywords":"BIOCOMPATIBILITY<br>GOLD<br>GUM ARABIC","pointOfContactMap":{"organizationDisplayName":["UMC_RadiolD<br>Department of Radiology<br>University of Missouri-Columbia<br>Columbia MO 65212 USA","UMC_RadiolD<br>Department of Radiology<br>University of Missouri-Columbia<br>Columbia MO 65212 USA"],"primaryContact":["true","false"],"role":["investigator","investigator"],"contactPerson":["Raghuraman Kannan<br>[email protected]","Kattesh V Katti<br>[email protected]"]},"pocBeanDomainId":27066372,"availableEntityNames":null,"caNanoLabScore":null,"mincharScore":null,"chemicalAssocs":null,"physicoChars":null,"invitroChars":null,"invivoChars":null,"caNano2MINChar":null,"caNanoMINChar":null}; $scope.sampleId = sampleService.sampleId; // Displays left hand nav for samples section. navTree shows nav and navDetail is page index // $rootScope.navTree = true; $rootScope.navDetail = 0; $scope.goBack = function() { $location.path("/sampleResults").replace(); $location.search('sampleId', null); }; if ($routeParams.sampleId) { $scope.sampleId.data = $routeParams.sampleId; } $scope.returnUserReadableBoolean = function(val) { if (val=='true') { return "Yes"; } return "No"; } $scope.$on('$viewContentLoaded', function(){ $scope.loader = true; $http({method: 'GET', url: '/caNanoLab/rest/sample/view?sampleId=' + $scope.sampleId.data}). success(function(data, status, headers, config) { $scope.sampleData = data; $scope.loader=false; }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.message = data; $scope.loader=false; }); }); });
software/cananolab-webapp/web/scripts/controllers/viewSample.js
'use strict'; var app = angular.module('angularApp') .controller('IndSampleCtrl', function (sampleService,navigationService, groupService, $rootScope,$scope,$http,$filter,$location,$routeParams) { $rootScope.tabs = navigationService.query(); $rootScope.groups = groupService.get(); $scope.sampleData = sampleService.sampleData; // $scope.sampleData = {"sampleId":27131906,"sampleName":"UMC_HSTVAMC_NCL_NB-NChandaNNBM2010-01","pointOfContact":null,"composition":null,"functions":null,"characterizations":null,"dataAvailability":null,"createdDate":1275683278000,"keywords":"BIOCOMPATIBILITY<br>GOLD<br>GUM ARABIC","pointOfContactMap":{"organizationDisplayName":["UMC_RadiolD<br>Department of Radiology<br>University of Missouri-Columbia<br>Columbia MO 65212 USA","UMC_RadiolD<br>Department of Radiology<br>University of Missouri-Columbia<br>Columbia MO 65212 USA"],"primaryContact":["true","false"],"role":["investigator","investigator"],"contactPerson":["Raghuraman Kannan<br>[email protected]","Kattesh V Katti<br>[email protected]"]},"pocBeanDomainId":27066372,"availableEntityNames":null,"caNanoLabScore":null,"mincharScore":null,"chemicalAssocs":null,"physicoChars":null,"invitroChars":null,"invivoChars":null,"caNano2MINChar":null,"caNanoMINChar":null}; $scope.sampleId = sampleService.sampleId; // Displays left hand nav for samples section. navTree shows nav and navDetail is page index // $rootScope.navTree = true; $rootScope.navDetail = 0; $scope.goBack = function() { $location.path("/sampleResults").replace(); $location.search('sampleId', null); }; if ($routeParams.sampleId) { $scope.sampleId.data = $routeParams.sampleId; } $scope.returnUserReadableBoolean = function(val) { if (val=='true') { return "Yes"; } return "No"; } $scope.$on('$viewContentLoaded', function(){ $http({method: 'GET', url: '/caNanoLab/rest/sample/view?sampleId=' + $scope.sampleId.data}). success(function(data, status, headers, config) { $scope.sampleData = data; }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. $scope.message = data; }); }); });
Changed viewSample to include loader
software/cananolab-webapp/web/scripts/controllers/viewSample.js
Changed viewSample to include loader
<ide><path>oftware/cananolab-webapp/web/scripts/controllers/viewSample.js <ide> <ide> <ide> $scope.$on('$viewContentLoaded', function(){ <add> $scope.loader = true; <ide> $http({method: 'GET', url: '/caNanoLab/rest/sample/view?sampleId=' + $scope.sampleId.data}). <ide> success(function(data, status, headers, config) { <ide> $scope.sampleData = data; <add> $scope.loader=false; <add> <ide> }). <ide> error(function(data, status, headers, config) { <ide> // called asynchronously if an error occurs <ide> // or server returns response with an error status. <ide> $scope.message = data; <add> $scope.loader=false; <ide> <ide> }); <ide> });
JavaScript
mit
6ccc79823dd30b5e3316f4e04fdcb4d3b546efdf
0
the-ress/vscode,joaomoreno/vscode,veeramarni/vscode,stringham/vscode,Microsoft/vscode,the-ress/vscode,microlv/vscode,Microsoft/vscode,cleidigh/vscode,Microsoft/vscode,mjbvz/vscode,microsoft/vscode,rishii7/vscode,microlv/vscode,stringham/vscode,joaomoreno/vscode,DustinCampbell/vscode,rishii7/vscode,landonepps/vscode,veeramarni/vscode,stringham/vscode,stringham/vscode,mjbvz/vscode,landonepps/vscode,DustinCampbell/vscode,stringham/vscode,0xmohit/vscode,mjbvz/vscode,veeramarni/vscode,veeramarni/vscode,0xmohit/vscode,mjbvz/vscode,stringham/vscode,joaomoreno/vscode,joaomoreno/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,stringham/vscode,cleidigh/vscode,mjbvz/vscode,eamodio/vscode,Microsoft/vscode,joaomoreno/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,the-ress/vscode,the-ress/vscode,0xmohit/vscode,veeramarni/vscode,hoovercj/vscode,stringham/vscode,mjbvz/vscode,stringham/vscode,joaomoreno/vscode,hoovercj/vscode,landonepps/vscode,veeramarni/vscode,0xmohit/vscode,DustinCampbell/vscode,cleidigh/vscode,Microsoft/vscode,joaomoreno/vscode,microlv/vscode,the-ress/vscode,mjbvz/vscode,DustinCampbell/vscode,rishii7/vscode,mjbvz/vscode,veeramarni/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,the-ress/vscode,microlv/vscode,landonepps/vscode,joaomoreno/vscode,the-ress/vscode,microsoft/vscode,mjbvz/vscode,microlv/vscode,hoovercj/vscode,cleidigh/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,eamodio/vscode,eamodio/vscode,microlv/vscode,hoovercj/vscode,cleidigh/vscode,cleidigh/vscode,stringham/vscode,0xmohit/vscode,Microsoft/vscode,veeramarni/vscode,veeramarni/vscode,microsoft/vscode,DustinCampbell/vscode,landonepps/vscode,Microsoft/vscode,the-ress/vscode,veeramarni/vscode,landonepps/vscode,mjbvz/vscode,0xmohit/vscode,landonepps/vscode,rishii7/vscode,rishii7/vscode,joaomoreno/vscode,eamodio/vscode,microsoft/vscode,0xmohit/vscode,eamodio/vscode,rishii7/vscode,stringham/vscode,cleidigh/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,veeramarni/vscode,landonepps/vscode,Microsoft/vscode,eamodio/vscode,landonepps/vscode,the-ress/vscode,microsoft/vscode,cleidigh/vscode,cleidigh/vscode,0xmohit/vscode,the-ress/vscode,rishii7/vscode,landonepps/vscode,hoovercj/vscode,microsoft/vscode,hoovercj/vscode,hoovercj/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,0xmohit/vscode,landonepps/vscode,landonepps/vscode,Microsoft/vscode,cleidigh/vscode,the-ress/vscode,microlv/vscode,0xmohit/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,stringham/vscode,eamodio/vscode,landonepps/vscode,mjbvz/vscode,stringham/vscode,veeramarni/vscode,hoovercj/vscode,joaomoreno/vscode,cleidigh/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,microlv/vscode,hoovercj/vscode,microsoft/vscode,eamodio/vscode,DustinCampbell/vscode,cleidigh/vscode,DustinCampbell/vscode,microlv/vscode,hoovercj/vscode,eamodio/vscode,DustinCampbell/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,microsoft/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,microlv/vscode,DustinCampbell/vscode,0xmohit/vscode,DustinCampbell/vscode,microsoft/vscode,Microsoft/vscode,DustinCampbell/vscode,veeramarni/vscode,landonepps/vscode,veeramarni/vscode,hoovercj/vscode,eamodio/vscode,rishii7/vscode,rishii7/vscode,joaomoreno/vscode,cleidigh/vscode,joaomoreno/vscode,microsoft/vscode,rishii7/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,eamodio/vscode,landonepps/vscode,rishii7/vscode,rishii7/vscode,the-ress/vscode,hoovercj/vscode,veeramarni/vscode,Microsoft/vscode,microsoft/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,hoovercj/vscode,rishii7/vscode,joaomoreno/vscode,stringham/vscode,hoovercj/vscode,cleidigh/vscode,0xmohit/vscode,the-ress/vscode,veeramarni/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,joaomoreno/vscode,veeramarni/vscode,cra0zy/VSCode,DustinCampbell/vscode,joaomoreno/vscode,stringham/vscode,eamodio/vscode,rishii7/vscode,microlv/vscode,rishii7/vscode,Microsoft/vscode,joaomoreno/vscode,eamodio/vscode,DustinCampbell/vscode,eamodio/vscode,Microsoft/vscode,landonepps/vscode,cleidigh/vscode,rishii7/vscode,microsoft/vscode,mjbvz/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,the-ress/vscode,0xmohit/vscode,mjbvz/vscode,Microsoft/vscode,DustinCampbell/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,landonepps/vscode,microlv/vscode,microlv/vscode,DustinCampbell/vscode,microlv/vscode,microsoft/vscode
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check 'use strict'; (function () { // From https://remysharp.com/2010/07/21/throttling-function-calls function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last, deferTimer; return function () { var context = scope || this; var now = +new Date, args = arguments; if (last && now < last + threshhold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold + last - now); } else { last = now; fn.apply(context, args); } }; } function postMessage(command, args) { window.parent.postMessage({ command: 'did-click-link', data: `command:${command}?${encodeURIComponent(JSON.stringify(args))}` }, 'file://'); } /** * Find the html elements that map to a specific target line in the editor. * * If an exact match, returns a single element. If the line is between elements, * returns the element prior to and the element after the given line. */ function getElementsForSourceLine(targetLine) { const lines = document.getElementsByClassName('code-line'); let previous = lines[0] && +lines[0].getAttribute('data-line') ? { line: +lines[0].getAttribute('data-line'), element: lines[0] } : null; for (const element of lines) { const lineNumber = +element.getAttribute('data-line'); if (isNaN(lineNumber)) { continue; } const entry = { line: lineNumber, element: element }; if (lineNumber === targetLine) { return { previous: entry, next: null }; } else if (lineNumber > targetLine) { return { previous, next: entry }; } previous = entry; } return { previous }; } /** * Find the html elements that are at a specific pixel offset on the page. */ function getLineElementsAtPageOffset(offset) { const lines = document.getElementsByClassName('code-line'); const position = offset - window.scrollY; let previous = null; for (const element of lines) { const line = +element.getAttribute('data-line'); if (isNaN(line)) { continue; } const bounds = element.getBoundingClientRect(); const entry = { element, line }; if (position < bounds.top) { if (previous && previous.fractional < 1) { previous.line += previous.fractional; return { previous }; } return { previous, next: entry }; } entry.fractional = (position - bounds.top) / (bounds.height); previous = entry; } return { previous }; } function getSourceRevealAddedOffset() { return -(window.innerHeight * 1 / 5); } /** * Attempt to reveal the element for a source line in the editor. */ function scrollToRevealSourceLine(line) { const { previous, next } = getElementsForSourceLine(line); marker.update(previous && previous.element); if (previous && settings.scrollPreviewWithEditorSelection) { let scrollTo = 0; if (next) { // Between two elements. Go to percentage offset between them. const betweenProgress = (line - previous.line) / (next.line - previous.line); const elementOffset = next.element.getBoundingClientRect().top - previous.element.getBoundingClientRect().top; scrollTo = previous.element.getBoundingClientRect().top + betweenProgress * elementOffset; } else { scrollTo = previous.element.getBoundingClientRect().top; } window.scroll(0, window.scrollY + scrollTo + getSourceRevealAddedOffset()); } } function getEditorLineNumberForPageOffset(offset) { const { previous, next } = getLineElementsAtPageOffset(offset); if (previous) { if (next) { const betweenProgress = (offset - window.scrollY - previous.element.getBoundingClientRect().top) / (next.element.getBoundingClientRect().top - previous.element.getBoundingClientRect().top); return previous.line + betweenProgress * (next.line - previous.line); } else { return previous.line; } } return null; } class ActiveLineMarker { update(before) { this._unmarkActiveElement(this._current); this._markActiveElement(before); this._current = before; } _unmarkActiveElement(element) { if (!element) { return; } element.className = element.className.replace(/\bcode-active-line\b/g); } _markActiveElement(element) { if (!element) { return; } element.className += ' code-active-line'; } } var scrollDisabled = true; var marker = new ActiveLineMarker(); const settings = JSON.parse(document.getElementById('vscode-markdown-preview-data').getAttribute('data-settings')); function onLoad() { if (settings.scrollPreviewWithEditorSelection) { const initialLine = +settings.line; if (!isNaN(initialLine)) { setTimeout(() => { scrollDisabled = true; scrollToRevealSourceLine(initialLine); }, 0); } } } if (document.readyState === 'loading' || document.readyState === 'uninitialized') { document.addEventListener('DOMContentLoaded', onLoad); } else { onLoad(); } window.addEventListener('resize', () => { scrollDisabled = true; }, true); window.addEventListener('message', (() => { const doScroll = throttle(line => { scrollDisabled = true; scrollToRevealSourceLine(line); }, 50); return event => { const line = +event.data.line; if (!isNaN(line)) { doScroll(line); } }; })(), false); document.addEventListener('dblclick', event => { if (!settings.doubleClickToSwitchToEditor) { return; } // Ignore clicks on links for (let node = event.target; node; node = node.parentNode) { if (node.tagName === "A") { return; } } const offset = event.pageY; const line = getEditorLineNumberForPageOffset(offset); if (!isNaN(line)) { postMessage('_markdown.didClick', [settings.source, line]); } }); document.addEventListener('click', event => { if (!event) { return; } const baseElement = document.getElementsByTagName('base')[0]; /** @type {any} */ let node = event.target; while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { if (node.href.startsWith('file://')) { const [path, fragment] = node.href.replace(/^file:\/\//i, '').split('#'); postMessage('_markdown.openDocumentLink', { path, fragment }); event.preventDefault(); event.stopPropagation(); break; } break; } node = node.parentNode; } }, true); if (settings.scrollEditorWithPreview) { window.addEventListener('scroll', throttle(() => { if (scrollDisabled) { scrollDisabled = false; } else { const line = getEditorLineNumberForPageOffset(window.scrollY); if (!isNaN(line)) { postMessage('_markdown.revealLine', [settings.source, line]); } } }, 50)); } }());
extensions/markdown/media/main.js
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check 'use strict'; (function () { // From https://remysharp.com/2010/07/21/throttling-function-calls function throttle(fn, threshhold, scope) { threshhold || (threshhold = 250); var last, deferTimer; return function () { var context = scope || this; var now = +new Date, args = arguments; if (last && now < last + threshhold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold + last - now); } else { last = now; fn.apply(context, args); } }; } function postMessage(command, args) { window.parent.postMessage({ command: 'did-click-link', data: `command:${command}?${encodeURIComponent(JSON.stringify(args))}` }, 'file://'); } /** * Find the html elements that map to a specific target line in the editor. * * If an exact match, returns a single element. If the line is between elements, * returns the element prior to and the element after the given line. */ function getElementsForSourceLine(targetLine) { const lines = document.getElementsByClassName('code-line'); let previous = lines[0] && +lines[0].getAttribute('data-line') ? { line: +lines[0].getAttribute('data-line'), element: lines[0] } : null; for (const element of lines) { const lineNumber = +element.getAttribute('data-line'); if (isNaN(lineNumber)) { continue; } const entry = { line: lineNumber, element: element }; if (lineNumber === targetLine) { return { previous: entry, next: null }; } else if (lineNumber > targetLine) { return { previous, next: entry }; } previous = entry; } return { previous }; } /** * Find the html elements that are at a specific pixel offset on the page. */ function getLineElementsAtPageOffset(offset) { const lines = document.getElementsByClassName('code-line'); const position = offset - window.scrollY; let previous = null; for (const element of lines) { const line = +element.getAttribute('data-line'); if (isNaN(line)) { continue; } const bounds = element.getBoundingClientRect(); const entry = { element, line }; if (position < bounds.top) { if (previous && previous.fractional < 1) { previous.line += previous.fractional; return { previous }; } return { previous, next: entry }; } entry.fractional = (position - bounds.top) / (bounds.height); previous = entry; } return { previous }; } function getSourceRevealAddedOffset() { return -(window.innerHeight * 1 / 5); } /** * Attempt to reveal the element for a source line in the editor. */ function scrollToRevealSourceLine(line) { const { previous, next } = getElementsForSourceLine(line); marker.update(previous && previous.element); if (previous && settings.scrollPreviewWithEditorSelection) { let scrollTo = 0; if (next) { // Between two elements. Go to percentage offset between them. const betweenProgress = (line - previous.line) / (next.line - previous.line); const elementOffset = next.element.getBoundingClientRect().top - previous.element.getBoundingClientRect().top; scrollTo = previous.element.getBoundingClientRect().top + betweenProgress * elementOffset; } else { scrollTo = previous.element.getBoundingClientRect().top; } window.scroll(0, window.scrollY + scrollTo + getSourceRevealAddedOffset()); } } function getEditorLineNumberForPageOffset(offset) { const { previous, next } = getLineElementsAtPageOffset(offset); if (previous) { if (next) { const betweenProgress = (offset - window.scrollY - previous.element.getBoundingClientRect().top) / (next.element.getBoundingClientRect().top - previous.element.getBoundingClientRect().top); return previous.line + betweenProgress * (next.line - previous.line); } else { return previous.line; } } return null; } class ActiveLineMarker { update(before) { this._unmarkActiveElement(this._current); this._markActiveElement(before); this._current = before; } _unmarkActiveElement(element) { if (!element) { return; } element.className = element.className.replace(/\bcode-active-line\b/g); } _markActiveElement(element) { if (!element) { return; } element.className += ' code-active-line'; } } var scrollDisabled = true; var marker = new ActiveLineMarker(); const settings = JSON.parse(document.getElementById('vscode-markdown-preview-data').getAttribute('data-settings')); function onLoad() { if (settings.scrollPreviewWithEditorSelection) { const initialLine = +settings.line; if (!isNaN(initialLine)) { setTimeout(() => { scrollDisabled = true; scrollToRevealSourceLine(initialLine); }, 0); } } } if (document.readyState === 'loading' || document.readyState === 'uninitialized') { document.addEventListener('DOMContentLoaded', onLoad); } else { onLoad(); } window.addEventListener('resize', () => { scrollDisabled = true; }, true); window.addEventListener('message', (() => { const doScroll = throttle(line => { scrollDisabled = true; scrollToRevealSourceLine(line); }, 50); return event => { const line = +event.data.line; if (!isNaN(line)) { doScroll(line); } }; })(), false); document.addEventListener('dblclick', event => { if (!settings.doubleClickToSwitchToEditor) { return; } // Ignore clicks on links for (let node = event.target; node; node = node.parentNode) { if (node.tagName === "A") { return; } } const offset = event.pageY; const line = getEditorLineNumberForPageOffset(offset); if (!isNaN(line)) { postMessage('_markdown.didClick', [settings.source, line]); } }); document.addEventListener('click', event => { if (!event) { return; } const baseElement = document.getElementsByTagName('base')[0]; /** @type {any} */ let node = event.target; while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { if (node.href.startsWith('file://')) { const [path, frag] = node.href.replace(/^file:\/\//i, '').split('#'); postMessage('_markdown.openDocumentLink', { path, frag }); event.preventDefault(); event.stopPropagation(); break; } break; } node = node.parentNode; } }, true); if (settings.scrollEditorWithPreview) { window.addEventListener('scroll', throttle(() => { if (scrollDisabled) { scrollDisabled = false; } else { const line = getEditorLineNumberForPageOffset(window.scrollY); if (!isNaN(line)) { postMessage('_markdown.revealLine', [settings.source, line]); } } }, 50)); } }());
Fix fragment name
extensions/markdown/media/main.js
Fix fragment name
<ide><path>xtensions/markdown/media/main.js <ide> while (node) { <ide> if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { <ide> if (node.href.startsWith('file://')) { <del> const [path, frag] = node.href.replace(/^file:\/\//i, '').split('#'); <del> postMessage('_markdown.openDocumentLink', { path, frag }); <add> const [path, fragment] = node.href.replace(/^file:\/\//i, '').split('#'); <add> postMessage('_markdown.openDocumentLink', { path, fragment }); <ide> event.preventDefault(); <ide> event.stopPropagation(); <ide> break;
JavaScript
mit
f0edb42dd11df8571d67b0d7bee41b7be33f181d
0
TheBenji/brackets-node-debugger,TheBenji/brackets-node-debugger
/*! * Brackets Node Debugger * * @author Benjamin August * @license http://opensource.org/licenses/MIT */ /*global define, brackets, $ */ define(function (require, exports) { "use strict"; var _ = brackets.getModule("thirdparty/lodash"), EditorManager = brackets.getModule("editor/EditorManager"), DocumentManager = brackets.getModule("document/DocumentManager"); var cm = null, cd = null, breakpoints = [], _nodeDebuggerDomain, gutterName = 'node-debugger-bp-gutter'; /* * Sets the CodeMirror instance for the active editor */ function _updateCm() { var editor = EditorManager.getActiveEditor(); if (!editor || !editor._codeMirror) { return; } cm = editor._codeMirror; //Get the path to the current file as well var _cd = DocumentManager.getCurrentDocument(); if(_cd) { cd = _cd.file.fullPath; } } /* * Set all gutters for the currentDocument */ function _updateGutters() { if (!cm) { return; } var gutters = cm.getOption("gutters").slice(0); if (gutters.indexOf(gutterName) === -1) { gutters.unshift(gutterName); cm.setOption("gutters", gutters); cm.on("gutterClick", gutterClick); } //Set all the gutters now breakpoints.forEach(function(bp) { if(bp.fullPath === cd) { var $marker = $("<div>") .addClass('breakpoint-gutter') .html("●"); bp.cm.setGutterMarker( bp.line, gutterName, $marker[0] ); } }); } /* * remove all gutters from the current document */ function _clearGutters() { if(!cm) { return; } var gutters = cm.getOption("gutters").slice(0), io = gutters.indexOf(gutterName); if (io !== -1) { gutters.splice(io, 1); cm.clearGutter(gutterName); cm.setOption("gutters", gutters); cm.off("gutterClick", gutterClick); } } /* * Sets or removes Breakpoint at cliked line * * @param {CodeMirror} cm * The CodeMirror instance * * @param {Number} n * LineNumber * * @param {String} gutterId */ function gutterClick(cm, n, gutterId) { if (gutterId !== gutterName && gutterId !== "CodeMirror-linenumbers") { return; } var info = cm.lineInfo(n); if(info.gutterMarkers && info.gutterMarkers[gutterName]) { var bp = _.find(breakpoints, function(obj) { return obj.line === n && cd === obj.fullPath; }); _nodeDebuggerDomain.exec("removeBreakpoint", bp.breakpoint); cm.setGutterMarker( bp.line, gutterName, null ); var i = breakpoints.indexOf(bp); breakpoints.splice(i, 1); } else { //TODO Show warning if not connected _nodeDebuggerDomain.exec("setBreakpoint", cd, n); } } /* * @param {NodeDomain} nodeDebuggerDomain */ function init(nodeDebuggerDomain) { _nodeDebuggerDomain = nodeDebuggerDomain; _updateCm(); _updateGutters(); } /* Sets the breakpoint gutter * * @param {breakpoint} bp * bp as object like the V8 Debugger sends it * */ function addBreakpoint(bp) { //If this one of the reconnect BP don't add it var exist = _.find(breakpoints, function(obj) { return obj.line === bp.line && obj.fullPath === bp.fullPath; }); if(!exist) { bp.cm = cm; breakpoints.push(bp); var $marker = $("<div>") .addClass('breakpoint-gutter') .html("●"); bp.cm.setGutterMarker( bp.line, gutterName, $marker[0] ); } } /* * Removes all Breakpoints */ function removeAllBreakpoints() { _clearGutters(); //Delete all breakpoints = []; } /* * Call on connect * Set all breakpoints if there are any * Remove all gutters and request a list of breakpoints * to make sure we're consistent */ function setAllBreakpoints() { console.log('Set Breakpoints: ' + breakpoints.length); if(breakpoints.length > 0) { breakpoints.forEach(function(bp) { _nodeDebuggerDomain.exec("setBreakpoint", bp.fullPath, bp.line); }); //NOTE: Reload all Breakpoints? //Request list of actual set breakpoints //_nodeDebuggerDomain.exec("getBreakpoints"); } } $(DocumentManager).on("currentDocumentChange", function () { _clearGutters(); _updateCm(); _updateGutters(); }); exports.init = init; exports.addBreakpoint = addBreakpoint; exports.setAllBreakpoints = setAllBreakpoints; exports.removeAllBreakpoints = removeAllBreakpoints; });
src/breakpointGutter.js
/*! * Brackets Node Debugger * * @author Benjamin August * @license http://opensource.org/licenses/MIT */ /*global define, brackets, $ */ define(function (require, exports) { "use strict"; var _ = brackets.getModule("thirdparty/lodash"), EditorManager = brackets.getModule("editor/EditorManager"), DocumentManager = brackets.getModule("document/DocumentManager"); var cm = null, cd = null, breakpoints = [], _nodeDebuggerDomain, gutterName = 'node-debugger-bp-gutter'; /* * Sets the CodeMirror instance for the active editor */ function _updateCm() { var editor = EditorManager.getActiveEditor(); if (!editor || !editor._codeMirror) { return; } cm = editor._codeMirror; //Get the path to the current file as well var _cd = DocumentManager.getCurrentDocument(); if(_cd) { cd = _cd.file.fullPath; } } /* * Update gutters, call on document change */ function _updateGutters() { if (!cm) { return; } var gutters = cm.getOption("gutters").slice(0); if (gutters.indexOf(gutterName) === -1) { gutters.unshift(gutterName); cm.setOption("gutters", gutters); cm.on("gutterClick", gutterClick); } } /* * Sets or removes Breakpoint at cliked line * * @param {CodeMirror} cm * The CodeMirror instance * * @param {Number} n * LineNumber * * @param {String} gutterId */ function gutterClick(cm, n, gutterId) { if (gutterId !== gutterName && gutterId !== "CodeMirror-linenumbers") { return; } var info = cm.lineInfo(n); if(info.gutterMarkers && info.gutterMarkers[gutterName]) { var bp = _.find(breakpoints, function(obj) { return obj.line === n && cm === obj.cm; }); _nodeDebuggerDomain.exec("removeBreakpoint", bp.breakpoint); cm.setGutterMarker( bp.line, gutterName, null ); var i = breakpoints.indexOf(bp); breakpoints.splice(i, 1); } else { //TODO Show warning if not connected _nodeDebuggerDomain.exec("setBreakpoint", cd, n); } } /* * @param {NodeDomain} nodeDebuggerDomain */ function init(nodeDebuggerDomain) { _nodeDebuggerDomain = nodeDebuggerDomain; _updateCm(); _updateGutters(); } /* Sets the breakpoint gutter * * @param {breakpoint} bp * bp as object like the V8 Debugger sends it * */ function addBreakpoint(bp) { //If this one of the reconnect BP don't add it var exist = _.find(breakpoints, function(obj) { return obj.line === bp.line && obj.fullPath === bp.fullPath; }); if(!exist) { bp.cm = cm; breakpoints.push(bp); var $marker = $("<div>") .addClass('breakpoint-gutter') .html("●"); bp.cm.setGutterMarker( bp.line, gutterName, $marker[0] ); } } /* * Removes all Breakpoints */ function removeAllBreakpoints() { breakpoints.forEach(function(bp) { bp.cm.setGutterMarker( bp.line, gutterName, null); _nodeDebuggerDomain.exec("removeBreakpoint", bp.breakpoint); }); //Delete all breakpoints = []; } /* * Call on connect * Set all breakpoints if there are any * Remove all gutters and request a list of breakpoints * to make sure we're consistent */ function setAllBreakpoints() { console.log('Set Breakpoints: ' + breakpoints.length); if(breakpoints.length > 0) { breakpoints.forEach(function(bp) { _nodeDebuggerDomain.exec("setBreakpoint", bp.fullPath, bp.line); }); //TODO: Reload all Breakpoints? //Request list of actual set breakpoints //_nodeDebuggerDomain.exec("getBreakpoints"); } } $(DocumentManager).on("currentDocumentChange", function () { _updateCm(); _updateGutters(); }); exports.init = init; exports.addBreakpoint = addBreakpoint; exports.setAllBreakpoints = setAllBreakpoints; exports.removeAllBreakpoints = removeAllBreakpoints; });
Should make the BP stuff a bit better
src/breakpointGutter.js
Should make the BP stuff a bit better
<ide><path>rc/breakpointGutter.js <ide> } <ide> <ide> /* <del> * Update gutters, call on document change <add> * Set all gutters for the currentDocument <ide> */ <ide> function _updateGutters() { <ide> if (!cm) { return; } <ide> gutters.unshift(gutterName); <ide> cm.setOption("gutters", gutters); <ide> cm.on("gutterClick", gutterClick); <add> } <add> <add> //Set all the gutters now <add> breakpoints.forEach(function(bp) { <add> if(bp.fullPath === cd) { <add> var $marker = $("<div>") <add> .addClass('breakpoint-gutter') <add> .html("●"); <add> <add> bp.cm.setGutterMarker( bp.line, gutterName, $marker[0] ); <add> } <add> }); <add> } <add> <add> /* <add> * remove all gutters from the current document <add> */ <add> function _clearGutters() { <add> if(!cm) { return; } <add> var gutters = cm.getOption("gutters").slice(0), <add> io = gutters.indexOf(gutterName); <add> if (io !== -1) { <add> gutters.splice(io, 1); <add> cm.clearGutter(gutterName); <add> cm.setOption("gutters", gutters); <add> cm.off("gutterClick", gutterClick); <ide> } <ide> } <ide> <ide> <ide> if(info.gutterMarkers && info.gutterMarkers[gutterName]) { <ide> var bp = _.find(breakpoints, function(obj) { <del> return obj.line === n && cm === obj.cm; <add> return obj.line === n && cd === obj.fullPath; <ide> }); <ide> _nodeDebuggerDomain.exec("removeBreakpoint", bp.breakpoint); <ide> cm.setGutterMarker( bp.line, gutterName, null ); <ide> * Removes all Breakpoints <ide> */ <ide> function removeAllBreakpoints() { <del> breakpoints.forEach(function(bp) { <del> bp.cm.setGutterMarker( bp.line, gutterName, null); <del> _nodeDebuggerDomain.exec("removeBreakpoint", bp.breakpoint); <del> }); <add> _clearGutters(); <ide> //Delete all <ide> breakpoints = []; <ide> } <ide> breakpoints.forEach(function(bp) { <ide> _nodeDebuggerDomain.exec("setBreakpoint", bp.fullPath, bp.line); <ide> }); <del> //TODO: Reload all Breakpoints? <add> //NOTE: Reload all Breakpoints? <ide> //Request list of actual set breakpoints <ide> //_nodeDebuggerDomain.exec("getBreakpoints"); <ide> } <ide> } <ide> <ide> $(DocumentManager).on("currentDocumentChange", function () { <del> _updateCm(); <add> _clearGutters(); <add> _updateCm(); <ide> _updateGutters(); <ide> }); <ide>
Java
apache-2.0
error: pathspec 'shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/model/physical/jdbc/handler/SQL92DatabaseMetaDataDialectHandlerTest.java' did not match any file(s) known to git
7f3a71b4f0fd479f8e6a549db67f9030fb5c1af8
1
apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
/* * 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.shardingsphere.infra.metadata.model.physical.jdbc.handler; import org.apache.shardingsphere.infra.database.type.dialect.SQL92DatabaseType; import org.apache.shardingsphere.sql.parser.sql.common.constant.QuoteCharacter; import org.junit.Test; import java.sql.SQLException; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; public final class SQL92DatabaseMetaDataDialectHandlerTest extends AbstractDatabaseMetaDataDialectHandlerTest { @Test public void assertGetSchema() throws SQLException { when(getConnection().getSchema()).thenReturn(DATABASE_NAME); String sql92Schema = getSchema(new SQL92DatabaseType()); assertThat(sql92Schema, is(DATABASE_NAME)); } @Test public void assertFormatTableNamePattern() { String sql92TableNamePattern = formatTableNamePattern(new SQL92DatabaseType()); assertThat(sql92TableNamePattern, is(TABLE_NAME_PATTERN)); } @Test public void assertGetQuoteCharacter() { QuoteCharacter sql92QuoteCharacter = getQuoteCharacter(new SQL92DatabaseType()); assertThat(sql92QuoteCharacter.getStartDelimiter(), is("\"")); assertThat(sql92QuoteCharacter.getEndDelimiter(), is("\"")); } }
shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/model/physical/jdbc/handler/SQL92DatabaseMetaDataDialectHandlerTest.java
Add SQL92DatabaseMetaDataDialectHandlerTest (#7871)
shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/model/physical/jdbc/handler/SQL92DatabaseMetaDataDialectHandlerTest.java
Add SQL92DatabaseMetaDataDialectHandlerTest (#7871)
<ide><path>hardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/model/physical/jdbc/handler/SQL92DatabaseMetaDataDialectHandlerTest.java <add>/* <add> * Licensed to the Apache Software Foundation (ASF) under one or more <add> * contributor license agreements. See the NOTICE file distributed with <add> * this work for additional information regarding copyright ownership. <add> * The ASF licenses this file to You under the Apache License, Version 2.0 <add> * (the "License"); you may not use this file except in compliance with <add> * the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.apache.shardingsphere.infra.metadata.model.physical.jdbc.handler; <add> <add>import org.apache.shardingsphere.infra.database.type.dialect.SQL92DatabaseType; <add>import org.apache.shardingsphere.sql.parser.sql.common.constant.QuoteCharacter; <add>import org.junit.Test; <add> <add>import java.sql.SQLException; <add> <add>import static org.hamcrest.CoreMatchers.is; <add>import static org.junit.Assert.assertThat; <add>import static org.mockito.Mockito.when; <add> <add>public final class SQL92DatabaseMetaDataDialectHandlerTest extends AbstractDatabaseMetaDataDialectHandlerTest { <add> <add> @Test <add> public void assertGetSchema() throws SQLException { <add> when(getConnection().getSchema()).thenReturn(DATABASE_NAME); <add> String sql92Schema = getSchema(new SQL92DatabaseType()); <add> assertThat(sql92Schema, is(DATABASE_NAME)); <add> } <add> <add> @Test <add> public void assertFormatTableNamePattern() { <add> String sql92TableNamePattern = formatTableNamePattern(new SQL92DatabaseType()); <add> assertThat(sql92TableNamePattern, is(TABLE_NAME_PATTERN)); <add> } <add> <add> @Test <add> public void assertGetQuoteCharacter() { <add> QuoteCharacter sql92QuoteCharacter = getQuoteCharacter(new SQL92DatabaseType()); <add> assertThat(sql92QuoteCharacter.getStartDelimiter(), is("\"")); <add> assertThat(sql92QuoteCharacter.getEndDelimiter(), is("\"")); <add> } <add>}
Java
apache-2.0
49590d26b2402352361b270675608476258580f7
0
apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis
/* * 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.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Stream; import org.apache.wicket.Component; import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.model.Model; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.tablecol.TableColumnOrderService; import org.apache.isis.commons.collections.Can; import org.apache.isis.commons.internal.collections._Lists; import org.apache.isis.commons.internal.collections._Maps; import org.apache.isis.core.metamodel.facetapi.Facet; import org.apache.isis.core.metamodel.facets.WhereValueFacet; import org.apache.isis.core.metamodel.facets.all.describedas.DescribedAsFacet; import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet; import org.apache.isis.core.metamodel.facets.all.named.NamedFacet; import org.apache.isis.core.metamodel.facets.object.grid.GridFacet; import org.apache.isis.core.metamodel.spec.ManagedObject; import org.apache.isis.core.metamodel.spec.ObjectSpecification; import org.apache.isis.core.metamodel.spec.feature.MixedIn; import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation; import org.apache.isis.core.runtime.memento.ObjectMemento; import org.apache.isis.viewer.wicket.model.models.EntityCollectionModel; import org.apache.isis.viewer.wicket.ui.components.collection.bulk.BulkActionsProvider; import org.apache.isis.viewer.wicket.ui.components.collection.count.CollectionCountProvider; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ColumnAbstract; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ObjectAdapterPropertyColumn; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ObjectAdapterTitleColumn; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ObjectAdapterToggleboxColumn; import org.apache.isis.viewer.wicket.ui.panels.PanelAbstract; import static org.apache.isis.commons.internal.base._With.mapIfPresentElse; import lombok.val; /** * {@link PanelAbstract Panel} that represents a {@link EntityCollectionModel * collection of entity}s rendered using {@link AjaxFallbackDefaultDataTable}. */ public class CollectionContentsAsAjaxTablePanel extends PanelAbstract<EntityCollectionModel> implements CollectionCountProvider { private static final long serialVersionUID = 1L; private static final String ID_TABLE = "table"; private IsisAjaxFallbackDataTable<ManagedObject, String> dataTable; public CollectionContentsAsAjaxTablePanel(final String id, final EntityCollectionModel model) { super(id, model); } @Override protected void onInitialize() { super.onInitialize(); buildGui(); } private void buildGui() { final List<IColumn<ManagedObject, String>> columns = _Lists.newArrayList(); // bulk actions final BulkActionsProvider bulkActionsProvider = getBulkActionsProvider(); ObjectAdapterToggleboxColumn toggleboxColumn = null; if(bulkActionsProvider != null) { toggleboxColumn = bulkActionsProvider.getToggleboxColumn(); if(toggleboxColumn != null) { columns.add(toggleboxColumn); } bulkActionsProvider.configureBulkActions(toggleboxColumn); } final EntityCollectionModel model = getModel(); addTitleColumn( columns, model.getParentObjectAdapterMemento(), getWicketViewerSettings().getMaxTitleLengthInParentedTables(), getWicketViewerSettings().getMaxTitleLengthInStandaloneTables()); addPropertyColumnsIfRequired(columns); val dataProvider = new CollectionContentsSortableDataProvider(model); dataTable = new IsisAjaxFallbackDataTable<>(ID_TABLE, columns, dataProvider, model.getPageSize(), toggleboxColumn); addOrReplace(dataTable); } private BulkActionsProvider getBulkActionsProvider() { Component component = this; while(component != null) { if(component instanceof BulkActionsProvider) { return (BulkActionsProvider) component; } component = component.getParent(); } return null; } private void addTitleColumn( final List<IColumn<ManagedObject, String>> columns, final ObjectMemento parentAdapterMementoIfAny, final int maxTitleParented, final int maxTitleStandalone) { final int maxTitleLength = getModel().isParented()? maxTitleParented: maxTitleStandalone; columns.add(new ObjectAdapterTitleColumn( super.getCommonContext(), parentAdapterMementoIfAny, maxTitleLength)); } private void addPropertyColumnsIfRequired(final List<IColumn<ManagedObject, String>> columns) { final ObjectSpecification typeOfSpec = getModel().getTypeOfSpecification(); final Comparator<String> propertyIdComparator; // same code also appears in EntityPage. // we need to do this here otherwise any tables will render the columns in the wrong order until at least // one object of that type has been rendered via EntityPage. val elementTypeGridFacet = typeOfSpec.getFacet(GridFacet.class); if(elementTypeGridFacet != null) { // the facet should always exist, in fact // just enough to ask for the metadata. // don't pass in any object, just need the meta-data val elementTypeGrid = elementTypeGridFacet.getGrid(null); final Map<String, Integer> propertyIdOrderWithinGrid = new HashMap<>(); elementTypeGrid.getAllPropertiesById().forEach((propertyId, __)->{ propertyIdOrderWithinGrid.put(propertyId, propertyIdOrderWithinGrid.size()); }); // if propertyId is mentioned within grid, put into first 'half' ordered by // occurrence within grid // if propertyId is not mentioned within grid, put into second 'half' ordered by // propertyId (String) in natural order propertyIdComparator = Comparator .<String>comparingInt(propertyId-> propertyIdOrderWithinGrid.getOrDefault(propertyId, Integer.MAX_VALUE)) .thenComparing(Comparator.naturalOrder()); } else { propertyIdComparator = null; } final Where whereContext = getModel().isParented() ? Where.PARENTED_TABLES : Where.STANDALONE_TABLES; final ObjectSpecification parentSpecIfAny = getModel().isParented() ? getCommonContext().reconstructObject(getModel().getParentObjectAdapterMemento()) .getSpecification() : null; final Predicate<ObjectAssociation> predicate = ObjectAssociation.Predicates.PROPERTIES .and((final ObjectAssociation association)->{ final Stream<Facet> facets = association.streamFacets() .filter((final Facet facet)-> facet instanceof WhereValueFacet && facet instanceof HiddenFacet); return !facets .map(facet->(WhereValueFacet) facet) .anyMatch(wawF->wawF.where().includes(whereContext)); }) .and(associationDoesNotReferenceParent(parentSpecIfAny)); final Stream<? extends ObjectAssociation> propertyList = typeOfSpec.streamAssociations(MixedIn.INCLUDED) .filter(predicate); final Map<String, ObjectAssociation> propertyById = _Maps.newLinkedHashMap(); propertyList.forEach(property-> propertyById.put(property.getId(), property)); List<String> propertyIds = _Lists.newArrayList(propertyById.keySet()); if(propertyIdComparator!=null) { propertyIds.sort(propertyIdComparator); } // optional SPI to reorder final Can<TableColumnOrderService> tableColumnOrderServices = getServiceRegistry().select(TableColumnOrderService.class); for (final TableColumnOrderService tableColumnOrderService : tableColumnOrderServices) { final List<String> propertyReorderedIds = reordered(tableColumnOrderService, propertyIds); if(propertyReorderedIds != null) { propertyIds = propertyReorderedIds; break; } } for (final String propertyId : propertyIds) { final ObjectAssociation property = propertyById.get(propertyId); if(property != null) { final ColumnAbstract<ManagedObject> nopc = createObjectAdapterPropertyColumn(property); columns.add(nopc); } } } private List<String> reordered( final TableColumnOrderService tableColumnOrderService, final List<String> propertyIds) { final Class<?> collectionType = getModel().getTypeOfSpecification().getCorrespondingClass(); final ObjectMemento parentObjectAdapterMemento = getModel().getParentObjectAdapterMemento(); if(parentObjectAdapterMemento != null) { val parentObjectAdapter = getCommonContext().reconstructObject(parentObjectAdapterMemento); final Object parent = parentObjectAdapter.getPojo(); final String collectionId = getModel().getCollectionMemento().getId(); return tableColumnOrderService.orderParented(parent, collectionId, collectionType, propertyIds); } else { return tableColumnOrderService.orderStandalone(collectionType, propertyIds); } } static Predicate<ObjectAssociation> associationDoesNotReferenceParent(final ObjectSpecification parentSpec) { if(parentSpec == null) { return __->true; } return new Predicate<ObjectAssociation>() { @Override public boolean test(ObjectAssociation association) { final HiddenFacet facet = association.getFacet(HiddenFacet.class); if(facet == null) { return true; } if (facet.where() != Where.REFERENCES_PARENT) { return true; } final ObjectSpecification assocSpec = association.getSpecification(); final boolean associationSpecIsOfParentSpec = parentSpec.isOfType(assocSpec); final boolean isVisible = !associationSpecIsOfParentSpec; return isVisible; } }; } private ObjectAdapterPropertyColumn createObjectAdapterPropertyColumn(final ObjectAssociation property) { final NamedFacet facet = property.getFacet(NamedFacet.class); final boolean escaped = facet == null || facet.escaped(); final String parentTypeName = property.getOnType().getSpecId().asString(); final String describedAs = mapIfPresentElse(property.getFacet(DescribedAsFacet.class), DescribedAsFacet::value, null); val commonContext = super.getCommonContext(); return new ObjectAdapterPropertyColumn( commonContext, getModel().getVariant(), Model.of(property.getName()), property.getId(), property.getId(), escaped, parentTypeName, describedAs); } @Override protected void onModelChanged() { buildGui(); } @Override public Integer getCount() { final EntityCollectionModel model = getModel(); return model.getCount(); } }
viewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/collectioncontents/ajaxtable/CollectionContentsAsAjaxTablePanel.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.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Stream; import org.apache.wicket.Component; import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.model.Model; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.layout.grid.Grid; import org.apache.isis.applib.services.tablecol.TableColumnOrderService; import org.apache.isis.commons.collections.Can; import org.apache.isis.commons.internal.collections._Lists; import org.apache.isis.commons.internal.collections._Maps; import org.apache.isis.core.metamodel.facetapi.Facet; import org.apache.isis.core.metamodel.facets.WhereValueFacet; import org.apache.isis.core.metamodel.facets.all.describedas.DescribedAsFacet; import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet; import org.apache.isis.core.metamodel.facets.all.named.NamedFacet; import org.apache.isis.core.metamodel.facets.object.grid.GridFacet; import org.apache.isis.core.metamodel.spec.ManagedObject; import org.apache.isis.core.metamodel.spec.ObjectSpecification; import org.apache.isis.core.metamodel.spec.feature.MixedIn; import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation; import org.apache.isis.core.runtime.memento.ObjectMemento; import org.apache.isis.viewer.wicket.model.models.EntityCollectionModel; import org.apache.isis.viewer.wicket.model.models.EntityModel; import org.apache.isis.viewer.wicket.ui.components.collection.bulk.BulkActionsProvider; import org.apache.isis.viewer.wicket.ui.components.collection.count.CollectionCountProvider; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ColumnAbstract; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ObjectAdapterPropertyColumn; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ObjectAdapterTitleColumn; import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ObjectAdapterToggleboxColumn; import org.apache.isis.viewer.wicket.ui.panels.PanelAbstract; import static org.apache.isis.commons.internal.base._With.mapIfPresentElse; import lombok.val; /** * {@link PanelAbstract Panel} that represents a {@link EntityCollectionModel * collection of entity}s rendered using {@link AjaxFallbackDefaultDataTable}. */ public class CollectionContentsAsAjaxTablePanel extends PanelAbstract<EntityCollectionModel> implements CollectionCountProvider { private static final long serialVersionUID = 1L; private static final String ID_TABLE = "table"; private IsisAjaxFallbackDataTable<ManagedObject, String> dataTable; public CollectionContentsAsAjaxTablePanel(final String id, final EntityCollectionModel model) { super(id, model); } @Override protected void onInitialize() { super.onInitialize(); buildGui(); } private void buildGui() { final List<IColumn<ManagedObject, String>> columns = _Lists.newArrayList(); // bulk actions final BulkActionsProvider bulkActionsProvider = getBulkActionsProvider(); ObjectAdapterToggleboxColumn toggleboxColumn = null; if(bulkActionsProvider != null) { toggleboxColumn = bulkActionsProvider.getToggleboxColumn(); if(toggleboxColumn != null) { columns.add(toggleboxColumn); } bulkActionsProvider.configureBulkActions(toggleboxColumn); } final EntityCollectionModel model = getModel(); addTitleColumn( columns, model.getParentObjectAdapterMemento(), getWicketViewerSettings().getMaxTitleLengthInParentedTables(), getWicketViewerSettings().getMaxTitleLengthInStandaloneTables()); addPropertyColumnsIfRequired(columns); val dataProvider = new CollectionContentsSortableDataProvider(model); dataTable = new IsisAjaxFallbackDataTable<>(ID_TABLE, columns, dataProvider, model.getPageSize(), toggleboxColumn); addOrReplace(dataTable); } private BulkActionsProvider getBulkActionsProvider() { Component component = this; while(component != null) { if(component instanceof BulkActionsProvider) { return (BulkActionsProvider) component; } component = component.getParent(); } return null; } private void addTitleColumn( final List<IColumn<ManagedObject, String>> columns, final ObjectMemento parentAdapterMementoIfAny, final int maxTitleParented, final int maxTitleStandalone) { final int maxTitleLength = getModel().isParented()? maxTitleParented: maxTitleStandalone; columns.add(new ObjectAdapterTitleColumn( super.getCommonContext(), parentAdapterMementoIfAny, maxTitleLength)); } private void addPropertyColumnsIfRequired(final List<IColumn<ManagedObject, String>> columns) { final ObjectSpecification typeOfSpec = getModel().getTypeOfSpecification(); final Comparator<String> propertyIdComparator; // same code also appears in EntityPage. // we need to do this here otherwise any tables will render the columns in the wrong order until at least // one object of that type has been rendered via EntityPage. final GridFacet gridFacet = typeOfSpec.getFacet(GridFacet.class); if(gridFacet != null) { // the facet should always exist, in fact // just enough to ask for the metadata. // This will cause the current ObjectSpec to be updated as a side effect. final EntityModel entityModel = getModel().getEntityModel(); final ManagedObject objectAdapterIfAny = entityModel != null ? entityModel.getObject() : null; final Grid grid = gridFacet.getGrid(objectAdapterIfAny); final Map<String, Integer> propertyIdOrderWithinGrid = new HashMap<>(); grid.getAllPropertiesById().forEach((propertyId, __)->{ propertyIdOrderWithinGrid.put(propertyId, propertyIdOrderWithinGrid.size()); }); // if propertyId is mentioned within grid, put into first 'half' ordered by // occurrence within grid // if propertyId is not mentioned within grid, put into second 'half' ordered by // propertyId (String) in natural order propertyIdComparator = Comparator .<String>comparingInt(propertyId-> propertyIdOrderWithinGrid.getOrDefault(propertyId, Integer.MAX_VALUE)) .thenComparing(Comparator.naturalOrder()); } else { propertyIdComparator = null; } final Where whereContext = getModel().isParented() ? Where.PARENTED_TABLES : Where.STANDALONE_TABLES; final ObjectSpecification parentSpecIfAny = getModel().isParented() ? getCommonContext().reconstructObject(getModel().getParentObjectAdapterMemento()) .getSpecification() : null; final Predicate<ObjectAssociation> predicate = ObjectAssociation.Predicates.PROPERTIES .and((final ObjectAssociation association)->{ final Stream<Facet> facets = association.streamFacets() .filter((final Facet facet)-> facet instanceof WhereValueFacet && facet instanceof HiddenFacet); return !facets .map(facet->(WhereValueFacet) facet) .anyMatch(wawF->wawF.where().includes(whereContext)); }) .and(associationDoesNotReferenceParent(parentSpecIfAny)); final Stream<? extends ObjectAssociation> propertyList = typeOfSpec.streamAssociations(MixedIn.INCLUDED) .filter(predicate); final Map<String, ObjectAssociation> propertyById = _Maps.newLinkedHashMap(); propertyList.forEach(property-> propertyById.put(property.getId(), property)); List<String> propertyIds = _Lists.newArrayList(propertyById.keySet()); if(propertyIdComparator!=null) { propertyIds.sort(propertyIdComparator); } // optional SPI to reorder final Can<TableColumnOrderService> tableColumnOrderServices = getServiceRegistry().select(TableColumnOrderService.class); for (final TableColumnOrderService tableColumnOrderService : tableColumnOrderServices) { final List<String> propertyReorderedIds = reordered(tableColumnOrderService, propertyIds); if(propertyReorderedIds != null) { propertyIds = propertyReorderedIds; break; } } for (final String propertyId : propertyIds) { final ObjectAssociation property = propertyById.get(propertyId); if(property != null) { final ColumnAbstract<ManagedObject> nopc = createObjectAdapterPropertyColumn(property); columns.add(nopc); } } } private List<String> reordered( final TableColumnOrderService tableColumnOrderService, final List<String> propertyIds) { final Class<?> collectionType = getModel().getTypeOfSpecification().getCorrespondingClass(); final ObjectMemento parentObjectAdapterMemento = getModel().getParentObjectAdapterMemento(); if(parentObjectAdapterMemento != null) { val parentObjectAdapter = getCommonContext().reconstructObject(parentObjectAdapterMemento); final Object parent = parentObjectAdapter.getPojo(); final String collectionId = getModel().getCollectionMemento().getId(); return tableColumnOrderService.orderParented(parent, collectionId, collectionType, propertyIds); } else { return tableColumnOrderService.orderStandalone(collectionType, propertyIds); } } static Predicate<ObjectAssociation> associationDoesNotReferenceParent(final ObjectSpecification parentSpec) { if(parentSpec == null) { return __->true; } return new Predicate<ObjectAssociation>() { @Override public boolean test(ObjectAssociation association) { final HiddenFacet facet = association.getFacet(HiddenFacet.class); if(facet == null) { return true; } if (facet.where() != Where.REFERENCES_PARENT) { return true; } final ObjectSpecification assocSpec = association.getSpecification(); final boolean associationSpecIsOfParentSpec = parentSpec.isOfType(assocSpec); final boolean isVisible = !associationSpecIsOfParentSpec; return isVisible; } }; } private ObjectAdapterPropertyColumn createObjectAdapterPropertyColumn(final ObjectAssociation property) { final NamedFacet facet = property.getFacet(NamedFacet.class); final boolean escaped = facet == null || facet.escaped(); final String parentTypeName = property.getOnType().getSpecId().asString(); final String describedAs = mapIfPresentElse(property.getFacet(DescribedAsFacet.class), DescribedAsFacet::value, null); val commonContext = super.getCommonContext(); return new ObjectAdapterPropertyColumn( commonContext, getModel().getVariant(), Model.of(property.getName()), property.getId(), property.getId(), escaped, parentTypeName, describedAs); } @Override protected void onModelChanged() { buildGui(); } @Override public Integer getCount() { final EntityCollectionModel model = getModel(); return model.getCount(); } }
ISIS-2534: Wicket: fixes CollectionContentsAsAjaxTablePanel misusing the GridFacet
viewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/collectioncontents/ajaxtable/CollectionContentsAsAjaxTablePanel.java
ISIS-2534: Wicket: fixes CollectionContentsAsAjaxTablePanel misusing the GridFacet
<ide><path>iewers/wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/collectioncontents/ajaxtable/CollectionContentsAsAjaxTablePanel.java <ide> import org.apache.wicket.model.Model; <ide> <ide> import org.apache.isis.applib.annotation.Where; <del>import org.apache.isis.applib.layout.grid.Grid; <ide> import org.apache.isis.applib.services.tablecol.TableColumnOrderService; <ide> import org.apache.isis.commons.collections.Can; <ide> import org.apache.isis.commons.internal.collections._Lists; <ide> import org.apache.isis.core.metamodel.spec.feature.ObjectAssociation; <ide> import org.apache.isis.core.runtime.memento.ObjectMemento; <ide> import org.apache.isis.viewer.wicket.model.models.EntityCollectionModel; <del>import org.apache.isis.viewer.wicket.model.models.EntityModel; <ide> import org.apache.isis.viewer.wicket.ui.components.collection.bulk.BulkActionsProvider; <ide> import org.apache.isis.viewer.wicket.ui.components.collection.count.CollectionCountProvider; <ide> import org.apache.isis.viewer.wicket.ui.components.collectioncontents.ajaxtable.columns.ColumnAbstract; <ide> <ide> private void addPropertyColumnsIfRequired(final List<IColumn<ManagedObject, String>> columns) { <ide> final ObjectSpecification typeOfSpec = getModel().getTypeOfSpecification(); <del> <del> <ide> final Comparator<String> propertyIdComparator; <ide> <ide> // same code also appears in EntityPage. <ide> // we need to do this here otherwise any tables will render the columns in the wrong order until at least <ide> // one object of that type has been rendered via EntityPage. <del> final GridFacet gridFacet = typeOfSpec.getFacet(GridFacet.class); <del> if(gridFacet != null) { <add> val elementTypeGridFacet = typeOfSpec.getFacet(GridFacet.class); <add> if(elementTypeGridFacet != null) { <ide> // the facet should always exist, in fact <ide> // just enough to ask for the metadata. <del> // This will cause the current ObjectSpec to be updated as a side effect. <del> final EntityModel entityModel = getModel().getEntityModel(); <del> final ManagedObject objectAdapterIfAny = entityModel != null ? entityModel.getObject() : null; <del> final Grid grid = gridFacet.getGrid(objectAdapterIfAny); <del> <add> <add> // don't pass in any object, just need the meta-data <add> val elementTypeGrid = elementTypeGridFacet.getGrid(null); <ide> <ide> final Map<String, Integer> propertyIdOrderWithinGrid = new HashMap<>(); <del> grid.getAllPropertiesById().forEach((propertyId, __)->{ <add> elementTypeGrid.getAllPropertiesById().forEach((propertyId, __)->{ <ide> propertyIdOrderWithinGrid.put(propertyId, propertyIdOrderWithinGrid.size()); <ide> }); <ide>
Java
apache-2.0
51d3f849b87719a0e778d68e546f471424d680e4
0
finn-no/solr-integrationtest-support,finn-no/solr-integrationtest-support
package no.finn.solr.integration; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest; import org.apache.solr.client.solrj.response.Group; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.component.SearchComponent; import org.hamcrest.CoreMatchers; import static java.util.Optional.ofNullable; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class SolrTestServer { private final File solrHome; private final Path dataDir; private final CoreContainer coreContainer; private final Optional<SolrCore> core; private final SolrClient client; private String defaultContentField = "body"; private String groupField = null; private String search; private String uniqueKeyField = "id"; private SolrQuery solrQuery = new SolrQuery(); private void configureSysProperties(File solrHome, Path data) { System.out.println("Running from: " + solrHome); System.out.println("Datadir is set to " + dataDir); System.setProperty("solr.solr.home", solrHome.getAbsolutePath()); System.setProperty("solr.data.dir", System.getProperty("solr.data.dir", dataDir.toAbsolutePath().toString())); } private File findRootOfTests(File folder) { if ("target".equals(folder.getName()) || "build".equals(folder.getName())) { return folder; } return findRootOfTests(folder.getParentFile()); } private File findSolrXml(File folder) { Optional<File> solrXml = FileUtils.listFiles(folder, new String[]{"xml"}, true) .stream() .filter(x -> x.getName().equals("solr.xml")) .findFirst(); assert solrXml.isPresent(); return solrXml.get(); } private File findSolrFolder() { ClassLoader loader = SolrTestServer.class.getClassLoader(); URL root = loader.getResource("."); File solrXml = ofNullable(root) .map(URL::getPath) .map(File::new) .map(classRoot -> findRootOfTests(classRoot)) .map(testRoot -> findSolrXml(testRoot)) .orElseThrow(() -> new IllegalStateException("Could not find Solr Home folder when looking from " +root)); System.out.println(solrXml); return solrXml.getParentFile(); } /** * Wires up a Solr Server */ public SolrTestServer() { this.solrHome = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString()); this.dataDir = solrHome.toPath().resolve("data"); try { copyFilesTo(solrHome, findSolrFolder()); } catch (IOException e) { System.out.println("IOException while copying to temporary folder"); } configureSysProperties(solrHome, dataDir); Path solrPath = solrHome.toPath().toAbsolutePath(); this.coreContainer = CoreContainer.createAndLoad(solrPath); assertNoLoadErrors(coreContainer); core = getCore(coreContainer); client = core.map(EmbeddedSolrServer::new).orElse(null); } private void assertNoLoadErrors(CoreContainer coreContainer) { Map<String, CoreContainer.CoreLoadFailure> coreInitFailures = coreContainer.getCoreInitFailures(); for (CoreContainer.CoreLoadFailure coreLoadFailure : coreInitFailures.values()) { System.out.println("Error in loading core: " + coreLoadFailure.cd.getCollectionName()); System.out.println("Instancedir set to: " + coreLoadFailure.cd.getInstanceDir()); System.out.println("Error message: " + coreLoadFailure.exception.getMessage()); System.out.println("Cause: " + coreLoadFailure.exception.getCause()); if (coreLoadFailure.exception.getCause().getCause() != null) { System.out.println("Cause of Cause: " + coreLoadFailure.exception.getCause().getCause()); } } assert coreInitFailures.size() == 0; } private void copyFilesTo(File solrHome, File solrFolder) throws IOException { FileUtils.copyDirectory(solrFolder, solrHome); } private Optional<SolrCore> getCore(CoreContainer coreContainer) { return coreContainer.getAllCoreNames() .stream() .findFirst() .map(coreContainer::getCore); } private boolean isGrouped() { return StringUtils.isNotBlank(groupField); } public void shutdown() throws IOException { client.close(); core.filter(c -> !c.isClosed()).ifPresent(SolrCore::close); ofNullable(coreContainer).filter(CoreContainer::isShutDown).ifPresent(CoreContainer::shutdown); solrHome.delete(); } public Optional<SearchComponent> getSearchComponent(String componentName) { return core.map(c -> c.getSearchComponent(componentName)); } /** * Sets a parameter * * @param parameter name of the parameter * @param values values of the parameter * @return The server currently under test */ public SolrTestServer withParam(String parameter, String... values) { solrQuery.set(parameter, values); return this; } /** * Resets the SolrQuery * * @return The server currently under test */ public SolrTestServer withEmptyParams() { solrQuery = new SolrQuery(); return this; } /** * Empties the index * * @return The server currently under test * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public SolrTestServer withEmptyIndex() throws IOException, SolrServerException { client.deleteByQuery("*:*"); client.commit(); return this; } /** * Sets a new default field to add content into * * @param defaultField name of the field * @return The server currently under test */ public SolrTestServer withDefaultContentField(String defaultField) { this.defaultContentField = defaultField; return this; } /** * Sets a field to group on * This will make the query use the solr group parameters * * @param groupField name of the field * @return The server currently under test */ public SolrTestServer withGrouping(String groupField) { this.groupField = groupField; return this; } /** * Sets up highlighting * It sets hl=true * hl.field = [highlightedField] * hl.alternateField = [alternateField] * * @param highlightedField which field to highlight * @param alternateField if no content can be found in highlightedField, use this instead * @return The server currently under test */ public SolrTestServer withHighlighting(String highlightedField, String alternateField) { return withParam("hl", "true") .withParam("hl.fl", highlightedField) .withParam("hl.alternateField", alternateField); } /** * Updates the fl parameter * * @param fields Which fields to request from Solr * @return The server currently under test */ public SolrTestServer withReturnedFields(String... fields) { return withParam("fl", StringUtils.join(fields, ",")); } // // Indexing / adding docs // /** * Adds a single document to the index * * @param doc - document to add * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void addDocument(SolrInputDocument doc) throws IOException, SolrServerException { client.add(doc); client.commit(); } /** * Gets document from a document builder * * @param docBuilder - build to get document from * @return id of the document added to the index * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocument(SolrInputDocumentBuilder docBuilder) throws IOException, SolrServerException { addDocument(docBuilder.getDoc()); return docBuilder.getDocId(); } /** * Adds a single string to the default content field * * @param content content to add * @return id of the document * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocumentWith(String content) throws IOException, SolrServerException { SolrInputDocumentBuilder docBuilder = new SolrInputDocumentBuilder(defaultContentField).with(content); return addDocument(docBuilder); } /** * Adds a single string to field specified * * @param fieldName name of the field to add content to * @param content content to add * @return id of the document * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocumentWithField(String fieldName, String content) throws IOException, SolrServerException { SolrInputDocumentBuilder docBuilder = new SolrInputDocumentBuilder(fieldName).with(content); return addDocument(docBuilder); } /** * Adds a single object value to the field specified * * @param fieldName name of the field to add content to * @param content content to add * @return id of the document * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocumentWithField(String fieldName, Object content) throws IOException, SolrServerException { SolrInputDocumentBuilder docBuilder = new SolrInputDocumentBuilder(fieldName).with(content); return addDocument(docBuilder); } /** * Adds docContents to the default content field * * @param docContent content(s) to add * @return id(s) of the document(s) added * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long[] addDocumentsWith(String... docContent) throws IOException, SolrServerException { List<Long> docIds = new ArrayList<>(); for (String content : docContent) { docIds.add(addDocumentWith(content)); } return docIds.toArray(new Long[docIds.size()]); } /** * Adds docContents to the specified field name * * @param fieldName name of the field to add contents to * @param docContents content(s) to add * @return id(s) of the document(s) added * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long[] addDocumentsWithField(String fieldName, String... docContents) throws IOException, SolrServerException { List<Long> docIds = new ArrayList<>(); for (String docContent : docContents) { docIds.add(addDocumentWithField(fieldName, docContent)); } return docIds.toArray(new Long[docIds.size()]); } /** * Convenience method to add more than one document at the time from several document builders * * @param documentBuilders - builder(s) to add to the index * @return id(s) of the document(s) added * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long[] addDocuments(SolrInputDocumentBuilder... documentBuilders) throws IOException, SolrServerException { List<Long> docIds = new ArrayList<>(); for (SolrInputDocumentBuilder documentBuilder : documentBuilders) { docIds.add(addDocument(documentBuilder)); } return docIds.toArray(new Long[docIds.size()]); } /** * Perform an update call against the extract endpoint * * @param file file to send as an update request * @param contentType MIME content-type * @param params - further params to send * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void updateStreamRequest(File file, String contentType, Map<String, String> params) throws IOException, SolrServerException { ContentStreamUpdateRequest updateRequest = new ContentStreamUpdateRequest("/update/extract"); for (Map.Entry<String, String> e : params.entrySet()) { updateRequest.setParam(e.getKey(), e.getValue()); } updateRequest.addFile(file, contentType); client.request(updateRequest); } /** * Performs a search and asserts exactly one hit. * * @param search search to perform * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertOneHit(String search) throws IOException, SolrServerException { performSearchAndAssertNoOfHits(search, 1); } /** * Performs a search and checks that ids are present in the result. * Guarantees that only the expectedIds are present by verifying hit length equal to expectedIds * * @param search search to perform * @param expectedIds ids of the documents expected to be found by the search * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertHits(String search, Long... expectedIds) throws IOException, SolrServerException { QueryResponse response = dismaxSearch(search); verifyHits(response, expectedIds.length); assertDocumentsInResult(response, expectedIds); } /** * Performs a search and checks number of hits * * @param search search to perform * @param resultCount number of documents expected to be found by the search * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertNoOfHits(String search, long resultCount) throws IOException, SolrServerException { verifyHits(dismaxSearch(search), resultCount); } /** * Performs a search and verifies that it does not find anything in the index * * @param search search to perform * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertNoHits(String search) throws IOException, SolrServerException { performSearchAndAssertNoOfHits(search, 0L); } /** * Performs a search * * @param searchQuery query to perform * @return The raw QueryResponse from the solr server * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public QueryResponse search(String searchQuery) throws IOException, SolrServerException { search = searchQuery; withParam("q", StringUtils.defaultIfBlank(searchQuery, "")); return search(); } /** * Performs a query of the form [field]:[query] * * @param field name of the field to search in * @param value expected value of the field * @return The raw QueryResponse from the solr server * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public QueryResponse search(String field, String value) throws IOException, SolrServerException { search = field + ":" + value; withParam("q", StringUtils.defaultIfBlank(field + ":" + value, "")); return search(); } /** * Performs a search with the parameters currently set * * @return The Solr QueryResponse * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public QueryResponse search() throws IOException, SolrServerException { if (StringUtils.isEmpty(solrQuery.get("q"))) { withParam("hl.q", "*:*"); } return client.query(solrQuery); } /** * Performs a search using the dismax query handler * * @param query search to perform * @return The Solr QueryResponse * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public QueryResponse dismaxSearch(String query) throws IOException, SolrServerException { withParam("qt", "dismax"); return search(query); } // // Verify/asserts // /** * Verifies that ids come in the order expected. Used to check that sorts are working as expected * @param response the result of the search * @param sequence the ids in the correct sequence */ public void verifySequenceOfHits(QueryResponse response, Long... sequence) { assertThat("getNumFound: " + response.getResults().getNumFound() + " not same length as expexted: " + sequence.length, response.getResults().getNumFound(), is(Long.valueOf(sequence.length))); int i = 0; for (long id : sequence) { String assertMessage = "Document " + i + " should have docId: " + id; assertThat(assertMessage, Long.parseLong((String) response.getResults().get(i).getFirstValue(uniqueKeyField)), CoreMatchers.is(id)); i++; } } /** * Verifiies that we've got exactly one hit * @param response the result of the search */ public void verifyOneHit(QueryResponse response) { verifyHits(response, 1L); } /** * Verifies `hits` number of hits * @param response the result of the search * @param hits amount of expected hits */ public void verifyHits(QueryResponse response, long hits) { long matches = isGrouped() ? response.getGroupResponse().getValues().get(0).getMatches() : response.getResults().getNumFound(); assertThat("Search for \"" + search + "\" should get " + hits + " results, but got: " + matches, matches, is(hits)); } /** * Verifies that ngroups response is of expected value * @param response the result of the search * @param groups amount of groups expected */ public void verifyNoOfGroups(QueryResponse response, long groups) { if (isGrouped()) { int matchGroups = response.getGroupResponse().getValues().get(0).getNGroups(); assertThat("Search for \"" + search + "\" should get " + groups + " groups, but got: " + matchGroups, (long) matchGroups, is(groups)); } } /** * JUnit assert that the document ids can be found in the result * @param response QueryResponse to check * @param docIds ids expected */ public void assertDocumentsInResult(QueryResponse response, Long... docIds) { for (Long docId : docIds) { assertTrue("DocId: [" + docId + "] should be in the result set", isGrouped() ? docIdIsInGroupedResponse(response, docId) : docIdIsInList(docId, response.getResults())); } } /** * One of the groups returned from the search contains the id * @param response Query response to check * @param docId id expected * @return whether or not the docid was contained in any of groups */ private boolean docIdIsInGroupedResponse(QueryResponse response, Long docId) { List<SolrDocument> docs = new ArrayList<>(); for (Group group : response.getGroupResponse().getValues().get(0).getValues()) { SolrDocumentList list = group.getResult(); for (SolrDocument doc : list) { docs.add(doc); } } return docIdIsInList(docId, docs); } private boolean docIdIsInList(Long docId, List<SolrDocument> docs) { for (SolrDocument doc : docs) { Object id = doc.getFirstValue(uniqueKeyField); if (id == null) { throw new NullPointerException(uniqueKeyField + " not found in doc. you should probably call solr.withReturnedFields" + "(\"" + uniqueKeyField + "\")" + " before calling the tests, " + "" + "or add \"+"+uniqueKeyField+ "\" to the fl-parameter in solrconfig.xml"); } if (id.equals(String.valueOf(docId))) { return true; } } return false; } // Highlighting/snippets /** * Checks that highlighting works as expected * * @param search query * @param startHighlightingElement the starting element to look for * @param endHighlightingElement the closing element to look for * @param snippets the snippets returned from solr as highlights */ public void assertHighlight(String search, String startHighlightingElement, String endHighlightingElement, List<String> snippets) { String pattern = String.format("%s%s%s", startHighlightingElement, search, endHighlightingElement); for (String snippet : snippets) { if (snippet.contains(search)) { assertTrue("missing " + pattern + " in: '" + snippet + "'", snippet.contains(pattern)); } } } private List<String> getSnippets(Map<String, Map<String, List<String>>> highlighting) { List<String> snippets = new ArrayList<>(); for (Map<String, List<String>> doc : highlighting.values()) { for (List<String> highlightedSnippets : doc.values()) { snippets.addAll(highlightedSnippets); } } return snippets; } /** * @param response QueryResponse to fetch highlight snippets from * @return Highlight snippets */ public List<String> getSnippets(QueryResponse response) { return getSnippets(response.getHighlighting()); } public void assertTeaser(String query, String teaser, List<String> snippets) { for (String snippet : snippets) { if (query == null || !snippet.contains(query)) { assertThat("teaser: " + teaser + " != snippet: " + snippet, snippet, is(teaser)); } } } // // Faceting // /** * JUnit assert that a facet query has the expected hit count * * @param response where to locate the facet * @param facetName name of the facet * @param hitCount expected hit count */ public void assertFacetQueryHasHitCount(QueryResponse response, String facetName, int hitCount) { final int facetCount = response.getFacetQuery().get(facetName); assertThat("facetCount: " + facetCount + " != expected hitcount: " + hitCount, facetCount, is(hitCount)); } /** * Convenience method to run raw Solr commands rather than using the helper methods * * @return The raw SolrClient */ public SolrClient getClient() { return this.client; } }
src/main/java/no/finn/solr/integration/SolrTestServer.java
package no.finn.solr.integration; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest; import org.apache.solr.client.solrj.response.Group; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.component.SearchComponent; import org.hamcrest.CoreMatchers; import static java.util.Optional.ofNullable; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class SolrTestServer { private final File solrHome; private final Path dataDir; private final CoreContainer coreContainer; private final Optional<SolrCore> core; private final SolrClient client; private String defaultContentField = "body"; private String groupField = null; private String search; private String uniqueKeyField = "id"; private SolrQuery solrQuery = new SolrQuery(); private void configureSysProperties(File solrHome, Path data) { System.out.println("Running from: " + solrHome); System.out.println("Datadir is set to " + dataDir); System.setProperty("solr.solr.home", solrHome.getAbsolutePath()); System.setProperty("solr.data.dir", System.getProperty("solr.data.dir", dataDir.toAbsolutePath().toString())); } private File findRootOfTests(File folder) { if ("target".equals(folder.getName()) || "build".equals(folder.getName())) { return folder; } return findRootOfTests(folder.getParentFile()); } private File findSolrXml(File folder) { Optional<File> solrXml = FileUtils.listFiles(folder, new String[]{"xml"}, true) .stream() .filter(x -> x.getName().equals("solr.xml")) .findFirst(); assert solrXml.isPresent(); return solrXml.get(); } private File findSolrFolder() { ClassLoader loader = SolrTestServer.class.getClassLoader(); URL root = loader.getResource("."); File solrXml = ofNullable(root) .map(URL::getPath) .map(File::new) .map(classRoot -> findRootOfTests(classRoot)) .map(testRoot -> findSolrXml(testRoot)) .orElseThrow(() -> new IllegalStateException("Could not find Solr Home folder when looking from " +root)); System.out.println(solrXml); return solrXml.getParentFile(); } /** * Wires up a Solr Server */ public SolrTestServer() { this.solrHome = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString()); this.dataDir = solrHome.toPath().resolve("data"); try { copyFilesTo(solrHome, findSolrFolder()); } catch (IOException e) { System.out.println("IOException while copying to temporary folder"); } configureSysProperties(solrHome, dataDir); Path solrPath = solrHome.toPath().toAbsolutePath(); this.coreContainer = CoreContainer.createAndLoad(solrPath); assertNoLoadErrors(coreContainer); core = getCore(coreContainer); client = core.map(c -> new EmbeddedSolrServer(c)).orElse(null); } private void assertNoLoadErrors(CoreContainer coreContainer) { Map<String, CoreContainer.CoreLoadFailure> coreInitFailures = coreContainer.getCoreInitFailures(); for (CoreContainer.CoreLoadFailure coreLoadFailure : coreInitFailures.values()) { System.out.println("Error in loading core: " + coreLoadFailure.cd.getCollectionName()); System.out.println("Instancedir set to: " +coreLoadFailure.cd.getInstanceDir()); System.out.println("Error message: " +coreLoadFailure.exception.getMessage()); System.out.println("Cause: " +coreLoadFailure.exception.getCause()); if (coreLoadFailure.exception.getCause().getCause() != null) { System.out.println("Cause of Cause: " +coreLoadFailure.exception.getCause().getCause()); } } assert coreInitFailures.size() == 0; } private void copyFilesTo(File solrHome, File solrFolder) throws IOException { FileUtils.copyDirectory(solrFolder, solrHome); } private Optional<SolrCore> getCore(CoreContainer coreContainer) { return coreContainer.getAllCoreNames() .stream() .findFirst() .map(name -> coreContainer.getCore(name)); } private boolean isGrouped() { return StringUtils.isNotBlank(groupField); } public void shutdown() throws IOException { client.close(); core.filter(c -> !c.isClosed()).ifPresent(SolrCore::close); ofNullable(coreContainer).filter(CoreContainer::isShutDown).ifPresent(CoreContainer::shutdown); solrHome.delete(); } public Optional<SearchComponent> getSearchComponent(String componentName) { return core.map(c -> c.getSearchComponent(componentName)); } /** * Sets a parameter * * @param parameter name of the parameter * @param values values of the parameter * @return The server currently under test */ public SolrTestServer withParam(String parameter, String... values) { solrQuery.set(parameter, values); return this; } /** * Resets the SolrQuery * * @return The server currently under test */ public SolrTestServer withEmptyParams() { solrQuery = new SolrQuery(); return this; } /** * Empties the index * * @return The server currently under test * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public SolrTestServer withEmptyIndex() throws IOException, SolrServerException { client.deleteByQuery("*:*"); client.commit(); return this; } /** * Sets a new default field to add content into * * @param defaultField name of the field * @return The server currently under test */ public SolrTestServer withDefaultContentField(String defaultField) { this.defaultContentField = defaultField; return this; } /** * Sets a field to group on * This will make the query use the solr group parameters * * @param groupField name of the field * @return The server currently under test */ public SolrTestServer withGrouping(String groupField) { this.groupField = groupField; return this; } /** * Sets up highlighting * It sets hl=true * hl.field = [highlightedField] * hl.alternateField = [alternateField] * * @param highlightedField which field to highlight * @param alternateField if no content can be found in highlightedField, use this instead * @return The server currently under test */ public SolrTestServer withHighlighting(String highlightedField, String alternateField) { return withParam("hl", "true") .withParam("hl.fl", highlightedField) .withParam("hl.alternateField", alternateField); } /** * Updates the fl parameter * * @param fields Which fields to request from Solr * @return The server currently under test */ public SolrTestServer withReturnedFields(String... fields) { return withParam("fl", StringUtils.join(fields, ",")); } // // Indexing / adding docs // /** * Adds a single document to the index * * @param doc - document to add * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void addDocument(SolrInputDocument doc) throws IOException, SolrServerException { client.add(doc); client.commit(); } /** * Gets document from a document builder * * @param docBuilder - build to get document from * @return id of the document added to the index * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocument(SolrInputDocumentBuilder docBuilder) throws IOException, SolrServerException { addDocument(docBuilder.getDoc()); return docBuilder.getDocId(); } /** * Adds a single string to the default content field * * @param content content to add * @return id of the document * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocumentWith(String content) throws IOException, SolrServerException { SolrInputDocumentBuilder docBuilder = new SolrInputDocumentBuilder(defaultContentField).with(content); return addDocument(docBuilder); } /** * Adds a single string to field specified * * @param fieldName name of the field to add content to * @param content content to add * @return id of the document * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocumentWithField(String fieldName, String content) throws IOException, SolrServerException { SolrInputDocumentBuilder docBuilder = new SolrInputDocumentBuilder(fieldName).with(content); return addDocument(docBuilder); } /** * Adds a single object value to the field specified * * @param fieldName name of the field to add content to * @param content content to add * @return id of the document * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long addDocumentWithField(String fieldName, Object content) throws IOException, SolrServerException { SolrInputDocumentBuilder docBuilder = new SolrInputDocumentBuilder(fieldName).with(content); return addDocument(docBuilder); } /** * Adds docContents to the default content field * * @param docContent content(s) to add * @return id(s) of the document(s) added * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long[] addDocumentsWith(String... docContent) throws IOException, SolrServerException { List<Long> docIds = new ArrayList<>(); for (String content : docContent) { docIds.add(addDocumentWith(content)); } return docIds.toArray(new Long[docIds.size()]); } /** * Adds docContents to the specified field name * * @param fieldName name of the field to add contents to * @param docContents content(s) to add * @return id(s) of the document(s) added * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long[] addDocumentsWithField(String fieldName, String... docContents) throws IOException, SolrServerException { List<Long> docIds = new ArrayList<>(); for (String docContent : docContents) { docIds.add(addDocumentWithField(fieldName, docContent)); } return docIds.toArray(new Long[docIds.size()]); } /** * Convenience method to add more than one document at the time from several document builders * * @param documentBuilders - builder(s) to add to the index * @return id(s) of the document(s) added * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public Long[] addDocuments(SolrInputDocumentBuilder... documentBuilders) throws IOException, SolrServerException { List<Long> docIds = new ArrayList<>(); for (SolrInputDocumentBuilder documentBuilder : documentBuilders) { docIds.add(addDocument(documentBuilder)); } return docIds.toArray(new Long[docIds.size()]); } /** * Perform an update call against the extract endpoint * * @param file file to send as an update request * @param contentType MIME content-type * @param params - further params to send * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void updateStreamRequest(File file, String contentType, Map<String, String> params) throws IOException, SolrServerException { ContentStreamUpdateRequest updateRequest = new ContentStreamUpdateRequest("/update/extract"); for (Map.Entry<String, String> e : params.entrySet()) { updateRequest.setParam(e.getKey(), e.getValue()); } updateRequest.addFile(file, contentType); client.request(updateRequest); } /** * Performs a search and asserts exactly one hit. * * @param search search to perform * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertOneHit(String search) throws IOException, SolrServerException { performSearchAndAssertNoOfHits(search, 1); } /** * Performs a search and checks that ids are present in the result. * Guarantees that only the expectedIds are present by verifying hit length equal to expectedIds * * @param search search to perform * @param expectedIds ids of the documents expected to be found by the search * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertHits(String search, Long... expectedIds) throws IOException, SolrServerException { QueryResponse response = dismaxSearch(search); verifyHits(response, expectedIds.length); assertDocumentsInResult(response, expectedIds); } /** * Performs a search and checks number of hits * * @param search search to perform * @param resultCount number of documents expected to be found by the search * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertNoOfHits(String search, long resultCount) throws IOException, SolrServerException { verifyHits(dismaxSearch(search), resultCount); } /** * Performs a search and verifies that it does not find anything in the index * * @param search search to perform * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public void performSearchAndAssertNoHits(String search) throws IOException, SolrServerException { performSearchAndAssertNoOfHits(search, 0L); } /** * Performs a search * * @param searchQuery query to perform * @return The raw QueryResponse from the solr server * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public QueryResponse search(String searchQuery) throws IOException, SolrServerException { search = searchQuery; withParam("q", StringUtils.defaultIfBlank(searchQuery, "")); return search(); } /** * Performs a query of the form [field]:[query] * * @param field name of the field to search in * @param value expected value of the field * @return The raw QueryResponse from the solr server * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server */ public QueryResponse search(String field, String value) throws IOException, SolrServerException { search = field + ":" + value; withParam("q", StringUtils.defaultIfBlank(field + ":" + value, "")); return search(); } /** * Performs a search with the parameters currently set * * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server * @return The Solr QueryResponse */ public QueryResponse search() throws IOException, SolrServerException { if (StringUtils.isEmpty(solrQuery.get("q"))) { withParam("hl.q", "*:*"); } return client.query(solrQuery); } /** * Performs a search using the dismax query handler * * @param query search to perform * @throws IOException if there is a communication error with the server * @throws SolrServerException if there is an error on the server * @return The Solr QueryResponse */ public QueryResponse dismaxSearch(String query) throws IOException, SolrServerException { withParam("qt", "dismax"); return search(query); } // // Verify/asserts // /** * Verifies that ids come in the order expected. Used to check that sorts are working as expected * @param response the result of the search * @param sequence the ids in the correct sequence */ public void verifySequenceOfHits(QueryResponse response, Long... sequence) { assertThat(response.getResults().getNumFound(), is(Long.valueOf(sequence.length))); int i = 0; for (long id : sequence) { String assertMessage = "Document " + i + " should have docId: " + id; assertThat(assertMessage, Long.parseLong((String) response.getResults().get(i).getFirstValue(uniqueKeyField)), CoreMatchers.is(id)); i++; } } /** * Verifiies that we've got exactly one hit * @param response the result of the search */ public void verifyOneHit(QueryResponse response) { verifyHits(response, 1L); } /** * Verifies `hits` number of hits * @param response the result of the search * @param hits amount of expected hits */ public void verifyHits(QueryResponse response, long hits) { long matches = isGrouped() ? response.getGroupResponse().getValues().get(0).getMatches() : response.getResults().getNumFound(); assertThat("Search for \"" + search + "\" should get " + hits + " results, but got: " + matches, matches, is(hits)); } /** * Verifies that ngroups response is of expected value * @param response the result of the search * @param groups amount of groups expected */ public void verifyNoOfGroups(QueryResponse response, long groups) { if (isGrouped()) { int matchGroups = response.getGroupResponse().getValues().get(0).getNGroups(); assertThat("Search for \"" + search + "\" should get " + groups + " groups, but got: " + matchGroups, (long) matchGroups, is(groups)); } } /** * JUnit assert that the document ids can be found in the result * @param response QueryResponse to check * @param docIds ids expected */ public void assertDocumentsInResult(QueryResponse response, Long... docIds) { for (Long docId : docIds) { assertTrue("DocId: [" + docId + "] should be in the result set", isGrouped() ? docIdIsInGroupedResponse(response, docId) : docIdIsInList(docId, response.getResults())); } } /** * One of the groups returned from the search contains the id * @param response Query response to check * @param docId id expected * @return whether or not the docid was contained in any of groups */ private boolean docIdIsInGroupedResponse(QueryResponse response, Long docId) { List<SolrDocument> docs = new ArrayList<>(); for (Group group : response.getGroupResponse().getValues().get(0).getValues()) { SolrDocumentList list = group.getResult(); for (SolrDocument doc : list) { docs.add(doc); } } return docIdIsInList(docId, docs); } private boolean docIdIsInList(Long docId, List<SolrDocument> docs) { for (SolrDocument doc : docs) { Object id = doc.getFirstValue(uniqueKeyField); if (id == null) { throw new NullPointerException(uniqueKeyField + " not found in doc. you should probably call solr.withReturnedFields" + "(\"" + uniqueKeyField + "\")" + " before calling the tests, " + "" + "or add \"+"+uniqueKeyField+ "\" to the fl-parameter in solrconfig.xml"); } if (id.equals(String.valueOf(docId))) { return true; } } return false; } // Highlighting/snippets /** * Checks that highlighting works as expected * * @param search query * @param startHighlightingElement the starting element to look for * @param endHighlightingElement the closing element to look for * @param snippets the snippets returned from solr as highlights */ public void assertHighlight(String search, String startHighlightingElement, String endHighlightingElement, List<String> snippets) { String pattern = String.format("%s%s%s", startHighlightingElement, search, endHighlightingElement); for (String snippet : snippets) { if (snippet.contains(search)) { assertTrue(snippet.contains(pattern)); } } } private List<String> getSnippets(Map<String, Map<String, List<String>>> highlighting) { List<String> snippets = new ArrayList<>(); for (Map<String, List<String>> doc : highlighting.values()) { for (List<String> highlightedSnippets : doc.values()) { snippets.addAll(highlightedSnippets); } } return snippets; } /** * @param response QueryResponse to fetch highlight snippets from * @return Highlight snippets */ public List<String> getSnippets(QueryResponse response) { return getSnippets(response.getHighlighting()); } public void assertTeaser(String query, String teaser, List<String> snippets) { for (String snippet : snippets) { if (query == null || !snippet.contains(query)) { assertThat(snippet, is(teaser)); } } } // // Faceting // /** * JUnit assert that a facet query has the expected hit count * @param response where to locate the facet * @param facetName name of the facet * @param hitCount expected hit count */ public void assertFacetQueryHasHitCount(QueryResponse response, String facetName, int hitCount) { assertThat(response.getFacetQuery().get(facetName), is(hitCount)); } /** * Convenience method to run raw Solr commands rather than using the helper methods * * @return The raw SolrClient */ public SolrClient getClient() { return this.client; } }
#8 #9 Adding reasons to assert-statements and fix assert comparing int to long. Also replaced som lambdas with mthod references.
src/main/java/no/finn/solr/integration/SolrTestServer.java
#8 #9 Adding reasons to assert-statements and fix assert comparing int to long. Also replaced som lambdas with mthod references.
<ide><path>rc/main/java/no/finn/solr/integration/SolrTestServer.java <ide> this.coreContainer = CoreContainer.createAndLoad(solrPath); <ide> assertNoLoadErrors(coreContainer); <ide> core = getCore(coreContainer); <del> client = core.map(c -> new EmbeddedSolrServer(c)).orElse(null); <add> client = core.map(EmbeddedSolrServer::new).orElse(null); <ide> } <ide> <ide> private void assertNoLoadErrors(CoreContainer coreContainer) { <ide> Map<String, CoreContainer.CoreLoadFailure> coreInitFailures = coreContainer.getCoreInitFailures(); <ide> for (CoreContainer.CoreLoadFailure coreLoadFailure : coreInitFailures.values()) { <ide> System.out.println("Error in loading core: " + coreLoadFailure.cd.getCollectionName()); <del> System.out.println("Instancedir set to: " +coreLoadFailure.cd.getInstanceDir()); <del> System.out.println("Error message: " +coreLoadFailure.exception.getMessage()); <del> System.out.println("Cause: " +coreLoadFailure.exception.getCause()); <add> System.out.println("Instancedir set to: " + coreLoadFailure.cd.getInstanceDir()); <add> System.out.println("Error message: " + coreLoadFailure.exception.getMessage()); <add> System.out.println("Cause: " + coreLoadFailure.exception.getCause()); <ide> if (coreLoadFailure.exception.getCause().getCause() != null) { <del> System.out.println("Cause of Cause: " +coreLoadFailure.exception.getCause().getCause()); <add> System.out.println("Cause of Cause: " + coreLoadFailure.exception.getCause().getCause()); <ide> } <ide> } <ide> assert coreInitFailures.size() == 0; <ide> <ide> private Optional<SolrCore> getCore(CoreContainer coreContainer) { <ide> return coreContainer.getAllCoreNames() <del> .stream() <del> .findFirst() <del> .map(name -> coreContainer.getCore(name)); <add> .stream() <add> .findFirst() <add> .map(coreContainer::getCore); <ide> } <ide> <ide> private boolean isGrouped() { <ide> public Optional<SearchComponent> getSearchComponent(String componentName) { <ide> return core.map(c -> c.getSearchComponent(componentName)); <ide> } <add> <ide> /** <ide> * Sets a parameter <ide> * <ide> /** <ide> * Performs a search with the parameters currently set <ide> * <del> * @throws IOException if there is a communication error with the server <del> * @throws SolrServerException if there is an error on the server <ide> * @return The Solr QueryResponse <add> * @throws IOException if there is a communication error with the server <add> * @throws SolrServerException if there is an error on the server <ide> */ <ide> public QueryResponse search() throws IOException, SolrServerException { <ide> if (StringUtils.isEmpty(solrQuery.get("q"))) { <ide> * Performs a search using the dismax query handler <ide> * <ide> * @param query search to perform <del> * @throws IOException if there is a communication error with the server <del> * @throws SolrServerException if there is an error on the server <ide> * @return The Solr QueryResponse <add> * @throws IOException if there is a communication error with the server <add> * @throws SolrServerException if there is an error on the server <ide> */ <ide> public QueryResponse dismaxSearch(String query) throws IOException, SolrServerException { <ide> withParam("qt", "dismax"); <ide> * @param sequence the ids in the correct sequence <ide> */ <ide> public void verifySequenceOfHits(QueryResponse response, Long... sequence) { <del> assertThat(response.getResults().getNumFound(), is(Long.valueOf(sequence.length))); <add> assertThat("getNumFound: " + response.getResults().getNumFound() + " not same length as expexted: " + sequence.length, <add> response.getResults().getNumFound(), is(Long.valueOf(sequence.length))); <ide> int i = 0; <ide> for (long id : sequence) { <ide> String assertMessage = "Document " + i + " should have docId: " + id; <ide> /** <ide> * Verifies `hits` number of hits <ide> * @param response the result of the search <del> * @param hits amount of expected hits <add> * @param hits amount of expected hits <ide> */ <ide> public void verifyHits(QueryResponse response, long hits) { <ide> long matches = isGrouped() ? response.getGroupResponse().getValues().get(0).getMatches() : response.getResults().getNumFound(); <ide> /** <ide> * Verifies that ngroups response is of expected value <ide> * @param response the result of the search <del> * @param groups amount of groups expected <add> * @param groups amount of groups expected <ide> */ <ide> public void verifyNoOfGroups(QueryResponse response, long groups) { <ide> if (isGrouped()) { <ide> /** <ide> * JUnit assert that the document ids can be found in the result <ide> * @param response QueryResponse to check <del> * @param docIds ids expected <add> * @param docIds ids expected <ide> */ <ide> public void assertDocumentsInResult(QueryResponse response, Long... docIds) { <ide> for (Long docId : docIds) { <ide> /** <ide> * One of the groups returned from the search contains the id <ide> * @param response Query response to check <del> * @param docId id expected <add> * @param docId id expected <ide> * @return whether or not the docid was contained in any of groups <ide> */ <ide> private boolean docIdIsInGroupedResponse(QueryResponse response, Long docId) { <ide> * @param endHighlightingElement the closing element to look for <ide> * @param snippets the snippets returned from solr as highlights <ide> */ <del> public void assertHighlight(String search, String startHighlightingElement, String endHighlightingElement, List<String> snippets) { <add> public void assertHighlight(String search, <add> String startHighlightingElement, <add> String endHighlightingElement, <add> List<String> snippets) { <ide> String pattern = String.format("%s%s%s", startHighlightingElement, search, endHighlightingElement); <ide> for (String snippet : snippets) { <ide> if (snippet.contains(search)) { <del> assertTrue(snippet.contains(pattern)); <add> assertTrue("missing " + pattern + " in: '" + snippet + "'", snippet.contains(pattern)); <ide> } <ide> } <ide> } <ide> public void assertTeaser(String query, String teaser, List<String> snippets) { <ide> for (String snippet : snippets) { <ide> if (query == null || !snippet.contains(query)) { <del> assertThat(snippet, is(teaser)); <add> assertThat("teaser: " + teaser + " != snippet: " + snippet, snippet, is(teaser)); <ide> } <ide> } <ide> } <ide> <ide> /** <ide> * JUnit assert that a facet query has the expected hit count <del> * @param response where to locate the facet <add> * <add> * @param response where to locate the facet <ide> * @param facetName name of the facet <ide> * @param hitCount expected hit count <ide> */ <ide> public void assertFacetQueryHasHitCount(QueryResponse response, String facetName, int hitCount) { <del> assertThat(response.getFacetQuery().get(facetName), is(hitCount)); <add> final int facetCount = response.getFacetQuery().get(facetName); <add> assertThat("facetCount: " + facetCount + " != expected hitcount: " + hitCount, facetCount, is(hitCount)); <ide> } <ide> <ide> /**
JavaScript
mit
e413ef5672b7f23a095fa849c8fa6a7e7a1c4a36
0
peterramsing/lost,corysimmons/lost,peterramsing/lost
'use strict'; var check = require('./check'); describe('lost-utility', function() { it('Doesn\'t remove the parent node if there are other rules in declaration', function () { check( 'a { lost-utility: edit; color: blue; }', 'a { color:blue; } a:not(input):not(textarea):not(select) ' + '{ background-color:rgba(0,0,255,.1); }' ); }); it('applies edit indicator', function() { check( 'a { lost-utility: edit }', 'a *:not(input):not(textarea):not(select) {\n' + ' background-color: rgba(0, 0, 255, 0.1)\n' + '}' ); }); it('applies edit indicator with color', function() { check( 'a { lost-utility: edit rgb(44, 55, 33) }', 'a *:not(input):not(textarea):not(select) {\n' + ' background-color: rgba(44, 55, 33, 0.1)\n' + '}' ), check( 'a { lost-utility: edit rgb(44,55,111) }', 'a *:not(input):not(textarea):not(select) {\n' + ' background-color: rgba(44,55,111, 0.1)\n' + '}' ); }); it('applies clearfix', function() { check( 'a { lost-utility: clearfix }', 'a:before {\n' + ' content: \'\';\n' + ' display: table\n' + '}\n' + 'a:after {\n' + ' content: \'\';\n' + ' display: table;\n' + ' clear: both\n' + '}' ); }); });
test/lost-utility.js
'use strict'; var check = require('./check'); describe('lost-utility', function() { it('applies edit indicator', function() { check( 'a { lost-utility: edit }', 'a *:not(input):not(textarea):not(select) {\n' + ' background-color: rgba(0, 0, 255, 0.1)\n' + '}' ); }); it('applies edit indicator with color', function() { check( 'a { lost-utility: edit rgb(44, 55, 33) }', 'a *:not(input):not(textarea):not(select) {\n' + ' background-color: rgba(44, 55, 33, 0.1)\n' + '}' ), check( 'a { lost-utility: edit rgb(44,55,111) }', 'a *:not(input):not(textarea):not(select) {\n' + ' background-color: rgba(44,55,111, 0.1)\n' + '}' ); }); it('applies clearfix', function() { check( 'a { lost-utility: clearfix }', 'a:before {\n' + ' content: \'\';\n' + ' display: table\n' + '}\n' + 'a:after {\n' + ' content: \'\';\n' + ' display: table;\n' + ' clear: both\n' + '}' ); }); });
Adds test for the utility if there are other rules in the declaration
test/lost-utility.js
Adds test for the utility if there are other rules in the declaration
<ide><path>est/lost-utility.js <ide> var check = require('./check'); <ide> <ide> describe('lost-utility', function() { <add> it('Doesn\'t remove the parent node if there are other rules in declaration', function () { <add> check( <add> 'a { lost-utility: edit; color: blue; }', <add> 'a { color:blue; } a:not(input):not(textarea):not(select) ' + <add> '{ background-color:rgba(0,0,255,.1); }' <add> ); <add> }); <add> <ide> it('applies edit indicator', function() { <ide> check( <ide> 'a { lost-utility: edit }',
Java
apache-2.0
9293c11e9aa65ab184cd8062c46c610dbf8a3578
0
peter-tackage/open-secret-santa,peter-tackage/open-secret-santa
package com.moac.android.opensecretsanta.adapter; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.ContactsContract; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.moac.android.opensecretsanta.R; import com.moac.android.opensecretsanta.model.Member; import com.moac.android.opensecretsanta.model.PersistableObject; import com.moac.android.opensecretsanta.util.ContactUtils; import com.squareup.picasso.Picasso; import java.util.List; public class MemberListAdapter extends ArrayAdapter<Member> { private final String TAG = MemberListAdapter.class.getSimpleName(); private int mResource; public MemberListAdapter(Context _context, int _resource, List<Member> _members) { super(_context, _resource, _members); mResource = _resource; } @Override public View getView(int _position, View _convertView, ViewGroup _parent) { Log.v(TAG, "getView() - creating for position: " + _position); View v = _convertView; ImageView avatarView; TextView memberNameView; TextView contactAddressView; TextView restrictionsView; // Attempt to reuse recycled view if possible // Refer - http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/ // More up-to-date info here - http://www.piwai.info/android-adapter-good-practices/ (specifically using Tag) // Good info on LayoutInflater here - http://stackoverflow.com/questions/5026926/making-sense-of-layoutinflater if(v == null) { v = LayoutInflater.from(getContext()).inflate(mResource, _parent, false); avatarView = (ImageView) v.findViewById(R.id.member_imageview); memberNameView = (TextView) v.findViewById(R.id.member_name_textview); contactAddressView = (TextView) v.findViewById(R.id.contact_address_textview); restrictionsView = (TextView) v.findViewById(R.id.restriction_count_textview); v.setTag(R.id.member_imageview, avatarView); v.setTag(R.id.member_name_textview, memberNameView); v.setTag(R.id.contact_address_textview, contactAddressView); v.setTag(R.id.restriction_count_textview, restrictionsView); } else { // Recycled View is available, retrieve the holder instance from the View avatarView = (ImageView) v.getTag(R.id.member_imageview); memberNameView = (TextView) v.getTag(R.id.member_name_textview); contactAddressView = (TextView) v.getTag(R.id.contact_address_textview); restrictionsView = (TextView) v.getTag(R.id.restriction_count_textview); } Member item = getItem(_position); // Assign the view with its content. if(item.getContactId() == PersistableObject.UNSET_ID || item.getLookupKey() == null) { Picasso.with(getContext()).load(R.drawable.ic_contact_picture).into(avatarView); } else { Uri lookupUri = ContactsContract.Contacts.getLookupUri(item.getContactId(), item.getLookupKey()); Uri contactUri = ContactsContract.Contacts.lookupContact(getContext().getContentResolver(), lookupUri); Picasso.with(getContext()).load(contactUri) .placeholder(R.drawable.ic_contact_picture).error(R.drawable.ic_contact_picture) .into(avatarView); } memberNameView.setText(item.getName()); contactAddressView.setText(item.getContactAddress()); final long restrictionCount = item.getRestrictionCount(); if(restrictionCount > 0) { restrictionsView.setText(String.valueOf(restrictionCount)); restrictionsView.setVisibility(View.VISIBLE); } else { restrictionsView.setVisibility(View.GONE); } return v; } }
open-secret-santa-app/src/main/java/com/moac/android/opensecretsanta/adapter/MemberListAdapter.java
package com.moac.android.opensecretsanta.adapter; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.moac.android.opensecretsanta.R; import com.moac.android.opensecretsanta.model.Member; import com.moac.android.opensecretsanta.util.ContactUtils; import java.util.List; public class MemberListAdapter extends ArrayAdapter<Member> { private final String TAG = MemberListAdapter.class.getSimpleName(); private int mResource; public MemberListAdapter(Context _context, int _resource, List<Member> _members) { super(_context, _resource, _members); mResource = _resource; } @Override public View getView(int _position, View _convertView, ViewGroup _parent) { Log.v(TAG, "getView() - creating for position: " + _position); View v = _convertView; ImageView avatarView; TextView memberNameView; TextView contactAddressView; TextView restrictionsView; // Attempt to reuse recycled view if possible // Refer - http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/ // More up-to-date info here - http://www.piwai.info/android-adapter-good-practices/ (specifically using Tag) // Good info on LayoutInflater here - http://stackoverflow.com/questions/5026926/making-sense-of-layoutinflater if(v == null) { v = LayoutInflater.from(getContext()).inflate(mResource, _parent, false); avatarView = (ImageView) v.findViewById(R.id.member_imageview); memberNameView = (TextView) v.findViewById(R.id.member_name_textview); contactAddressView = (TextView) v.findViewById(R.id.contact_address_textview); restrictionsView = (TextView) v.findViewById(R.id.restriction_count_textview); v.setTag(R.id.member_imageview, avatarView); v.setTag(R.id.member_name_textview, memberNameView); v.setTag(R.id.contact_address_textview, contactAddressView); v.setTag(R.id.restriction_count_textview, restrictionsView); } else { // Recycled View is available, retrieve the holder instance from the View avatarView = (ImageView) v.getTag(R.id.member_imageview); memberNameView = (TextView)v.getTag(R.id.member_name_textview); contactAddressView = (TextView)v.getTag(R.id.contact_address_textview); restrictionsView = (TextView)v.getTag(R.id.restriction_count_textview); } Member item = getItem(_position); // Assign the view with its content. Drawable avatar = ContactUtils.getContactPhoto(getContext(), item.getContactId(), item.getLookupKey()); if (avatar != null) { avatarView.setImageDrawable(avatar); } else{ avatarView.setImageResource(R.drawable.ic_contact_picture); } memberNameView.setText(item.getName()); contactAddressView.setText(item.getContactAddress()); final long restrictionCount = item.getRestrictionCount(); if(restrictionCount > 0) { restrictionsView.setText(String.valueOf(restrictionCount)); restrictionsView.setVisibility(View.VISIBLE); } else { restrictionsView.setVisibility(View.GONE); } return v; } }
Use Picasso to load contact avatars in MemberList
open-secret-santa-app/src/main/java/com/moac/android/opensecretsanta/adapter/MemberListAdapter.java
Use Picasso to load contact avatars in MemberList
<ide><path>pen-secret-santa-app/src/main/java/com/moac/android/opensecretsanta/adapter/MemberListAdapter.java <ide> <ide> import android.content.Context; <ide> import android.graphics.drawable.Drawable; <add>import android.net.Uri; <add>import android.provider.ContactsContract; <ide> import android.util.Log; <ide> import android.view.LayoutInflater; <ide> import android.view.View; <ide> import android.widget.TextView; <ide> import com.moac.android.opensecretsanta.R; <ide> import com.moac.android.opensecretsanta.model.Member; <add>import com.moac.android.opensecretsanta.model.PersistableObject; <ide> import com.moac.android.opensecretsanta.util.ContactUtils; <add>import com.squareup.picasso.Picasso; <ide> <ide> import java.util.List; <ide> <ide> } else { <ide> // Recycled View is available, retrieve the holder instance from the View <ide> avatarView = (ImageView) v.getTag(R.id.member_imageview); <del> memberNameView = (TextView)v.getTag(R.id.member_name_textview); <del> contactAddressView = (TextView)v.getTag(R.id.contact_address_textview); <del> restrictionsView = (TextView)v.getTag(R.id.restriction_count_textview); <add> memberNameView = (TextView) v.getTag(R.id.member_name_textview); <add> contactAddressView = (TextView) v.getTag(R.id.contact_address_textview); <add> restrictionsView = (TextView) v.getTag(R.id.restriction_count_textview); <ide> } <ide> <ide> Member item = getItem(_position); <ide> <ide> // Assign the view with its content. <del> Drawable avatar = ContactUtils.getContactPhoto(getContext(), item.getContactId(), item.getLookupKey()); <del> if (avatar != null) { <del> avatarView.setImageDrawable(avatar); <del> } else{ <del> avatarView.setImageResource(R.drawable.ic_contact_picture); <add> if(item.getContactId() == PersistableObject.UNSET_ID || item.getLookupKey() == null) { <add> Picasso.with(getContext()).load(R.drawable.ic_contact_picture).into(avatarView); <add> } else { <add> Uri lookupUri = ContactsContract.Contacts.getLookupUri(item.getContactId(), item.getLookupKey()); <add> Uri contactUri = ContactsContract.Contacts.lookupContact(getContext().getContentResolver(), lookupUri); <add> Picasso.with(getContext()).load(contactUri) <add> .placeholder(R.drawable.ic_contact_picture).error(R.drawable.ic_contact_picture) <add> .into(avatarView); <ide> } <add> <ide> memberNameView.setText(item.getName()); <ide> contactAddressView.setText(item.getContactAddress()); <ide>
Java
apache-2.0
146cbe74e5950413ff8d5cab51ae4f60f08efee3
0
b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.datastore.index.entry; import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.CONCEPT_NUMBER; import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER; import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.RELATIONSHIP_NUMBER; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.newHashMap; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.Set; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexableField; import com.b2international.commons.BooleanUtils; import com.b2international.commons.StringUtils; import com.b2international.commons.functions.UncheckedCastFunction; import com.b2international.snowowl.core.CoreTerminologyBroker; import com.b2international.snowowl.core.api.IComponent; import com.b2international.snowowl.core.date.EffectiveTimes; import com.b2international.snowowl.datastore.index.mapping.Mappings; import com.b2international.snowowl.snomed.core.domain.Acceptability; import com.b2international.snowowl.snomed.core.domain.InactivationIndicator; import com.b2international.snowowl.snomed.core.domain.RelationshipRefinability; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.core.domain.SnomedCoreComponent; import com.b2international.snowowl.snomed.core.domain.SnomedDescription; import com.b2international.snowowl.snomed.core.domain.SnomedRelationship; import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember; import com.b2international.snowowl.snomed.datastore.SnomedRefSetUtil; import com.b2international.snowowl.snomed.datastore.index.mapping.SnomedMappings; import com.b2international.snowowl.snomed.snomedrefset.DataType; import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; /** * Lightweight representation of a SNOMED CT reference set member. */ public class SnomedRefSetMemberIndexEntry extends SnomedIndexEntry implements IComponent<String>, Serializable { private static final Set<String> ADDITIONAL_FIELDS = SnomedMappings.fieldsToLoad() .memberAcceptabilityId() .memberValueId() .memberTargetComponentId() .memberMapTargetComponentId() .memberMapTargetComponentDescription() .memberMapGroup() .memberMapPriority() .memberMapRule() .memberMapAdvice() .memberMapCategoryId() .memberCorrelationId() .memberDescriptionFormatId() .memberDescriptionLength() .memberOperatorId() .memberContainerModuleId() .memberUomId() .memberDataTypeLabel() .memberDataTypeOrdinal() .memberSerializedValue() .memberCharacteristicTypeId() .memberQuery() .memberSourceEffectiveTime() .memberTargetEffectiveTime() .build(); /** * @param name the field name to check * @return {@code true} if the specified field name is valid as an additional {@code String} or {@link Number} value, {@code false} otherwise */ public static boolean isAdditionalField(final String name) { return ADDITIONAL_FIELDS.contains(name); } private static final long serialVersionUID = 3504576207161692354L; public static Builder builder() { return new Builder(); } public static Builder builder(final Document doc) { final SnomedRefSetType refSetType = SnomedRefSetType.get(SnomedMappings.memberRefSetType().getValue(doc)); final Builder builder = builder() .active(BooleanUtils.valueOf(SnomedMappings.active().getValue(doc))) .effectiveTimeLong(SnomedMappings.effectiveTime().getValue(doc)) .id(SnomedMappings.memberUuid().getValue(doc)) .moduleId(SnomedMappings.module().getValueAsString(doc)) .referencedComponentId(SnomedMappings.memberReferencedComponentId().getValueAsString(doc)) .referencedComponentType(SnomedMappings.memberReferencedComponentType().getShortValue(doc)) .referenceSetId(SnomedMappings.memberRefSetId().getValueAsString(doc)) .referenceSetType(refSetType) .released(BooleanUtils.valueOf(SnomedMappings.released().getValue(doc))) .storageKey(Mappings.storageKey().getValue(doc)); if (SnomedRefSetUtil.isMapping(refSetType)) { builder.mapTargetComponentType(SnomedMappings.memberMapTargetComponentType().getShortValue(doc)); } for (IndexableField storedField : doc) { if (SnomedRefSetMemberIndexEntry.isAdditionalField(storedField.name())) { if (storedField.numericValue() != null) { builder.additionalField(storedField.name(), storedField.numericValue()); } else { builder.additionalField(storedField.name(), storedField.stringValue()); } } } return builder; } public static Builder builder(final SnomedRefSetMemberIndexEntry source) { return builder() .active(source.active) .effectiveTimeLong(source.effectiveTimeLong) .id(source.id) .moduleId(source.moduleId) .referencedComponentId(source.referencedComponentId) .referencedComponentType(source.referencedComponentType) .referenceSetId(source.getRefSetIdentifierId()) .referenceSetType(source.referenceSetType) .released(source.released) .storageKey(source.storageKey) .score(source.score) .mapTargetComponentType(source.mapTargetComponentType) .additionalFields(source.additionalFields); } public static final Builder builder(final SnomedReferenceSetMember input) { final Object mapTargetComponentType = input.getProperties().get(SnomedMappings.memberMapTargetComponentType().fieldName()); return builder() .active(input.isActive()) .effectiveTimeLong(EffectiveTimes.getEffectiveTime(input.getEffectiveTime())) .id(input.getId()) .moduleId(input.getModuleId()) .referencedComponentId(input.getReferencedComponent().getId()) .referencedComponentType(input.getReferencedComponent()) .referenceSetId(input.getReferenceSetId()) .referenceSetType(input.type()) .released(input.isReleased()) .mapTargetComponentType(mapTargetComponentType == null ? -1 : (short) mapTargetComponentType) .additionalFields(input.getProperties()); } public static Collection<SnomedRefSetMemberIndexEntry> from(final Collection<SnomedReferenceSetMember> refSetMembers) { return FluentIterable.from(refSetMembers).transform(new Function<SnomedReferenceSetMember, SnomedRefSetMemberIndexEntry>() { @Override public SnomedRefSetMemberIndexEntry apply(final SnomedReferenceSetMember refSetMember) { return builder(refSetMember).build(); } }).toList(); } public static class Builder extends AbstractBuilder<Builder> { private String referencedComponentId; private final Map<String, Object> additionalFields = newHashMap(); private String referenceSetId; private SnomedRefSetType referenceSetType; private short referencedComponentType; private short mapTargetComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT; private Builder() { // Disallow instantiation outside static method } @Override protected Builder getSelf() { return this; } public Builder referencedComponentId(final String referencedComponentId) { this.referencedComponentId = referencedComponentId; return this; } public Builder additionalField(final String fieldName, final Object fieldValue) { this.additionalFields.put(fieldName, fieldValue); return this; } public Builder additionalFields(final Map<String, Object> additionalFields) { this.additionalFields.putAll(additionalFields); return this; } public Builder referenceSetId(final String referenceSetId) { this.referenceSetId = referenceSetId; return this; } public Builder referenceSetType(final SnomedRefSetType referenceSetType) { this.referenceSetType = referenceSetType; return this; } public Builder referencedComponentType(final short referencedComponentType) { this.referencedComponentType = referencedComponentType; return this; } public Builder referencedComponentType(final SnomedCoreComponent component) { if (component instanceof SnomedConcept) { this.referencedComponentType = CONCEPT_NUMBER; } else if (component instanceof SnomedDescription) { this.referencedComponentType = DESCRIPTION_NUMBER; } else if (component instanceof SnomedRelationship) { this.referencedComponentType = RELATIONSHIP_NUMBER; } else { this.referencedComponentType = -1; } return this; } public Builder mapTargetComponentType(final short mapTargetComponentType) { this.mapTargetComponentType = mapTargetComponentType; return this; } public SnomedRefSetMemberIndexEntry build() { return new SnomedRefSetMemberIndexEntry(id, label, score, storageKey, moduleId, released, active, effectiveTimeLong, referencedComponentId, ImmutableMap.copyOf(additionalFields), referenceSetId, referenceSetType, referencedComponentType, mapTargetComponentType); } } private final String referencedComponentId; private final ImmutableMap<String, Object> additionalFields; private final String referenceSetId; private final SnomedRefSetType referenceSetType; private final short referencedComponentType; private final short mapTargetComponentType; private SnomedRefSetMemberIndexEntry(final String id, final String label, final float score, final long storageKey, final String moduleId, final boolean released, final boolean active, final long effectiveTimeLong, final String referencedComponentId, final ImmutableMap<String, Object> additionalFields, final String referenceSetId, final SnomedRefSetType referenceSetType, final short referencedComponentType, final short mapTargetComponentType) { super(id, label, referenceSetId, // XXX: iconId is the reference set identifier score, storageKey, moduleId, released, active, effectiveTimeLong); checkArgument(referencedComponentType >= CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT, "Referenced component type '%s' is invalid.", referencedComponentType); checkArgument(mapTargetComponentType >= CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT, "Map target component type '%s' is invalid.", referencedComponentType); this.referencedComponentId = checkNotNull(referencedComponentId, "Reference component identifier may not be null."); this.additionalFields = checkNotNull(additionalFields, "Additional field map may not be null."); this.referenceSetId = checkNotNull(referenceSetId, "Reference set identifier may not be null."); this.referenceSetType = checkNotNull(referenceSetType, "Reference set type may not be null."); this.referencedComponentType = referencedComponentType; this.mapTargetComponentType = mapTargetComponentType; } // /** // * (non-API) // * Creates a reference set member from a CDOish object. // */ // public static SnomedRefSetMemberIndexEntry create(final SnomedRefSetMember member) { // return create(member, null); // } // // /** // * (non-API) // * Creates a reference set member from a CDOish object with the given label of the referenced component. // */ // public static SnomedRefSetMemberIndexEntry create(final SnomedRefSetMember member, @Nullable final String label) { // Preconditions.checkNotNull(member, "Reference set member argument cannot be null."); // Preconditions.checkArgument(!CDOState.NEW.equals(member.cdoState()), "Reference set member CDO state should not be NEW. " + // "Use com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetLuceneIndexDTO.createForNewMember(SnomedRefSetMember<?>) instead."); // Preconditions.checkArgument(!CDOState.TRANSIENT.equals(member.cdoState()), "Reference set member CDO state should not be TRANSIENT. " + // "Use com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetLuceneIndexDTO.createForDetachedMember(SnomedRefSetMember<?>, SnomedRefSet<?>) instead"); // return new SnomedRefSetMemberIndexEntry(member, label, tryGetIconId(member), CDOIDUtil.getLong(member.cdoID()), member.getRefSet()); // } // // /** // * (non-API) // * Creates a reference set member from a new CDOish reference set member. // */ // public static SnomedRefSetMemberIndexEntry createForNewMember(final SnomedRefSetMember member) { // return createForNewMember(member, null); // } // // /** // * (non-API) // * Creates a reference set member from a new CDOish reference set member with the given label of the referenced component. // */ // public static SnomedRefSetMemberIndexEntry createForNewMember(final SnomedRefSetMember member, @Nullable final String label) { // Preconditions.checkNotNull(member, "Reference set member argument cannot be null."); // Preconditions.checkArgument(CDOState.NEW.equals(member.cdoState()), "Reference set member CDO state must be NEW."); // return new SnomedRefSetMemberIndexEntry(member, label, tryGetIconId(member), 0L, member.getRefSet()); // } // // /** // * (non-API) // * Creates a reference set member representing a detached member. // */ // public static SnomedRefSetMemberIndexEntry createForDetachedMember(final SnomedRefSetMember member, final SnomedRefSet refSet) { // return createForDetachedMember(member, refSet, null); // } // // /** // * (non-API) // * Creates a reference set member representing a detached member. // */ // public static SnomedRefSetMemberIndexEntry createForDetachedMember(final SnomedRefSetMember member, final SnomedRefSet refSet, @Nullable final String label) { // Preconditions.checkNotNull(member, "Reference set member argument cannot be null."); // Preconditions.checkNotNull(refSet, "Container reference set argument cannot be null."); // Preconditions.checkArgument(CDOState.TRANSIENT.equals(member.cdoState()), "Reference set member CDO state must be TRANSIENT."); // return new SnomedRefSetMemberIndexEntry(member, label, SnomedConstants.Concepts.ROOT_CONCEPT, 0L, refSet); // } // // /** // * (non-API) // * Creates a mock reference set member. // */ // public static SnomedRefSetMemberIndexEntry createMockMember(final IComponent<String> component) { // return new SnomedRefSetMemberIndexEntry(component, SnomedIconProvider.getInstance().getIconComponentId(component.getId())); // } // // protected static String tryGetIconId(final SnomedRefSetMember member) { // // if (CDOUtils.checkObject(member)) { // // if (member instanceof SnomedQueryRefSetMember) { // return Concepts.REFSET_ROOT_CONCEPT; // } // // final short referencedComponentType = member.getReferencedComponentType(); // final String referencedComponentId = member.getReferencedComponentId(); // Object iconIdAsobject = CoreTerminologyBroker.getInstance().getComponentIconIdProvider(referencedComponentType).getIconId(BranchPathUtils.createPath(member.cdoView()), referencedComponentId); // if (null != iconIdAsobject) { // return String.valueOf(iconIdAsobject); // } // // } // // return Concepts.ROOT_CONCEPT; // } // // /** // * (non-API) // * Creates a new reference set member based on the given index document. // */ // public static SnomedRefSetMemberIndexEntry create(final Document doc, @Nullable final IBranchPath branchPath) { // Preconditions.checkNotNull(doc, "Document argument cannot be null."); // // final SnomedRefSetType type = SnomedRefSetType.get(SnomedMappings.memberRefSetType().getValue(doc)); // final String uuid = doc.get(SnomedIndexBrowserConstants.REFERENCE_SET_MEMBER_UUID); // final String moduleId = SnomedMappings.module().getValueAsString(doc); // final long storageKey = Mappings.storageKey().getValue(doc); // final boolean active = SnomedMappings.active().getValue(doc) == 1; // final boolean released = IndexUtils.getBooleanValue(doc.getField(SnomedIndexBrowserConstants.COMPONENT_RELEASED)); // final long refSetId = SnomedMappings.memberRefSetId().getValue(doc); // final short referencedComponentType = SnomedMappings.memberReferencedComponentType().getShortValue(doc); // final String referencedComponentId = SnomedMappings.memberReferencedComponentId().getValueAsString(doc); // final long effectiveTimeLong = SnomedMappings.effectiveTime().getValue(doc); // final short specialFieldComponentType = isMapping(type) ? getSpecialFieldComponentTypeId(doc) : getSpecialFieldComponentTypeId(type); // final String specialFieldId = doc.get(SnomedRefSetUtil.getSpecialComponentIdIndexField(type)); // final String mapTargetDescription = doc.get(SnomedIndexBrowserConstants.REFERENCE_SET_MEMBER_MAP_TARGET_COMPONENT_DESCRIPTION); // // String iconId = null; // if (null != branchPath) { // Object iconIdAsObjact = CoreTerminologyBroker.getInstance().getComponentIconIdProvider(referencedComponentType).getIconId(branchPath, referencedComponentId); // if (null != iconIdAsObjact) { // iconId = String.valueOf(iconIdAsObjact); // } // } // // return new SnomedRefSetMemberIndexEntry( // uuid, // uuid, // iconId, // moduleId, // 0.0F, // storageKey, // released, // active, // refSetId, // referencedComponentType, // referencedComponentId, // type, // effectiveTimeLong, // specialFieldComponentType, // specialFieldId, // mapTargetDescription); // // } // // // /** // * @param id // * @param label // * @param iconId TODO // * @param moduleId // * @param score // * @param storageKey // * @param storageKey // * @param released // * @param active // * @param refSetIdentifierId // * @param refComponentType // * @param referencedComponentId // * @param refSetType // * @param effectiveTime // * @param specialFieldComponentType // * @param specialFieldLabel // * @param specialFieldId // * @param mapTargetDescription2 // */ // private SnomedRefSetMemberIndexEntry(final String id, final String label, String iconId, final String moduleId, // final float score, final long storageKey, final boolean released, final boolean active, // final long refSetIdentifierId, final short refComponentType, final String referencedComponentId, // final SnomedRefSetType refSetType, final long effectiveTime, final short specialFieldComponentType, final String specialFieldLabel, final String specialFieldId, final String mapTargetDescription) { // // super(id, iconId, score, storageKey, moduleId, released, active, effectiveTime); // this.refSetIdentifierId = refSetIdentifierId; // this.refComponentType = refComponentType; // this.referencedComponentId = referencedComponentId; // this.refSetType = refSetType; // this.storageKey = storageKey; // this.specialFieldComponentType = specialFieldComponentType; // this.specialFieldLabel = specialFieldLabel; // this.specialFieldId = specialFieldId; // this.label = label; // this.active = active; // this.mapTargetDescription = mapTargetDescription; // } // // protected SnomedRefSetMemberIndexEntry(final IComponent<String> component, String iconId) { // super(Preconditions.checkNotNull(component, "Component argument cannot be null.").getId(), iconId, 0.0F, -1L, Concepts.MODULE_SCT_CORE, false, true, -1L); // referencedComponentId = component.getId(); // refComponentType = CoreTerminologyBroker.getInstance().getTerminologyComponentIdAsShort(component); // label = component.getLabel(); // storageKey = -1L; // } // // /** // * Copy constructor. // * @param entry // */ // protected SnomedRefSetMemberIndexEntry(final SnomedRefSetMemberIndexEntry entry) { // super(entry.getId(), entry.getIconId(), 0.0F, entry.getStorageKey(), entry.getModuleId(), entry.isReleased(), entry.isActive(), entry.getEffectiveTimeAsLong()); // referencedComponentId = entry.getReferencedComponentId(); // refComponentType = CoreTerminologyBroker.getInstance().getTerminologyComponentIdAsShort(entry.getReferencedComponentType()); // specialFieldComponentType = CoreTerminologyBroker.getInstance().getTerminologyComponentIdAsShort(entry.getSpecialFieldComponentType()); // specialFieldId = entry.getSpecialFieldId(); // specialFieldLabel = entry.getSpecialFieldLabel(); // refSetIdentifierId = Long.parseLong(entry.getRefSetIdentifierId()); // refSetType = entry.getRefSetType(); // active = entry.isActive(); // storageKey = entry.getStorageKey(); // label = entry.getLabel(); // mapTargetDescription = entry.mapTargetDescription; // } // // protected SnomedRefSetMemberIndexEntry(final SnomedRefSetMember member, @Nullable final String label, String iconId, final long cdoId, final SnomedRefSet refSet) { // super(member.getUuid(), iconId, 0.0F, cdoId, member.getModuleId(), member.isReleased(), member.isActive(), // member.isSetEffectiveTime() ? member.getEffectiveTime().getTime() : EffectiveTimes.UNSET_EFFECTIVE_TIME); // refSetIdentifierId = Long.parseLong(refSet.getIdentifierId()); // referencedComponentId = member.getReferencedComponentId(); // refComponentType = member.getReferencedComponentType(); // active = member.isActive(); // refSetType = refSet.getType(); // this.label = super.label; //required as we are managing quite different reference for the label // storageKey = cdoId; // // switch (refSetType) { // case SIMPLE: // specialFieldComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER; // specialFieldId = null; // specialFieldLabel = null; // break; // case QUERY: // specialFieldComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER; // specialFieldId = ((SnomedQueryRefSetMember) member).getQuery(); //query string should be set as ID // specialFieldLabel = ((SnomedQueryRefSetMember) member).getQuery(); // break; // case EXTENDED_MAP: //$FALL-THROUGH$ // case COMPLEX_MAP: //$FALL-THROUGH$ // case SIMPLE_MAP: // specialFieldComponentType = ((SnomedMappingRefSet) refSet).getMapTargetComponentType(); // specialFieldId = ((SnomedSimpleMapRefSetMember) member).getMapTargetComponentId(); // mapTargetDescription = ((SnomedSimpleMapRefSetMember) member).getMapTargetComponentDescription(); // if (null == specialFieldId) { // specialFieldId = ""; // } else { // if (!isUnspecified()) { // final IComponent<String> concept = getTerminologyBrowser().getConcept(specialFieldId); // if (null == concept) { // specialFieldLabel = specialFieldId; // } else { // specialFieldLabel = concept.getLabel(); // } // } else { // specialFieldLabel = specialFieldId; // } // } // break; // case DESCRIPTION_TYPE: // final SnomedDescriptionTypeRefSetMember descrMember = (SnomedDescriptionTypeRefSetMember) member; // specialFieldId = descrMember.getDescriptionFormat(); // specialFieldComponentType = SnomedTerminologyComponentConstants.CONCEPT_NUMBER; // specialFieldLabel = CoreTerminologyBroker.getInstance().getComponent( // createPair(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, descrMember.getDescriptionFormat())).getLabel(); // break; // case ATTRIBUTE_VALUE: // final SnomedAttributeValueRefSetMember attrMember = (SnomedAttributeValueRefSetMember) member; // specialFieldId = attrMember.getValueId(); // specialFieldComponentType = SnomedTerminologyComponentConstants.CONCEPT_NUMBER; // specialFieldLabel = CoreTerminologyBroker.getInstance().getComponent( // createPair(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, attrMember.getValueId())).getLabel(); // break; // case LANGUAGE: // final SnomedLanguageRefSetMember langMember = (SnomedLanguageRefSetMember) member; // specialFieldComponentType = SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER; // specialFieldId = langMember.getAcceptabilityId(); // specialFieldLabel = CoreTerminologyBroker.getInstance().getComponent( // createPair(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, specialFieldId)).getLabel(); // break; // case CONCRETE_DATA_TYPE: // specialFieldComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT; // specialFieldId = String.valueOf(((SnomedConcreteDataTypeRefSetMember) member).getDataType().getValue()); // specialFieldLabel = ((SnomedConcreteDataTypeRefSetMember) member).getSerializedValue(); // break; // default: throw new IllegalArgumentException("Unknown reference set type: " + refSet.getType()); // } // // } /** * @return the referenced component identifier */ public String getReferencedComponentId() { return referencedComponentId; } /** * @param fieldName the name of the additional field * @return the {@code String} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code String} */ public String getStringField(final String fieldName) { return getField(fieldName, String.class); } /** * @param fieldName the name of the additional field * @return the {@code Integer} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Integer} */ public Integer getIntegerField(final String fieldName) { return getField(fieldName, Integer.class); } /** * @param fieldName the name of the additional field * @return the {@code Long} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Long} */ public Long getLongField(final String fieldName) { return getField(fieldName, Long.class); } /** * @param fieldName the name of the additional field * @return the {@code BigDecimal} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code BigDecimal} */ public BigDecimal getBigDecimalField(final String fieldName) { return getField(fieldName, BigDecimal.class); } /** * @param fieldName the name of the additional field * @return the {@code Date} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Date} */ public Date getDateField(final String fieldName) { return getField(fieldName, Date.class); } /** * @param fieldName the name of the additional field * @return the {@code Boolean} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Boolean} */ public Boolean getBooleanField(final String fieldName) { return getField(fieldName, Boolean.class); } /** * @param fieldName the name of the additional field * @return the {@code Object} value stored for the field * @throws IllegalStateException if no value was set for the field */ public Object getField(final String fieldName) { return getOptionalField(fieldName).get(); } private Optional<Object> getOptionalField(final String fieldName) { return Optional.fromNullable(additionalFields.get(fieldName)); } private <T> T getField(final String fieldName, final Class<T> type) { return getField(fieldName, new UncheckedCastFunction<Object, T>(type)); } private <T> T getField(final String fieldName, Function<Object, T> transformFunction) { return getOptionalField(fieldName).transform(transformFunction).get(); } /** * @return the identifier of the member's reference set */ public String getRefSetIdentifierId() { return referenceSetId; } /** * @return the type of the member's reference set */ public SnomedRefSetType getRefSetType() { return referenceSetType; } /** * @return the {@code String} terminology component identifier of the component referenced in this member */ public String getReferencedComponentType() { return CoreTerminologyBroker.getInstance().getTerminologyComponentId(referencedComponentType); } /** * @return the {@code String} terminology component identifier of the map target in this member, or * {@link CoreTerminologyBroker#UNSPECIFIED} if not known (or the reference set is not a map) */ public String getMapTargetComponentType() { return CoreTerminologyBroker.getInstance().getTerminologyComponentId(mapTargetComponentType); } /** * @return the {@code String} terminology component identifier of the map target in this member, or * {@link CoreTerminologyBroker#UNSPECIFIED_NUMBER_SHORT} if not known (or the reference set is not a map) */ public short getMapTargetComponentTypeAsShort() { return mapTargetComponentType; } @Override public String toString() { return toStringHelper() .add("referencedComponentId", referencedComponentId) .add("additionalFields", additionalFields) .add("referenceSetType", referenceSetType) .add("referencedComponentType", referencedComponentType) .add("mapTargetComponentType", mapTargetComponentType) .toString(); } @SuppressWarnings("unchecked") public <T> T getValue() { return (T) getField(SnomedMappings.memberSerializedValue().fieldName()); } public DataType getRefSetPackageDataType() { return DataType.get(getIntegerField(SnomedMappings.memberDataTypeOrdinal().fieldName())); } public String getUomComponentId() { return getStringField(SnomedMappings.memberUomId().fieldName()); } public String getAttributeLabel() { return getStringField(SnomedMappings.memberDataTypeLabel().fieldName()); } public String getOperatorComponentId() { return getStringField(SnomedMappings.memberOperatorId().fieldName()); } public String getCharacteristicTypeId() { return getStringField(SnomedMappings.memberCharacteristicTypeId().fieldName()); } public Acceptability getAcceptability() { return Acceptability.getByConceptId(getAcceptabilityId()); } public String getAcceptabilityId() { return StringUtils.valueOfOrEmptyString(getLongField(SnomedMappings.memberAcceptabilityId().fieldName())); } public Integer getDescriptionLength() { return getIntegerField(SnomedMappings.memberDescriptionLength().fieldName()); } public String getMapTargetComponentId() { return getStringField(SnomedMappings.memberMapTargetComponentId().fieldName()); } public int getMapGroup() { return getIntegerField(SnomedMappings.memberMapGroup().fieldName()); } public int getMapPriority() { return getIntegerField(SnomedMappings.memberMapPriority().fieldName()); } public String getMapRule() { return getStringField(SnomedMappings.memberMapRule().fieldName()); } public String getMapAdvice() { return getStringField(SnomedMappings.memberMapAdvice().fieldName()); } public String getMapCategoryId() { return getStringField(SnomedMappings.memberMapCategoryId().fieldName()); } public String getCorrelationId() { return getStringField(SnomedMappings.memberCorrelationId().fieldName()); } public String getMapTargetDescription() { return getStringField(SnomedMappings.memberMapTargetComponentDescription().fieldName()); } public String getQuery() { return getStringField(SnomedMappings.memberQuery().fieldName()); } public String getTargetComponentId() { return getStringField(SnomedMappings.memberTargetComponentId().fieldName()); } public RelationshipRefinability getRefinability() { return RelationshipRefinability.getByConceptId(getValueId()); } public InactivationIndicator getInactivationIndicator() { return InactivationIndicator.getByConceptId(getValueId()); } public String getValueId() { return getStringField(SnomedMappings.memberValueId().fieldName()); } @Deprecated public String getSpecialFieldLabel() { throw new UnsupportedOperationException("Special field label needs to be computed separately."); } }
snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/index/entry/SnomedRefSetMemberIndexEntry.java
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.datastore.index.entry; import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.CONCEPT_NUMBER; import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER; import static com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants.RELATIONSHIP_NUMBER; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.newHashMap; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.Set; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexableField; import com.b2international.commons.BooleanUtils; import com.b2international.commons.functions.UncheckedCastFunction; import com.b2international.snowowl.core.CoreTerminologyBroker; import com.b2international.snowowl.core.api.IComponent; import com.b2international.snowowl.core.date.EffectiveTimes; import com.b2international.snowowl.datastore.index.mapping.Mappings; import com.b2international.snowowl.snomed.core.domain.Acceptability; import com.b2international.snowowl.snomed.core.domain.InactivationIndicator; import com.b2international.snowowl.snomed.core.domain.RelationshipRefinability; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.core.domain.SnomedCoreComponent; import com.b2international.snowowl.snomed.core.domain.SnomedDescription; import com.b2international.snowowl.snomed.core.domain.SnomedRelationship; import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember; import com.b2international.snowowl.snomed.datastore.SnomedRefSetUtil; import com.b2international.snowowl.snomed.datastore.index.mapping.SnomedMappings; import com.b2international.snowowl.snomed.snomedrefset.DataType; import com.b2international.snowowl.snomed.snomedrefset.SnomedRefSetType; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableMap; /** * Lightweight representation of a SNOMED CT reference set member. */ public class SnomedRefSetMemberIndexEntry extends SnomedIndexEntry implements IComponent<String>, Serializable { private static final Set<String> ADDITIONAL_FIELDS = SnomedMappings.fieldsToLoad() .memberAcceptabilityId() .memberValueId() .memberTargetComponentId() .memberMapTargetComponentId() .memberMapTargetComponentDescription() .memberMapGroup() .memberMapPriority() .memberMapRule() .memberMapAdvice() .memberMapCategoryId() .memberCorrelationId() .memberDescriptionFormatId() .memberDescriptionLength() .memberOperatorId() .memberContainerModuleId() .memberUomId() .memberDataTypeLabel() .memberDataTypeOrdinal() .memberSerializedValue() .memberCharacteristicTypeId() .memberQuery() .memberSourceEffectiveTime() .memberTargetEffectiveTime() .build(); /** * @param name the field name to check * @return {@code true} if the specified field name is valid as an additional {@code String} or {@link Number} value, {@code false} otherwise */ public static boolean isAdditionalField(final String name) { return ADDITIONAL_FIELDS.contains(name); } private static final long serialVersionUID = 3504576207161692354L; public static Builder builder() { return new Builder(); } public static Builder builder(final Document doc) { final SnomedRefSetType refSetType = SnomedRefSetType.get(SnomedMappings.memberRefSetType().getValue(doc)); final Builder builder = builder() .active(BooleanUtils.valueOf(SnomedMappings.active().getValue(doc))) .effectiveTimeLong(SnomedMappings.effectiveTime().getValue(doc)) .id(SnomedMappings.memberUuid().getValue(doc)) .moduleId(SnomedMappings.module().getValueAsString(doc)) .referencedComponentId(SnomedMappings.memberReferencedComponentId().getValueAsString(doc)) .referencedComponentType(SnomedMappings.memberReferencedComponentType().getShortValue(doc)) .referenceSetId(SnomedMappings.memberRefSetId().getValueAsString(doc)) .referenceSetType(refSetType) .released(BooleanUtils.valueOf(SnomedMappings.released().getValue(doc))) .storageKey(Mappings.storageKey().getValue(doc)); if (SnomedRefSetUtil.isMapping(refSetType)) { builder.mapTargetComponentType(SnomedMappings.memberMapTargetComponentType().getShortValue(doc)); } for (IndexableField storedField : doc) { if (SnomedRefSetMemberIndexEntry.isAdditionalField(storedField.name())) { if (storedField.numericValue() != null) { builder.additionalField(storedField.name(), storedField.numericValue()); } else { builder.additionalField(storedField.name(), storedField.stringValue()); } } } return builder; } public static Builder builder(final SnomedRefSetMemberIndexEntry source) { return builder() .active(source.active) .effectiveTimeLong(source.effectiveTimeLong) .id(source.id) .moduleId(source.moduleId) .referencedComponentId(source.referencedComponentId) .referencedComponentType(source.referencedComponentType) .referenceSetId(source.getRefSetIdentifierId()) .referenceSetType(source.referenceSetType) .released(source.released) .storageKey(source.storageKey) .score(source.score) .mapTargetComponentType(source.mapTargetComponentType) .additionalFields(source.additionalFields); } public static final Builder builder(final SnomedReferenceSetMember input) { final Object mapTargetComponentType = input.getProperties().get(SnomedMappings.memberMapTargetComponentType().fieldName()); return builder() .active(input.isActive()) .effectiveTimeLong(EffectiveTimes.getEffectiveTime(input.getEffectiveTime())) .id(input.getId()) .moduleId(input.getModuleId()) .referencedComponentId(input.getReferencedComponent().getId()) .referencedComponentType(input.getReferencedComponent()) .referenceSetId(input.getReferenceSetId()) .referenceSetType(input.type()) .released(input.isReleased()) .mapTargetComponentType(mapTargetComponentType == null ? -1 : (short) mapTargetComponentType) .additionalFields(input.getProperties()); } public static Collection<SnomedRefSetMemberIndexEntry> from(final Collection<SnomedReferenceSetMember> refSetMembers) { return FluentIterable.from(refSetMembers).transform(new Function<SnomedReferenceSetMember, SnomedRefSetMemberIndexEntry>() { @Override public SnomedRefSetMemberIndexEntry apply(final SnomedReferenceSetMember refSetMember) { return builder(refSetMember).build(); } }).toList(); } public static class Builder extends AbstractBuilder<Builder> { private String referencedComponentId; private final Map<String, Object> additionalFields = newHashMap(); private String referenceSetId; private SnomedRefSetType referenceSetType; private short referencedComponentType; private short mapTargetComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT; private Builder() { // Disallow instantiation outside static method } @Override protected Builder getSelf() { return this; } public Builder referencedComponentId(final String referencedComponentId) { this.referencedComponentId = referencedComponentId; return this; } public Builder additionalField(final String fieldName, final Object fieldValue) { this.additionalFields.put(fieldName, fieldValue); return this; } public Builder additionalFields(final Map<String, Object> additionalFields) { this.additionalFields.putAll(additionalFields); return this; } public Builder referenceSetId(final String referenceSetId) { this.referenceSetId = referenceSetId; return this; } public Builder referenceSetType(final SnomedRefSetType referenceSetType) { this.referenceSetType = referenceSetType; return this; } public Builder referencedComponentType(final short referencedComponentType) { this.referencedComponentType = referencedComponentType; return this; } public Builder referencedComponentType(final SnomedCoreComponent component) { if (component instanceof SnomedConcept) { this.referencedComponentType = CONCEPT_NUMBER; } else if (component instanceof SnomedDescription) { this.referencedComponentType = DESCRIPTION_NUMBER; } else if (component instanceof SnomedRelationship) { this.referencedComponentType = RELATIONSHIP_NUMBER; } else { this.referencedComponentType = -1; } return this; } public Builder mapTargetComponentType(final short mapTargetComponentType) { this.mapTargetComponentType = mapTargetComponentType; return this; } public SnomedRefSetMemberIndexEntry build() { return new SnomedRefSetMemberIndexEntry(id, label, score, storageKey, moduleId, released, active, effectiveTimeLong, referencedComponentId, ImmutableMap.copyOf(additionalFields), referenceSetId, referenceSetType, referencedComponentType, mapTargetComponentType); } } private final String referencedComponentId; private final ImmutableMap<String, Object> additionalFields; private final String referenceSetId; private final SnomedRefSetType referenceSetType; private final short referencedComponentType; private final short mapTargetComponentType; private SnomedRefSetMemberIndexEntry(final String id, final String label, final float score, final long storageKey, final String moduleId, final boolean released, final boolean active, final long effectiveTimeLong, final String referencedComponentId, final ImmutableMap<String, Object> additionalFields, final String referenceSetId, final SnomedRefSetType referenceSetType, final short referencedComponentType, final short mapTargetComponentType) { super(id, label, referenceSetId, // XXX: iconId is the reference set identifier score, storageKey, moduleId, released, active, effectiveTimeLong); checkArgument(referencedComponentType >= CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT, "Referenced component type '%s' is invalid.", referencedComponentType); checkArgument(mapTargetComponentType >= CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT, "Map target component type '%s' is invalid.", referencedComponentType); this.referencedComponentId = checkNotNull(referencedComponentId, "Reference component identifier may not be null."); this.additionalFields = checkNotNull(additionalFields, "Additional field map may not be null."); this.referenceSetId = checkNotNull(referenceSetId, "Reference set identifier may not be null."); this.referenceSetType = checkNotNull(referenceSetType, "Reference set type may not be null."); this.referencedComponentType = referencedComponentType; this.mapTargetComponentType = mapTargetComponentType; } // /** // * (non-API) // * Creates a reference set member from a CDOish object. // */ // public static SnomedRefSetMemberIndexEntry create(final SnomedRefSetMember member) { // return create(member, null); // } // // /** // * (non-API) // * Creates a reference set member from a CDOish object with the given label of the referenced component. // */ // public static SnomedRefSetMemberIndexEntry create(final SnomedRefSetMember member, @Nullable final String label) { // Preconditions.checkNotNull(member, "Reference set member argument cannot be null."); // Preconditions.checkArgument(!CDOState.NEW.equals(member.cdoState()), "Reference set member CDO state should not be NEW. " + // "Use com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetLuceneIndexDTO.createForNewMember(SnomedRefSetMember<?>) instead."); // Preconditions.checkArgument(!CDOState.TRANSIENT.equals(member.cdoState()), "Reference set member CDO state should not be TRANSIENT. " + // "Use com.b2international.snowowl.snomed.datastore.index.refset.SnomedRefSetLuceneIndexDTO.createForDetachedMember(SnomedRefSetMember<?>, SnomedRefSet<?>) instead"); // return new SnomedRefSetMemberIndexEntry(member, label, tryGetIconId(member), CDOIDUtil.getLong(member.cdoID()), member.getRefSet()); // } // // /** // * (non-API) // * Creates a reference set member from a new CDOish reference set member. // */ // public static SnomedRefSetMemberIndexEntry createForNewMember(final SnomedRefSetMember member) { // return createForNewMember(member, null); // } // // /** // * (non-API) // * Creates a reference set member from a new CDOish reference set member with the given label of the referenced component. // */ // public static SnomedRefSetMemberIndexEntry createForNewMember(final SnomedRefSetMember member, @Nullable final String label) { // Preconditions.checkNotNull(member, "Reference set member argument cannot be null."); // Preconditions.checkArgument(CDOState.NEW.equals(member.cdoState()), "Reference set member CDO state must be NEW."); // return new SnomedRefSetMemberIndexEntry(member, label, tryGetIconId(member), 0L, member.getRefSet()); // } // // /** // * (non-API) // * Creates a reference set member representing a detached member. // */ // public static SnomedRefSetMemberIndexEntry createForDetachedMember(final SnomedRefSetMember member, final SnomedRefSet refSet) { // return createForDetachedMember(member, refSet, null); // } // // /** // * (non-API) // * Creates a reference set member representing a detached member. // */ // public static SnomedRefSetMemberIndexEntry createForDetachedMember(final SnomedRefSetMember member, final SnomedRefSet refSet, @Nullable final String label) { // Preconditions.checkNotNull(member, "Reference set member argument cannot be null."); // Preconditions.checkNotNull(refSet, "Container reference set argument cannot be null."); // Preconditions.checkArgument(CDOState.TRANSIENT.equals(member.cdoState()), "Reference set member CDO state must be TRANSIENT."); // return new SnomedRefSetMemberIndexEntry(member, label, SnomedConstants.Concepts.ROOT_CONCEPT, 0L, refSet); // } // // /** // * (non-API) // * Creates a mock reference set member. // */ // public static SnomedRefSetMemberIndexEntry createMockMember(final IComponent<String> component) { // return new SnomedRefSetMemberIndexEntry(component, SnomedIconProvider.getInstance().getIconComponentId(component.getId())); // } // // protected static String tryGetIconId(final SnomedRefSetMember member) { // // if (CDOUtils.checkObject(member)) { // // if (member instanceof SnomedQueryRefSetMember) { // return Concepts.REFSET_ROOT_CONCEPT; // } // // final short referencedComponentType = member.getReferencedComponentType(); // final String referencedComponentId = member.getReferencedComponentId(); // Object iconIdAsobject = CoreTerminologyBroker.getInstance().getComponentIconIdProvider(referencedComponentType).getIconId(BranchPathUtils.createPath(member.cdoView()), referencedComponentId); // if (null != iconIdAsobject) { // return String.valueOf(iconIdAsobject); // } // // } // // return Concepts.ROOT_CONCEPT; // } // // /** // * (non-API) // * Creates a new reference set member based on the given index document. // */ // public static SnomedRefSetMemberIndexEntry create(final Document doc, @Nullable final IBranchPath branchPath) { // Preconditions.checkNotNull(doc, "Document argument cannot be null."); // // final SnomedRefSetType type = SnomedRefSetType.get(SnomedMappings.memberRefSetType().getValue(doc)); // final String uuid = doc.get(SnomedIndexBrowserConstants.REFERENCE_SET_MEMBER_UUID); // final String moduleId = SnomedMappings.module().getValueAsString(doc); // final long storageKey = Mappings.storageKey().getValue(doc); // final boolean active = SnomedMappings.active().getValue(doc) == 1; // final boolean released = IndexUtils.getBooleanValue(doc.getField(SnomedIndexBrowserConstants.COMPONENT_RELEASED)); // final long refSetId = SnomedMappings.memberRefSetId().getValue(doc); // final short referencedComponentType = SnomedMappings.memberReferencedComponentType().getShortValue(doc); // final String referencedComponentId = SnomedMappings.memberReferencedComponentId().getValueAsString(doc); // final long effectiveTimeLong = SnomedMappings.effectiveTime().getValue(doc); // final short specialFieldComponentType = isMapping(type) ? getSpecialFieldComponentTypeId(doc) : getSpecialFieldComponentTypeId(type); // final String specialFieldId = doc.get(SnomedRefSetUtil.getSpecialComponentIdIndexField(type)); // final String mapTargetDescription = doc.get(SnomedIndexBrowserConstants.REFERENCE_SET_MEMBER_MAP_TARGET_COMPONENT_DESCRIPTION); // // String iconId = null; // if (null != branchPath) { // Object iconIdAsObjact = CoreTerminologyBroker.getInstance().getComponentIconIdProvider(referencedComponentType).getIconId(branchPath, referencedComponentId); // if (null != iconIdAsObjact) { // iconId = String.valueOf(iconIdAsObjact); // } // } // // return new SnomedRefSetMemberIndexEntry( // uuid, // uuid, // iconId, // moduleId, // 0.0F, // storageKey, // released, // active, // refSetId, // referencedComponentType, // referencedComponentId, // type, // effectiveTimeLong, // specialFieldComponentType, // specialFieldId, // mapTargetDescription); // // } // // // /** // * @param id // * @param label // * @param iconId TODO // * @param moduleId // * @param score // * @param storageKey // * @param storageKey // * @param released // * @param active // * @param refSetIdentifierId // * @param refComponentType // * @param referencedComponentId // * @param refSetType // * @param effectiveTime // * @param specialFieldComponentType // * @param specialFieldLabel // * @param specialFieldId // * @param mapTargetDescription2 // */ // private SnomedRefSetMemberIndexEntry(final String id, final String label, String iconId, final String moduleId, // final float score, final long storageKey, final boolean released, final boolean active, // final long refSetIdentifierId, final short refComponentType, final String referencedComponentId, // final SnomedRefSetType refSetType, final long effectiveTime, final short specialFieldComponentType, final String specialFieldLabel, final String specialFieldId, final String mapTargetDescription) { // // super(id, iconId, score, storageKey, moduleId, released, active, effectiveTime); // this.refSetIdentifierId = refSetIdentifierId; // this.refComponentType = refComponentType; // this.referencedComponentId = referencedComponentId; // this.refSetType = refSetType; // this.storageKey = storageKey; // this.specialFieldComponentType = specialFieldComponentType; // this.specialFieldLabel = specialFieldLabel; // this.specialFieldId = specialFieldId; // this.label = label; // this.active = active; // this.mapTargetDescription = mapTargetDescription; // } // // protected SnomedRefSetMemberIndexEntry(final IComponent<String> component, String iconId) { // super(Preconditions.checkNotNull(component, "Component argument cannot be null.").getId(), iconId, 0.0F, -1L, Concepts.MODULE_SCT_CORE, false, true, -1L); // referencedComponentId = component.getId(); // refComponentType = CoreTerminologyBroker.getInstance().getTerminologyComponentIdAsShort(component); // label = component.getLabel(); // storageKey = -1L; // } // // /** // * Copy constructor. // * @param entry // */ // protected SnomedRefSetMemberIndexEntry(final SnomedRefSetMemberIndexEntry entry) { // super(entry.getId(), entry.getIconId(), 0.0F, entry.getStorageKey(), entry.getModuleId(), entry.isReleased(), entry.isActive(), entry.getEffectiveTimeAsLong()); // referencedComponentId = entry.getReferencedComponentId(); // refComponentType = CoreTerminologyBroker.getInstance().getTerminologyComponentIdAsShort(entry.getReferencedComponentType()); // specialFieldComponentType = CoreTerminologyBroker.getInstance().getTerminologyComponentIdAsShort(entry.getSpecialFieldComponentType()); // specialFieldId = entry.getSpecialFieldId(); // specialFieldLabel = entry.getSpecialFieldLabel(); // refSetIdentifierId = Long.parseLong(entry.getRefSetIdentifierId()); // refSetType = entry.getRefSetType(); // active = entry.isActive(); // storageKey = entry.getStorageKey(); // label = entry.getLabel(); // mapTargetDescription = entry.mapTargetDescription; // } // // protected SnomedRefSetMemberIndexEntry(final SnomedRefSetMember member, @Nullable final String label, String iconId, final long cdoId, final SnomedRefSet refSet) { // super(member.getUuid(), iconId, 0.0F, cdoId, member.getModuleId(), member.isReleased(), member.isActive(), // member.isSetEffectiveTime() ? member.getEffectiveTime().getTime() : EffectiveTimes.UNSET_EFFECTIVE_TIME); // refSetIdentifierId = Long.parseLong(refSet.getIdentifierId()); // referencedComponentId = member.getReferencedComponentId(); // refComponentType = member.getReferencedComponentType(); // active = member.isActive(); // refSetType = refSet.getType(); // this.label = super.label; //required as we are managing quite different reference for the label // storageKey = cdoId; // // switch (refSetType) { // case SIMPLE: // specialFieldComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER; // specialFieldId = null; // specialFieldLabel = null; // break; // case QUERY: // specialFieldComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER; // specialFieldId = ((SnomedQueryRefSetMember) member).getQuery(); //query string should be set as ID // specialFieldLabel = ((SnomedQueryRefSetMember) member).getQuery(); // break; // case EXTENDED_MAP: //$FALL-THROUGH$ // case COMPLEX_MAP: //$FALL-THROUGH$ // case SIMPLE_MAP: // specialFieldComponentType = ((SnomedMappingRefSet) refSet).getMapTargetComponentType(); // specialFieldId = ((SnomedSimpleMapRefSetMember) member).getMapTargetComponentId(); // mapTargetDescription = ((SnomedSimpleMapRefSetMember) member).getMapTargetComponentDescription(); // if (null == specialFieldId) { // specialFieldId = ""; // } else { // if (!isUnspecified()) { // final IComponent<String> concept = getTerminologyBrowser().getConcept(specialFieldId); // if (null == concept) { // specialFieldLabel = specialFieldId; // } else { // specialFieldLabel = concept.getLabel(); // } // } else { // specialFieldLabel = specialFieldId; // } // } // break; // case DESCRIPTION_TYPE: // final SnomedDescriptionTypeRefSetMember descrMember = (SnomedDescriptionTypeRefSetMember) member; // specialFieldId = descrMember.getDescriptionFormat(); // specialFieldComponentType = SnomedTerminologyComponentConstants.CONCEPT_NUMBER; // specialFieldLabel = CoreTerminologyBroker.getInstance().getComponent( // createPair(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, descrMember.getDescriptionFormat())).getLabel(); // break; // case ATTRIBUTE_VALUE: // final SnomedAttributeValueRefSetMember attrMember = (SnomedAttributeValueRefSetMember) member; // specialFieldId = attrMember.getValueId(); // specialFieldComponentType = SnomedTerminologyComponentConstants.CONCEPT_NUMBER; // specialFieldLabel = CoreTerminologyBroker.getInstance().getComponent( // createPair(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, attrMember.getValueId())).getLabel(); // break; // case LANGUAGE: // final SnomedLanguageRefSetMember langMember = (SnomedLanguageRefSetMember) member; // specialFieldComponentType = SnomedTerminologyComponentConstants.DESCRIPTION_NUMBER; // specialFieldId = langMember.getAcceptabilityId(); // specialFieldLabel = CoreTerminologyBroker.getInstance().getComponent( // createPair(SnomedTerminologyComponentConstants.CONCEPT_NUMBER, specialFieldId)).getLabel(); // break; // case CONCRETE_DATA_TYPE: // specialFieldComponentType = CoreTerminologyBroker.UNSPECIFIED_NUMBER_SHORT; // specialFieldId = String.valueOf(((SnomedConcreteDataTypeRefSetMember) member).getDataType().getValue()); // specialFieldLabel = ((SnomedConcreteDataTypeRefSetMember) member).getSerializedValue(); // break; // default: throw new IllegalArgumentException("Unknown reference set type: " + refSet.getType()); // } // // } /** * @return the referenced component identifier */ public String getReferencedComponentId() { return referencedComponentId; } /** * @param fieldName the name of the additional field * @return the {@code String} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code String} */ public String getStringField(final String fieldName) { return getField(fieldName, String.class); } /** * @param fieldName the name of the additional field * @return the {@code Integer} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Integer} */ public Integer getIntegerField(final String fieldName) { return getField(fieldName, Integer.class); } /** * @param fieldName the name of the additional field * @return the {@code BigDecimal} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code BigDecimal} */ public BigDecimal getBigDecimalField(final String fieldName) { return getField(fieldName, BigDecimal.class); } /** * @param fieldName the name of the additional field * @return the {@code Date} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Date} */ public Date getDateField(final String fieldName) { return getField(fieldName, Date.class); } /** * @param fieldName the name of the additional field * @return the {@code Boolean} value stored for the field * @throws IllegalStateException if no value was set for the field * @throws ClassCastException if the value is not of type {@code Boolean} */ public Boolean getBooleanField(final String fieldName) { return getField(fieldName, Boolean.class); } /** * @param fieldName the name of the additional field * @return the {@code Object} value stored for the field * @throws IllegalStateException if no value was set for the field */ public Object getField(final String fieldName) { return getOptionalField(fieldName).get(); } private Optional<Object> getOptionalField(final String fieldName) { return Optional.fromNullable(additionalFields.get(fieldName)); } private <T> T getField(final String fieldName, final Class<T> type) { return getField(fieldName, new UncheckedCastFunction<Object, T>(type)); } private <T> T getField(final String fieldName, Function<Object, T> transformFunction) { return getOptionalField(fieldName).transform(transformFunction).get(); } /** * @return the identifier of the member's reference set */ public String getRefSetIdentifierId() { return referenceSetId; } /** * @return the type of the member's reference set */ public SnomedRefSetType getRefSetType() { return referenceSetType; } /** * @return the {@code String} terminology component identifier of the component referenced in this member */ public String getReferencedComponentType() { return CoreTerminologyBroker.getInstance().getTerminologyComponentId(referencedComponentType); } /** * @return the {@code String} terminology component identifier of the map target in this member, or * {@link CoreTerminologyBroker#UNSPECIFIED} if not known (or the reference set is not a map) */ public String getMapTargetComponentType() { return CoreTerminologyBroker.getInstance().getTerminologyComponentId(mapTargetComponentType); } /** * @return the {@code String} terminology component identifier of the map target in this member, or * {@link CoreTerminologyBroker#UNSPECIFIED_NUMBER_SHORT} if not known (or the reference set is not a map) */ public short getMapTargetComponentTypeAsShort() { return mapTargetComponentType; } @Override public String toString() { return toStringHelper() .add("referencedComponentId", referencedComponentId) .add("additionalFields", additionalFields) .add("referenceSetType", referenceSetType) .add("referencedComponentType", referencedComponentType) .add("mapTargetComponentType", mapTargetComponentType) .toString(); } @SuppressWarnings("unchecked") public <T> T getValue() { return (T) getField(SnomedMappings.memberSerializedValue().fieldName()); } public DataType getRefSetPackageDataType() { return DataType.get(getIntegerField(SnomedMappings.memberDataTypeOrdinal().fieldName())); } public String getUomComponentId() { return getStringField(SnomedMappings.memberUomId().fieldName()); } public String getAttributeLabel() { return getStringField(SnomedMappings.memberDataTypeLabel().fieldName()); } public String getOperatorComponentId() { return getStringField(SnomedMappings.memberOperatorId().fieldName()); } public String getCharacteristicTypeId() { return getStringField(SnomedMappings.memberCharacteristicTypeId().fieldName()); } public Acceptability getAcceptability() { return Acceptability.getByConceptId(getAcceptabilityId()); } public String getAcceptabilityId() { return getStringField(SnomedMappings.memberAcceptabilityId().fieldName()); } public Integer getDescriptionLength() { return getIntegerField(SnomedMappings.memberDescriptionLength().fieldName()); } public String getMapTargetComponentId() { return getStringField(SnomedMappings.memberMapTargetComponentId().fieldName()); } public int getMapGroup() { return getIntegerField(SnomedMappings.memberMapGroup().fieldName()); } public int getMapPriority() { return getIntegerField(SnomedMappings.memberMapPriority().fieldName()); } public String getMapRule() { return getStringField(SnomedMappings.memberMapRule().fieldName()); } public String getMapAdvice() { return getStringField(SnomedMappings.memberMapAdvice().fieldName()); } public String getMapCategoryId() { return getStringField(SnomedMappings.memberMapCategoryId().fieldName()); } public String getCorrelationId() { return getStringField(SnomedMappings.memberCorrelationId().fieldName()); } public String getMapTargetDescription() { return getStringField(SnomedMappings.memberMapTargetComponentDescription().fieldName()); } public String getQuery() { return getStringField(SnomedMappings.memberQuery().fieldName()); } public String getTargetComponentId() { return getStringField(SnomedMappings.memberTargetComponentId().fieldName()); } public RelationshipRefinability getRefinability() { return RelationshipRefinability.getByConceptId(getValueId()); } public InactivationIndicator getInactivationIndicator() { return InactivationIndicator.getByConceptId(getValueId()); } public String getValueId() { return getStringField(SnomedMappings.memberValueId().fieldName()); } @Deprecated public String getSpecialFieldLabel() { throw new UnsupportedOperationException("Special field label needs to be computed separately."); } }
SO-1787 Get acceptability id as long field.
snomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/index/entry/SnomedRefSetMemberIndexEntry.java
SO-1787 Get acceptability id as long field.
<ide><path>nomed/com.b2international.snowowl.snomed.datastore/src/com/b2international/snowowl/snomed/datastore/index/entry/SnomedRefSetMemberIndexEntry.java <ide> import org.apache.lucene.index.IndexableField; <ide> <ide> import com.b2international.commons.BooleanUtils; <add>import com.b2international.commons.StringUtils; <ide> import com.b2international.commons.functions.UncheckedCastFunction; <ide> import com.b2international.snowowl.core.CoreTerminologyBroker; <ide> import com.b2international.snowowl.core.api.IComponent; <ide> public Integer getIntegerField(final String fieldName) { <ide> return getField(fieldName, Integer.class); <ide> } <add> /** <add> * @param fieldName the name of the additional field <add> * @return the {@code Long} value stored for the field <add> * @throws IllegalStateException if no value was set for the field <add> * @throws ClassCastException if the value is not of type {@code Long} <add> */ <add> public Long getLongField(final String fieldName) { <add> return getField(fieldName, Long.class); <add> } <ide> <ide> /** <ide> * @param fieldName the name of the additional field <ide> } <ide> <ide> public String getAcceptabilityId() { <del> return getStringField(SnomedMappings.memberAcceptabilityId().fieldName()); <add> return StringUtils.valueOfOrEmptyString(getLongField(SnomedMappings.memberAcceptabilityId().fieldName())); <ide> } <ide> <ide> public Integer getDescriptionLength() {
Java
mit
c3a8484190e691e04e045be5ccee3e21d5278a03
0
raoulvdberge/refinedstorage,way2muchnoise/refinedstorage,raoulvdberge/refinedstorage,way2muchnoise/refinedstorage
package com.raoulvdberge.refinedstorage.apiimpl.network.node.cover; import com.raoulvdberge.refinedstorage.RSItems; import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode; import com.raoulvdberge.refinedstorage.apiimpl.API; import com.raoulvdberge.refinedstorage.apiimpl.network.node.ICoverable; import com.raoulvdberge.refinedstorage.apiimpl.network.node.NetworkNode; import com.raoulvdberge.refinedstorage.item.ItemCover; import net.minecraft.block.Block; import net.minecraft.block.BlockGlass; import net.minecraft.block.BlockStainedGlass; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemStackHandler; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; public class CoverManager { private static final String NBT_DIRECTION = "Direction"; private static final String NBT_ITEM = "Item"; private Map<EnumFacing, ItemStack> covers = new HashMap<>(); private NetworkNode node; private boolean canPlaceCoversOnFace = true; public CoverManager(NetworkNode node) { this.node = node; } public boolean canConduct(EnumFacing direction) { if (hasCover(direction)) { return false; } INetworkNode neighbor = API.instance().getNetworkNodeManager(node.getWorld()).getNode(node.getPos().offset(direction)); if (neighbor instanceof ICoverable && ((ICoverable) neighbor).getCoverManager().hasCover(direction.getOpposite())) { return false; } return true; } @Nullable public ItemStack getCover(EnumFacing facing) { return covers.get(facing); } public boolean hasCover(EnumFacing facing) { return covers.containsKey(facing); } public boolean setCover(EnumFacing facing, ItemStack stack) { if (isValidCover(stack) && !hasCover(facing)) { if (facing == node.getDirection() && !canPlaceCoversOnFace) { return false; } covers.put(facing, stack); node.markDirty(); if (node.getNetwork() != null) { node.getNetwork().getNodeGraph().rebuild(); } return true; } return false; } public CoverManager setCanPlaceCoversOnFace(boolean canPlaceCoversOnFace) { this.canPlaceCoversOnFace = canPlaceCoversOnFace; return this; } public void readFromNbt(NBTTagList list) { for (int i = 0; i < list.tagCount(); ++i) { NBTTagCompound tag = list.getCompoundTagAt(i); if (tag.hasKey(NBT_DIRECTION) && tag.hasKey(NBT_ITEM)) { EnumFacing direction = EnumFacing.getFront(tag.getInteger(NBT_DIRECTION)); ItemStack item = new ItemStack(tag.getCompoundTag(NBT_ITEM)); if (isValidCover(item)) { covers.put(direction, item); } } } } public NBTTagList writeToNbt() { NBTTagList list = new NBTTagList(); for (Map.Entry<EnumFacing, ItemStack> entry : covers.entrySet()) { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger(NBT_DIRECTION, entry.getKey().ordinal()); tag.setTag(NBT_ITEM, entry.getValue().serializeNBT()); list.appendTag(tag); } return list; } public IItemHandlerModifiable getAsInventory() { ItemStackHandler handler = new ItemStackHandler(covers.size()); int i = 0; for (Map.Entry<EnumFacing, ItemStack> entry : covers.entrySet()) { ItemStack cover = new ItemStack(RSItems.COVER); ItemCover.setItem(cover, entry.getValue()); handler.setStackInSlot(i++, cover); } return handler; } @SuppressWarnings("deprecation") public static boolean isValidCover(ItemStack item) { if (item.isEmpty()) { return false; } Block block = getBlock(item); IBlockState state = getBlockState(item); return block != null && state != null && ((isModelSupported(state) && block.isTopSolid(state) && !block.getTickRandomly() && !block.hasTileEntity(state)) || block instanceof BlockGlass || block instanceof BlockStainedGlass); } private static boolean isModelSupported(IBlockState state) { if (state.getRenderType() != EnumBlockRenderType.MODEL || state instanceof IExtendedBlockState) { return false; } return state.isFullCube(); } @Nullable public static Block getBlock(@Nullable ItemStack item) { if (item == null) { return null; } Block block = Block.getBlockFromItem(item.getItem()); if (block == Blocks.AIR) { return null; } return block; } @Nullable @SuppressWarnings("deprecation") public static IBlockState getBlockState(@Nullable ItemStack item) { Block block = getBlock(item); if (block == null) { return null; } try { return block.getStateFromMeta(item.getItem().getMetadata(item)); } catch (Exception e) { return null; } } }
src/main/java/com/raoulvdberge/refinedstorage/apiimpl/network/node/cover/CoverManager.java
package com.raoulvdberge.refinedstorage.apiimpl.network.node.cover; import com.raoulvdberge.refinedstorage.RSItems; import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode; import com.raoulvdberge.refinedstorage.apiimpl.API; import com.raoulvdberge.refinedstorage.apiimpl.network.node.ICoverable; import com.raoulvdberge.refinedstorage.apiimpl.network.node.NetworkNode; import com.raoulvdberge.refinedstorage.item.ItemCover; import net.minecraft.block.Block; import net.minecraft.block.BlockGlass; import net.minecraft.block.BlockStainedGlass; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemStackHandler; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; public class CoverManager { private static final String NBT_DIRECTION = "Direction"; private static final String NBT_ITEM = "Item"; private Map<EnumFacing, ItemStack> covers = new HashMap<>(); private NetworkNode node; private boolean canPlaceCoversOnFace = true; public CoverManager(NetworkNode node) { this.node = node; } public boolean canConduct(EnumFacing direction) { if (hasCover(direction)) { return false; } INetworkNode neighbor = API.instance().getNetworkNodeManager(node.getWorld()).getNode(node.getPos().offset(direction)); if (neighbor instanceof ICoverable && ((ICoverable) neighbor).getCoverManager().hasCover(direction.getOpposite())) { return false; } return true; } @Nullable public ItemStack getCover(EnumFacing facing) { return covers.get(facing); } public boolean hasCover(EnumFacing facing) { return covers.containsKey(facing); } public boolean setCover(EnumFacing facing, ItemStack stack) { if (isValidCover(stack) && !hasCover(facing)) { if (facing == node.getDirection() && !canPlaceCoversOnFace) { return false; } covers.put(facing, stack); node.markDirty(); if (node.getNetwork() != null) { node.getNetwork().getNodeGraph().rebuild(); } return true; } return false; } public CoverManager setCanPlaceCoversOnFace(boolean canPlaceCoversOnFace) { this.canPlaceCoversOnFace = canPlaceCoversOnFace; return this; } public void readFromNbt(NBTTagList list) { for (int i = 0; i < list.tagCount(); ++i) { NBTTagCompound tag = list.getCompoundTagAt(i); if (tag.hasKey(NBT_DIRECTION) && tag.hasKey(NBT_ITEM)) { EnumFacing direction = EnumFacing.getFront(tag.getInteger(NBT_DIRECTION)); ItemStack item = new ItemStack(tag.getCompoundTag(NBT_ITEM)); if (isValidCover(item)) { covers.put(direction, item); } } } } public NBTTagList writeToNbt() { NBTTagList list = new NBTTagList(); for (Map.Entry<EnumFacing, ItemStack> entry : covers.entrySet()) { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger(NBT_DIRECTION, entry.getKey().ordinal()); tag.setTag(NBT_ITEM, entry.getValue().serializeNBT()); list.appendTag(tag); } return list; } public IItemHandlerModifiable getAsInventory() { ItemStackHandler handler = new ItemStackHandler(covers.size()); int i = 0; for (Map.Entry<EnumFacing, ItemStack> entry : covers.entrySet()) { ItemStack cover = new ItemStack(RSItems.COVER); ItemCover.setItem(cover, entry.getValue()); handler.setStackInSlot(i++, cover); } return handler; } @SuppressWarnings("deprecation") public static boolean isValidCover(ItemStack item) { if (item.isEmpty()) { return false; } Block block = getBlock(item); IBlockState state = getBlockState(item); return block != null && state != null && ((isModelSupported(state) && block.isTopSolid(state) && !block.getTickRandomly() && !block.hasTileEntity(state)) || block instanceof BlockGlass || block instanceof BlockStainedGlass); } private static boolean isModelSupported(IBlockState state) { if (state.getRenderType() != EnumBlockRenderType.MODEL || state instanceof IExtendedBlockState) { return false; } return state.isFullCube(); } @Nullable public static Block getBlock(@Nullable ItemStack item) { if (item == null) { return null; } Block block = Block.getBlockFromItem(item.getItem()); if (block == Blocks.AIR) { return null; } return block; } @Nullable @SuppressWarnings("deprecation") public static IBlockState getBlockState(@Nullable ItemStack item) { Block block = getBlock(item); if (block == null) { return null; } return block.getStateFromMeta(item.getItem().getMetadata(item)); } }
Fix crash with covers.
src/main/java/com/raoulvdberge/refinedstorage/apiimpl/network/node/cover/CoverManager.java
Fix crash with covers.
<ide><path>rc/main/java/com/raoulvdberge/refinedstorage/apiimpl/network/node/cover/CoverManager.java <ide> return null; <ide> } <ide> <del> return block.getStateFromMeta(item.getItem().getMetadata(item)); <add> try { <add> return block.getStateFromMeta(item.getItem().getMetadata(item)); <add> } catch (Exception e) { <add> return null; <add> } <ide> } <ide> }
Java
apache-2.0
ebdc464bf18ad49087bbd159e28289eec07db249
0
epalaobe/XMLGenerator
package calypsox.tk.bo.xml; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import com.calypso.tk.core.CashFlow; import com.calypso.tk.core.CashFlowSet; import com.calypso.tk.core.FlowGenerationException; import com.calypso.tk.core.JDate; import com.calypso.tk.core.Log; import com.calypso.tk.core.Trade; import com.calypso.tk.core.TradeBundle; import com.calypso.tk.marketdata.PricingEnv; import com.calypso.tk.upload.jaxb.CalypsoTrade; import com.calypso.tk.upload.jaxb.HolidayCode; import com.calypso.tk.upload.jaxb.Keyword; public abstract class AbstractCDUFTradeBuilder implements CDUFTradeBuilder { /** * Variable for twentyFourHourTimeToMilliseconds method */ private static final int HUNDRED = 100; /** * Variable for twentyFourHourTimeToMilliseconds method */ private static final int SIXTY = 60; /** * Variable for twentyFourHourTimeToMilliseconds method */ private static final int SIXTY_THOUSAND = 60000; /** * Fill some data header that are general to all trades. * * @param trade the trade * @param calypsoTrade the method modifies the calypsoTrade to add the trade data */ @Override public void fillTradeHeader(final PricingEnv pricingEnv, final Trade trade, final CalypsoTrade calypsoTrade) { calypsoTrade.setAction(getAction(trade.getAction())); // required calypsoTrade.setBuySell(getBuySell(trade.getQuantity())); // required calypsoTrade.setComment(trade.getComment()); // required calypsoTrade.setCounterPartyRole(trade.getRole()); // required calypsoTrade.setExternalReference(trade.getExternalReference()); // required calypsoTrade.setInternalReference(trade.getInternalReference()); // required // The cash settle info is a particular property of some products like swaps, then it should not be here but in the irs // generator. It is possible to call the super.fillTradeHeader() and then fill the gaps for the particular product. // calypsoTrade.setCashSettlementInfo() // Trade Notional and StartDate information is from product data, then now it is in the FRA and IRS fillTradeHeader // method. // calypsoTrade.setTradeNotional(); // calypsoTrade.setStartDate(trade.get); //required calypsoTrade.setSalesPerson(trade.getSalesPerson()); // required calypsoTrade.setTradeBook(getBook(trade.getBook())); // required calypsoTrade.setTradeCounterParty(getCounterParty(trade.getCounterParty())); // required calypsoTrade.setTradeCurrency(trade.getTradeCurrency()); // required calypsoTrade.setTradeDateTime(getXmlGregorianCalendarFromDate(getTradeDateJDate(trade.getTradeDate()))); // required calypsoTrade.setTradeSettleDate(getXmlGregorianCalendarFromDate(trade.getSettleDate())); // required calypsoTrade.setTraderName(trade.getTraderName()); // required calypsoTrade.setHolidayCode(getHolidayCode(trade.getProduct())); // required calypsoTrade.setTradeBundleName(getTradeBundle(trade.getBundle())); // required calypsoTrade.setTradeBundleType(getTradeBundleType(trade.getBundle())); // required calypsoTrade.setTradeBundleOneMsg(getTradeBundleOneMessage(trade.getBundle())); calypsoTrade.setMarketType(trade.getMarketType()); calypsoTrade.setMaturityDate(getXmlGregorianCalendarFromDate(trade.getMaturityDate())); calypsoTrade.setMirrorBook(getBook(trade.getMirrorBook())); calypsoTrade.setNegotiatedCurrency(trade.getNegotiatedCurrency()); calypsoTrade.setMarketPlace(getCounterPartyCountry(trade.getCounterParty())); calypsoTrade.setProductSubType(trade.getProductSubType()); // required //nillable calypsoTrade.setTradeId(Integer.valueOf(trade.getId())); // required //nillable calypsoTrade.setTradeKeywords(getTradeKeywords(trade)); calypsoTrade.setReconventionList(getReconventionList(trade.getProduct())); // TODO: calypsoTrade.setTemplateName(); //required // TODO: calypsoTrade.setAllegeActionB(); // TODO: calypsoTrade.setCancelAction(); // TODO: calypsoTrade.setNovation(); // TODO: calypsoTrade.setReprice(); // TODO: calypsoTrade.setReRate(); // TODO: calypsoTrade.setRollDetails(); // TODO: calypsoTrade.setTermination(); // TODO: calypsoTrade.setExercise(); // TODO: calypsoTrade.setFeeReRate(); // TODO: calypsoTrade.setInterestCleanup(); // TODO: calypsoTrade.setTradeEventsInSameBundle(); } /** * @param legalEntity the legal entity * @return the String with legal entity country name. */ String getCounterPartyCountry(final com.calypso.tk.core.LegalEntity legalEntity) { if (legalEntity != null) { return legalEntity.getCountry(); } return null; } /** * @param action the action object * @return the String with action name */ String getAction(final com.calypso.tk.core.Action action) { if (action != null) { return action.toString(); } return null; } /** * Get JDate from JDateTime * * @param jDateTime the JDateTime * @return the JDate Object */ JDate getTradeDateJDate(final com.calypso.tk.core.JDatetime jDateTime) { if (jDateTime != null) { return jDateTime.getJDate(null); } return null; } /** * Get all keywords values in TradeKeywords Object. * * @param trade the trade * @return the TradeKeywords object with all keywords values. */ com.calypso.tk.upload.jaxb.TradeKeywords getTradeKeywords(final Trade trade) { com.calypso.tk.upload.jaxb.TradeKeywords keywords = new com.calypso.tk.upload.jaxb.TradeKeywords(); List<Keyword> kwList = keywords.getKeyword(); @SuppressWarnings("unchecked") Map<String, String> tradeKeywords = trade.getKeywords(); if (tradeKeywords != null) { Set<Entry<String, String>> kwSet = tradeKeywords.entrySet(); for (Entry<String, String> entry : kwSet) { Keyword keyword = new Keyword(); keyword.setKeywordName(entry.getKey()); keyword.setKeywordValue(entry.getValue()); kwList.add(keyword); } } return keywords; } /** * Fill a ReconventionList with data product. * * @param product the product * @return the ReconventionList of product */ com.calypso.tk.upload.jaxb.ReconventionList getReconventionList(final com.calypso.tk.core.Product product) { com.calypso.tk.upload.jaxb.ReconventionList reconventionList = new com.calypso.tk.upload.jaxb.ReconventionList(); List<com.calypso.tk.upload.jaxb.ReconventionDetails> listReconventionDetails = reconventionList.getReconventionDetails(); List<com.calypso.tk.product.reconvention.Reconvention> reconventions = com.calypso.tk.product.reconvention.impl.ReconventionUtil.getReconventions(product); for (com.calypso.tk.product.reconvention.Reconvention reconvention : reconventions) { com.calypso.tk.upload.jaxb.ReconventionDetails reconventionDetails = new com.calypso.tk.upload.jaxb.ReconventionDetails(); reconventionDetails.setEffectiveDate(getXmlGregorianCalendarFromDate(reconvention.getEffectiveDate())); reconventionDetails.setParameters(getReconventionParameters(reconvention)); reconventionDetails.setPreScheduledB(reconvention.getIsPrescheduled()); // TODO: reconventionDetails.setPrincipalStructure(); reconventionDetails.setReconventionDatetime(getXmlGregorianCalendarFromDate(reconvention.getReconventionDatetime().getJDate(null))); reconventionDetails.setType(getReconventionType(reconvention.getReconventionType())); listReconventionDetails.add(reconventionDetails); } return null; } /** * Fill Parameters Object with reconvention data. * * @param reconvention the reconvention * @return the Parameters Object with reconvention data. */ com.calypso.tk.upload.jaxb.Parameters getReconventionParameters(final com.calypso.tk.product.reconvention.Reconvention reconvention) { com.calypso.tk.upload.jaxb.Parameters parameters = new com.calypso.tk.upload.jaxb.Parameters(); List<com.calypso.tk.upload.jaxb.Parameter> listParameters = parameters.getParameter(); List<com.calypso.tk.product.reconvention.ReconventionParameter<?>> reconventionParameters = reconvention.getReconventionParameters(); for (com.calypso.tk.product.reconvention.ReconventionParameter<?> reconventionParameter : reconventionParameters) { com.calypso.tk.upload.jaxb.Parameter parameter = new com.calypso.tk.upload.jaxb.Parameter(); parameter.setParameterName(reconventionParameter.getName()); parameter.setParameterValue(String.valueOf(reconventionParameter.getValue())); listParameters.add(parameter); } return parameters; } /** * Get de cash flows of product * * @param pricingEnv the pricing enviroment * @param product the product * @return the CashFlows of product */ com.calypso.tk.upload.jaxb.CashFlows getCashflows(final PricingEnv pricingEnv, final com.calypso.tk.core.Product product) { com.calypso.tk.upload.jaxb.CashFlows cashflows = new com.calypso.tk.upload.jaxb.CashFlows(); List<com.calypso.tk.upload.jaxb.Cashflow> cfList = cashflows.getCashFlow(); CashFlowSet cfSet = null; if (product != null) { if (product.getCustomFlowsB()) { cfSet = product.getFlows(); } else { try { if ((pricingEnv != null) && (JDate.getNow() != null)) { cfSet = product.generateFlows(JDate.getNow()); product.calculateAll(cfSet, pricingEnv, JDate.getNow()); } } catch (FlowGenerationException e) { Log.error(this, e.getMessage(), e); } } } if (cfSet != null) { Iterator<CashFlow> iterator = cfSet.iterator(); while (iterator.hasNext()) { CashFlow cashflow = iterator.next(); com.calypso.tk.upload.jaxb.Cashflow jaxbCashflow = new com.calypso.tk.upload.jaxb.Cashflow(); jaxbCashflow.setAmount(cashflow.getAmount()); jaxbCashflow.setDiscountFactor(cashflow.getDf()); jaxbCashflow.setDate(getXmlGregorianCalendarFromDate(cashflow.getDate())); jaxbCashflow.setEndDate(getXmlGregorianCalendarFromDate(cashflow.getEndDate())); jaxbCashflow.setStartDate(getXmlGregorianCalendarFromDate(cashflow.getStartDate())); jaxbCashflow.setRoundingMethod(getRoundingMethod(cashflow.getRoundingMethod())); jaxbCashflow.setFlowType(cashflow.getType()); cfList.add(jaxbCashflow); } } return cashflows; } /** * Get the direction of trade * * @param quantity the quantity * @return buy if quantity is higher and sell if is smaller. */ String getBuySell(final double quantity) { if (quantity > 0) { return "BUY"; } else { return "SELL"; } } /** * @param book the book * @return the String with Book name. */ String getBook(final com.calypso.tk.core.Book book) { if (book != null) { return book.getName(); } return null; } /** * @param tradeBundle the TradeBundle * @return the String with TradeBundle name. */ String getTradeBundle(final TradeBundle tradeBundle) { if (tradeBundle != null) { return tradeBundle.getName(); } return null; } /** * @param tradeBundle the TradeBundle * @return the String with TradeBundle type. */ String getTradeBundleType(final TradeBundle tradeBundle) { if (tradeBundle != null) { return tradeBundle.getType(); } return null; } /** * @param tradeBundle the TradeBundle * @return the boolean value of TradeBundle OneMessage. */ boolean getTradeBundleOneMessage(final TradeBundle tradeBundle) { if (tradeBundle != null) { return tradeBundle.getOneMessage(); } return false; } /** * @param legalEntity the LegalEntity * @return the String with LegalEntity code */ String getCounterParty(final com.calypso.tk.core.LegalEntity legalEntity) { if (legalEntity != null) { return legalEntity.getCode(); } return null; } /** * @param reoundingMethod the rounding method * @return the String with rounding method name. */ String getRoundingMethod(final com.calypso.tk.core.RoundingMethod reoundingMethod) { if (reoundingMethod != null) { return reoundingMethod.toString(); } return null; } /** * @param reconventionType the reconvention type * @return the string with reconvention type name */ String getReconventionType(final com.calypso.tk.product.reconvention.ReconventionType reconventionType) { if (reconventionType != null) { return reconventionType.toString(); } return null; } /** * @param product the product * @return the HolidayCode with holiday data. */ HolidayCode getHolidayCode(final com.calypso.tk.core.Product product) { if (product.getRateIndex() != null) { @SuppressWarnings("unchecked") Vector<String> holidays = product.getHolidays(); HolidayCode holidayCode = new HolidayCode(); List<String> list = holidayCode.getHoliday(); if (!holidays.isEmpty()) { for (int i = 0; i < holidays.size(); i++) { String holiday = holidays.get(i); list.add(holiday); } return holidayCode; } } return null; } /** * Parse JDate to XMLGregorianCalendar * * @param jdate the JDate object * @return the XMLGregorianCalendar object with JDate data. */ XMLGregorianCalendar getXmlGregorianCalendarFromDate(final JDate jdate) { if (jdate != null) { GregorianCalendar calendar = new GregorianCalendar(); calendar.set(jdate.getYear(), jdate.getMonth() - 1, jdate.getDayOfMonth()); try { return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { Log.error(this, e.getMessage()); return null; } } return null; } /** * @param time the time in millis * @return the XMLGregorianCalendar object with time data. */ XMLGregorianCalendar getXmlGregorianCalendarFromTime(final int time) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(time); try { return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { Log.error(this, e.getMessage()); return null; } } /** * @param time the Time in format int. * @return the time in millis */ int twentyFourHourTimeToMilliseconds(final int time) { return (((time / HUNDRED) * SIXTY) + (time % HUNDRED)) * SIXTY_THOUSAND; } }
XMLGenerator/src/main/java/calypsox/tk/bo/xml/AbstractCDUFTradeBuilder.java
package calypsox.tk.bo.xml; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import com.calypso.tk.core.CashFlow; import com.calypso.tk.core.CashFlowSet; import com.calypso.tk.core.FlowGenerationException; import com.calypso.tk.core.JDate; import com.calypso.tk.core.Log; import com.calypso.tk.core.Trade; import com.calypso.tk.core.TradeBundle; import com.calypso.tk.marketdata.PricingEnv; import com.calypso.tk.upload.jaxb.CalypsoTrade; import com.calypso.tk.upload.jaxb.HolidayCode; import com.calypso.tk.upload.jaxb.Keyword; public abstract class AbstractCDUFTradeBuilder implements CDUFTradeBuilder { /** * Variable for twentyFourHourTimeToMilliseconds method */ private static final int HUNDRED = 100; /** * Variable for twentyFourHourTimeToMilliseconds method */ private static final int SIXTY = 60; /** * Variable for twentyFourHourTimeToMilliseconds method */ private static final int SIXTY_THOUSAND = 60000; /** * Fill some data header that are general to all trades. * * @param trade the trade * @param calypsoTrade the method modifies the calypsoTrade to add the trade data */ @Override public void fillTradeHeader(final PricingEnv pricingEnv, final Trade trade, final CalypsoTrade calypsoTrade) { calypsoTrade.setAction(getAction(trade.getAction())); // required calypsoTrade.setBuySell(getBuySell(trade.getQuantity())); // required calypsoTrade.setComment(trade.getComment()); // required calypsoTrade.setCounterPartyRole(trade.getRole()); // required calypsoTrade.setExternalReference(trade.getExternalReference()); // required calypsoTrade.setInternalReference(trade.getInternalReference()); // required // The cash settle info is a particular property of some products like swaps, then it should not be here but in the irs // generator. It is possible to call the super.fillTradeHeader() and then fill the gaps for the particular product. // calypsoTrade.setCashSettlementInfo() // Trade Notional and StartDate information is from product data, then now it is in the FRA and IRS fillTradeHeader // method. // calypsoTrade.setTradeNotional(); // calypsoTrade.setStartDate(trade.get); //required calypsoTrade.setSalesPerson(trade.getSalesPerson()); // required calypsoTrade.setTradeBook(getBook(trade.getBook())); // required calypsoTrade.setTradeCounterParty(getCounterParty(trade.getCounterParty())); // required calypsoTrade.setTradeCurrency(trade.getTradeCurrency()); // required calypsoTrade.setTradeDateTime(getXmlGregorianCalendarFromDate(getTradeDateJDate(trade.getTradeDate()))); // required calypsoTrade.setTradeSettleDate(getXmlGregorianCalendarFromDate(trade.getSettleDate())); // required calypsoTrade.setTraderName(trade.getTraderName()); // required calypsoTrade.setHolidayCode(getHolidayCode(trade.getProduct())); // required calypsoTrade.setTradeBundleName(getTradeBundle(trade.getBundle())); // required calypsoTrade.setTradeBundleType(getTradeBundleType(trade.getBundle())); // required calypsoTrade.setTradeBundleOneMsg(getTradeBundleOneMessage(trade.getBundle())); calypsoTrade.setMarketType(trade.getMarketType()); calypsoTrade.setMaturityDate(getXmlGregorianCalendarFromDate(trade.getMaturityDate())); calypsoTrade.setMirrorBook(getBook(trade.getMirrorBook())); calypsoTrade.setNegotiatedCurrency(trade.getNegotiatedCurrency()); calypsoTrade.setMarketPlace(getCounterPartyCountry(trade.getCounterParty())); calypsoTrade.setProductSubType(trade.getProductSubType()); // required //nillable calypsoTrade.setTradeId(Integer.valueOf(trade.getId())); // required //nillable calypsoTrade.setTradeKeywords(getTradeKeywords(trade)); calypsoTrade.setReconventionList(getReconventionList(trade.getProduct())); // TODO: calypsoTrade.setTemplateName(); //required // TODO: calypsoTrade.setAllegeActionB(); // TODO: calypsoTrade.setCancelAction(); // TODO: calypsoTrade.setNovation(); // TODO: calypsoTrade.setReprice(); // TODO: calypsoTrade.setReRate(); // TODO: calypsoTrade.setRollDetails(); // TODO: calypsoTrade.setTermination(); // TODO: calypsoTrade.setExercise(); // TODO: calypsoTrade.setFeeReRate(); // TODO: calypsoTrade.setInterestCleanup(); // TODO: calypsoTrade.setTradeEventsInSameBundle(); } /** * @param legalEntity the legal entity * @return the String with legal entity country name. */ String getCounterPartyCountry(final com.calypso.tk.core.LegalEntity legalEntity) { if (legalEntity != null) { return legalEntity.getCountry(); } return null; } /** * @param action the action object * @return the String with action name */ String getAction(final com.calypso.tk.core.Action action) { if (action != null) { return action.toString(); } return null; } /** * Get JDate from JDateTime * * @param jDateTime the JDateTime * @return the JDate Object */ JDate getTradeDateJDate(final com.calypso.tk.core.JDatetime jDateTime){ if(jDateTime!=null){ return jDateTime.getJDate(null); } return null; } /** * Get all keywords values in TradeKeywords Object. * * @param trade the trade * @return the TradeKeywords object with all keywords values. */ com.calypso.tk.upload.jaxb.TradeKeywords getTradeKeywords(final Trade trade) { com.calypso.tk.upload.jaxb.TradeKeywords keywords = new com.calypso.tk.upload.jaxb.TradeKeywords(); List<Keyword> kwList = keywords.getKeyword(); @SuppressWarnings("unchecked") Map<String, String> tradeKeywords = trade.getKeywords(); if (tradeKeywords != null) { Set<Entry<String, String>> kwSet = tradeKeywords.entrySet(); for (Entry<String, String> entry : kwSet) { Keyword keyword = new Keyword(); keyword.setKeywordName(entry.getKey()); keyword.setKeywordValue(entry.getValue()); kwList.add(keyword); } } return keywords; } /** * Fill a ReconventionList with data product. * * @param product the product * @return the ReconventionList of product */ com.calypso.tk.upload.jaxb.ReconventionList getReconventionList(final com.calypso.tk.core.Product product) { com.calypso.tk.upload.jaxb.ReconventionList reconventionList = new com.calypso.tk.upload.jaxb.ReconventionList(); List<com.calypso.tk.upload.jaxb.ReconventionDetails> listReconventionDetails = reconventionList.getReconventionDetails(); List<com.calypso.tk.product.reconvention.Reconvention> reconventions = com.calypso.tk.product.reconvention.impl.ReconventionUtil.getReconventions(product); for (com.calypso.tk.product.reconvention.Reconvention reconvention : reconventions) { com.calypso.tk.upload.jaxb.ReconventionDetails reconventionDetails = new com.calypso.tk.upload.jaxb.ReconventionDetails(); reconventionDetails.setEffectiveDate(getXmlGregorianCalendarFromDate(reconvention.getEffectiveDate())); reconventionDetails.setParameters(getReconventionParameters(reconvention)); reconventionDetails.setPreScheduledB(reconvention.getIsPrescheduled()); // TODO: reconventionDetails.setPrincipalStructure(); reconventionDetails.setReconventionDatetime(getXmlGregorianCalendarFromDate(reconvention.getReconventionDatetime().getJDate(null))); reconventionDetails.setType(getReconventionType(reconvention.getReconventionType())); listReconventionDetails.add(reconventionDetails); } return null; } /** * Fill Parameters Object with reconvention data. * * @param reconvention the reconvention * @return the Parameters Object with reconvention data. */ com.calypso.tk.upload.jaxb.Parameters getReconventionParameters(final com.calypso.tk.product.reconvention.Reconvention reconvention) { com.calypso.tk.upload.jaxb.Parameters parameters = new com.calypso.tk.upload.jaxb.Parameters(); List<com.calypso.tk.upload.jaxb.Parameter> listParameters = parameters.getParameter(); List<com.calypso.tk.product.reconvention.ReconventionParameter<?>> reconventionParameters = reconvention.getReconventionParameters(); for (com.calypso.tk.product.reconvention.ReconventionParameter<?> reconventionParameter : reconventionParameters) { com.calypso.tk.upload.jaxb.Parameter parameter = new com.calypso.tk.upload.jaxb.Parameter(); parameter.setParameterName(reconventionParameter.getName()); parameter.setParameterValue(String.valueOf(reconventionParameter.getValue())); listParameters.add(parameter); } return parameters; } /** * Get de cash flows of product * * @param pricingEnv the pricing enviroment * @param product the product * @return the CashFlows of product */ com.calypso.tk.upload.jaxb.CashFlows getCashflows(final PricingEnv pricingEnv, final com.calypso.tk.core.Product product) { com.calypso.tk.upload.jaxb.CashFlows cashflows = new com.calypso.tk.upload.jaxb.CashFlows(); List<com.calypso.tk.upload.jaxb.Cashflow> cfList = cashflows.getCashFlow(); CashFlowSet cfSet = null; if(product != null){ if (product.getCustomFlowsB()) { cfSet = product.getFlows(); } else { try { if(pricingEnv != null && JDate.getNow() != null){ cfSet = product.generateFlows(JDate.getNow()); product.calculateAll(cfSet, pricingEnv, JDate.getNow()); } } catch (FlowGenerationException e) { Log.error(this, e.getMessage(), e); } } } if (cfSet != null) { Iterator<CashFlow> iterator = cfSet.iterator(); while (iterator.hasNext()) { CashFlow cashflow = iterator.next(); com.calypso.tk.upload.jaxb.Cashflow jaxbCashflow = new com.calypso.tk.upload.jaxb.Cashflow(); jaxbCashflow.setAmount(cashflow.getAmount()); jaxbCashflow.setDiscountFactor(cashflow.getDf()); jaxbCashflow.setDate(getXmlGregorianCalendarFromDate(cashflow.getDate())); jaxbCashflow.setEndDate(getXmlGregorianCalendarFromDate(cashflow.getEndDate())); jaxbCashflow.setStartDate(getXmlGregorianCalendarFromDate(cashflow.getStartDate())); jaxbCashflow.setRoundingMethod(getRoundingMethod(cashflow.getRoundingMethod())); cfList.add(jaxbCashflow); } } return cashflows; } /** * Get the direction of trade * * @param quantity the quantity * @return buy if quantity is higher and sell if is smaller. */ String getBuySell(final double quantity) { if (quantity > 0) { return "BUY"; } else { return "SELL"; } } /** * @param book the book * @return the String with Book name. */ String getBook(final com.calypso.tk.core.Book book) { if (book != null) { return book.getName(); } return null; } /** * @param tradeBundle the TradeBundle * @return the String with TradeBundle name. */ String getTradeBundle(final TradeBundle tradeBundle) { if (tradeBundle != null) { return tradeBundle.getName(); } return null; } /** * @param tradeBundle the TradeBundle * @return the String with TradeBundle type. */ String getTradeBundleType(final TradeBundle tradeBundle) { if (tradeBundle != null) { return tradeBundle.getType(); } return null; } /** * @param tradeBundle the TradeBundle * @return the boolean value of TradeBundle OneMessage. */ boolean getTradeBundleOneMessage(final TradeBundle tradeBundle) { if (tradeBundle != null) { return tradeBundle.getOneMessage(); } return false; } /** * @param legalEntity the LegalEntity * @return the String with LegalEntity code */ String getCounterParty(final com.calypso.tk.core.LegalEntity legalEntity) { if (legalEntity != null) { return legalEntity.getCode(); } return null; } /** * @param reoundingMethod the rounding method * @return the String with rounding method name. */ String getRoundingMethod(final com.calypso.tk.core.RoundingMethod reoundingMethod) { if (reoundingMethod != null) { return reoundingMethod.toString(); } return null; } /** * @param reconventionType the reconvention type * @return the string with reconvention type name */ String getReconventionType(final com.calypso.tk.product.reconvention.ReconventionType reconventionType) { if (reconventionType != null) { return reconventionType.toString(); } return null; } /** * @param product the product * @return the HolidayCode with holiday data. */ HolidayCode getHolidayCode(final com.calypso.tk.core.Product product) { if(product.getRateIndex()!=null){ @SuppressWarnings("unchecked") Vector<String> holidays = product.getHolidays(); HolidayCode holidayCode = new HolidayCode(); List<String> list = holidayCode.getHoliday(); if (!holidays.isEmpty()) { for (int i=0; i<holidays.size(); i++) { String holiday = holidays.get(i); list.add(holiday); } return holidayCode; } } return null; } /** * Parse JDate to XMLGregorianCalendar * * @param jdate the JDate object * @return the XMLGregorianCalendar object with JDate data. */ XMLGregorianCalendar getXmlGregorianCalendarFromDate(final JDate jdate) { if (jdate != null) { GregorianCalendar calendar = new GregorianCalendar(); calendar.set(jdate.getYear(), jdate.getMonth() - 1, jdate.getDayOfMonth()); try { return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { Log.error(this, e.getMessage()); return null; } } return null; } /** * @param time the time in millis * @return the XMLGregorianCalendar object with time data. */ XMLGregorianCalendar getXmlGregorianCalendarFromTime(final int time) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(time); try { return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { Log.error(this, e.getMessage()); return null; } } /** * @param time the Time in format int. * @return the time in millis */ int twentyFourHourTimeToMilliseconds(final int time) { return (((time / HUNDRED) * SIXTY) + (time % HUNDRED)) * SIXTY_THOUSAND; } }
cashflow type
XMLGenerator/src/main/java/calypsox/tk/bo/xml/AbstractCDUFTradeBuilder.java
cashflow type
<ide><path>MLGenerator/src/main/java/calypsox/tk/bo/xml/AbstractCDUFTradeBuilder.java <ide> * Variable for twentyFourHourTimeToMilliseconds method <ide> */ <ide> private static final int SIXTY_THOUSAND = 60000; <del> <del> /** <del> * Fill some data header that are general to all trades. <del> * <del> * @param trade the trade <del> * @param calypsoTrade the method modifies the calypsoTrade to add the trade data <del> */ <del> @Override <del> public void fillTradeHeader(final PricingEnv pricingEnv, final Trade trade, final CalypsoTrade calypsoTrade) { <del> calypsoTrade.setAction(getAction(trade.getAction())); // required <del> calypsoTrade.setBuySell(getBuySell(trade.getQuantity())); // required <del> calypsoTrade.setComment(trade.getComment()); // required <del> calypsoTrade.setCounterPartyRole(trade.getRole()); // required <del> calypsoTrade.setExternalReference(trade.getExternalReference()); // required <del> calypsoTrade.setInternalReference(trade.getInternalReference()); // required <del> // The cash settle info is a particular property of some products like swaps, then it should not be here but in the irs <del> // generator. It is possible to call the super.fillTradeHeader() and then fill the gaps for the particular product. <del> // calypsoTrade.setCashSettlementInfo() <del> // Trade Notional and StartDate information is from product data, then now it is in the FRA and IRS fillTradeHeader <del> // method. <del> // calypsoTrade.setTradeNotional(); <del> // calypsoTrade.setStartDate(trade.get); //required <del> calypsoTrade.setSalesPerson(trade.getSalesPerson()); // required <del> calypsoTrade.setTradeBook(getBook(trade.getBook())); // required <del> calypsoTrade.setTradeCounterParty(getCounterParty(trade.getCounterParty())); // required <del> calypsoTrade.setTradeCurrency(trade.getTradeCurrency()); // required <del> calypsoTrade.setTradeDateTime(getXmlGregorianCalendarFromDate(getTradeDateJDate(trade.getTradeDate()))); // required <del> calypsoTrade.setTradeSettleDate(getXmlGregorianCalendarFromDate(trade.getSettleDate())); // required <del> calypsoTrade.setTraderName(trade.getTraderName()); // required <del> calypsoTrade.setHolidayCode(getHolidayCode(trade.getProduct())); // required <del> calypsoTrade.setTradeBundleName(getTradeBundle(trade.getBundle())); // required <del> calypsoTrade.setTradeBundleType(getTradeBundleType(trade.getBundle())); // required <del> calypsoTrade.setTradeBundleOneMsg(getTradeBundleOneMessage(trade.getBundle())); <del> calypsoTrade.setMarketType(trade.getMarketType()); <del> calypsoTrade.setMaturityDate(getXmlGregorianCalendarFromDate(trade.getMaturityDate())); <del> calypsoTrade.setMirrorBook(getBook(trade.getMirrorBook())); <del> calypsoTrade.setNegotiatedCurrency(trade.getNegotiatedCurrency()); <del> calypsoTrade.setMarketPlace(getCounterPartyCountry(trade.getCounterParty())); <del> <del> calypsoTrade.setProductSubType(trade.getProductSubType()); // required //nillable <del> calypsoTrade.setTradeId(Integer.valueOf(trade.getId())); // required //nillable <del> calypsoTrade.setTradeKeywords(getTradeKeywords(trade)); <del> <del> calypsoTrade.setReconventionList(getReconventionList(trade.getProduct())); <del> <del> // TODO: calypsoTrade.setTemplateName(); //required <del> // TODO: calypsoTrade.setAllegeActionB(); <del> // TODO: calypsoTrade.setCancelAction(); <del> // TODO: calypsoTrade.setNovation(); <del> // TODO: calypsoTrade.setReprice(); <del> // TODO: calypsoTrade.setReRate(); <del> // TODO: calypsoTrade.setRollDetails(); <del> // TODO: calypsoTrade.setTermination(); <del> // TODO: calypsoTrade.setExercise(); <del> // TODO: calypsoTrade.setFeeReRate(); <del> // TODO: calypsoTrade.setInterestCleanup(); <del> // TODO: calypsoTrade.setTradeEventsInSameBundle(); <del> } <del> <del> /** <del> * @param legalEntity the legal entity <del> * @return the String with legal entity country name. <del> */ <del> String getCounterPartyCountry(final com.calypso.tk.core.LegalEntity legalEntity) { <del> if (legalEntity != null) { <del> return legalEntity.getCountry(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param action the action object <del> * @return the String with action name <del> */ <del> String getAction(final com.calypso.tk.core.Action action) { <del> if (action != null) { <del> return action.toString(); <del> } <del> return null; <del> } <del> <del> /** <del> * Get JDate from JDateTime <del> * <del> * @param jDateTime the JDateTime <del> * @return the JDate Object <del> */ <del> JDate getTradeDateJDate(final com.calypso.tk.core.JDatetime jDateTime){ <del> if(jDateTime!=null){ <del> return jDateTime.getJDate(null); <del> } <del> return null; <del> } <del> <del> /** <del> * Get all keywords values in TradeKeywords Object. <del> * <del> * @param trade the trade <del> * @return the TradeKeywords object with all keywords values. <del> */ <del> com.calypso.tk.upload.jaxb.TradeKeywords getTradeKeywords(final Trade trade) { <del> com.calypso.tk.upload.jaxb.TradeKeywords keywords = new com.calypso.tk.upload.jaxb.TradeKeywords(); <del> List<Keyword> kwList = keywords.getKeyword(); <del> <del> @SuppressWarnings("unchecked") <del> Map<String, String> tradeKeywords = trade.getKeywords(); <del> if (tradeKeywords != null) { <del> Set<Entry<String, String>> kwSet = tradeKeywords.entrySet(); <del> for (Entry<String, String> entry : kwSet) { <del> Keyword keyword = new Keyword(); <del> keyword.setKeywordName(entry.getKey()); <del> keyword.setKeywordValue(entry.getValue()); <del> kwList.add(keyword); <del> } <del> } <del> return keywords; <del> } <del> <del> /** <del> * Fill a ReconventionList with data product. <del> * <del> * @param product the product <del> * @return the ReconventionList of product <del> */ <del> com.calypso.tk.upload.jaxb.ReconventionList getReconventionList(final com.calypso.tk.core.Product product) { <del> com.calypso.tk.upload.jaxb.ReconventionList reconventionList = new com.calypso.tk.upload.jaxb.ReconventionList(); <del> List<com.calypso.tk.upload.jaxb.ReconventionDetails> listReconventionDetails = reconventionList.getReconventionDetails(); <del> List<com.calypso.tk.product.reconvention.Reconvention> reconventions = com.calypso.tk.product.reconvention.impl.ReconventionUtil.getReconventions(product); <del> <del> for (com.calypso.tk.product.reconvention.Reconvention reconvention : reconventions) { <del> com.calypso.tk.upload.jaxb.ReconventionDetails reconventionDetails = new com.calypso.tk.upload.jaxb.ReconventionDetails(); <del> reconventionDetails.setEffectiveDate(getXmlGregorianCalendarFromDate(reconvention.getEffectiveDate())); <del> reconventionDetails.setParameters(getReconventionParameters(reconvention)); <del> reconventionDetails.setPreScheduledB(reconvention.getIsPrescheduled()); <del> // TODO: reconventionDetails.setPrincipalStructure(); <del> reconventionDetails.setReconventionDatetime(getXmlGregorianCalendarFromDate(reconvention.getReconventionDatetime().getJDate(null))); <del> reconventionDetails.setType(getReconventionType(reconvention.getReconventionType())); <del> listReconventionDetails.add(reconventionDetails); <del> } <del> return null; <del> } <del> <del> /** <del> * Fill Parameters Object with reconvention data. <del> * <del> * @param reconvention the reconvention <del> * @return the Parameters Object with reconvention data. <del> */ <del> com.calypso.tk.upload.jaxb.Parameters getReconventionParameters(final com.calypso.tk.product.reconvention.Reconvention reconvention) { <del> com.calypso.tk.upload.jaxb.Parameters parameters = new com.calypso.tk.upload.jaxb.Parameters(); <del> List<com.calypso.tk.upload.jaxb.Parameter> listParameters = parameters.getParameter(); <del> List<com.calypso.tk.product.reconvention.ReconventionParameter<?>> reconventionParameters = reconvention.getReconventionParameters(); <del> for (com.calypso.tk.product.reconvention.ReconventionParameter<?> reconventionParameter : reconventionParameters) { <del> com.calypso.tk.upload.jaxb.Parameter parameter = new com.calypso.tk.upload.jaxb.Parameter(); <del> parameter.setParameterName(reconventionParameter.getName()); <del> parameter.setParameterValue(String.valueOf(reconventionParameter.getValue())); <del> listParameters.add(parameter); <del> } <del> return parameters; <del> } <del> <del> /** <del> * Get de cash flows of product <del> * <del> * @param pricingEnv the pricing enviroment <del> * @param product the product <del> * @return the CashFlows of product <del> */ <del> com.calypso.tk.upload.jaxb.CashFlows getCashflows(final PricingEnv pricingEnv, final com.calypso.tk.core.Product product) { <del> com.calypso.tk.upload.jaxb.CashFlows cashflows = new com.calypso.tk.upload.jaxb.CashFlows(); <del> List<com.calypso.tk.upload.jaxb.Cashflow> cfList = cashflows.getCashFlow(); <del> <del> CashFlowSet cfSet = null; <del> if(product != null){ <del> if (product.getCustomFlowsB()) { <del> cfSet = product.getFlows(); <del> } else { <del> try { <del> if(pricingEnv != null && JDate.getNow() != null){ <del> cfSet = product.generateFlows(JDate.getNow()); <del> product.calculateAll(cfSet, pricingEnv, JDate.getNow()); <del> } <del> } catch (FlowGenerationException e) { <del> Log.error(this, e.getMessage(), e); <del> } <del> } <del> } <del> if (cfSet != null) { <del> Iterator<CashFlow> iterator = cfSet.iterator(); <del> while (iterator.hasNext()) { <del> CashFlow cashflow = iterator.next(); <del> com.calypso.tk.upload.jaxb.Cashflow jaxbCashflow = new com.calypso.tk.upload.jaxb.Cashflow(); <del> jaxbCashflow.setAmount(cashflow.getAmount()); <del> jaxbCashflow.setDiscountFactor(cashflow.getDf()); <del> jaxbCashflow.setDate(getXmlGregorianCalendarFromDate(cashflow.getDate())); <del> jaxbCashflow.setEndDate(getXmlGregorianCalendarFromDate(cashflow.getEndDate())); <del> jaxbCashflow.setStartDate(getXmlGregorianCalendarFromDate(cashflow.getStartDate())); <del> jaxbCashflow.setRoundingMethod(getRoundingMethod(cashflow.getRoundingMethod())); <del> cfList.add(jaxbCashflow); <del> } <del> } <del> return cashflows; <del> } <del> <del> /** <del> * Get the direction of trade <del> * <del> * @param quantity the quantity <del> * @return buy if quantity is higher and sell if is smaller. <del> */ <del> String getBuySell(final double quantity) { <del> if (quantity > 0) { <del> return "BUY"; <del> } else { <del> return "SELL"; <del> } <del> } <del> <del> /** <del> * @param book the book <del> * @return the String with Book name. <del> */ <del> String getBook(final com.calypso.tk.core.Book book) { <del> if (book != null) { <del> return book.getName(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param tradeBundle the TradeBundle <del> * @return the String with TradeBundle name. <del> */ <del> String getTradeBundle(final TradeBundle tradeBundle) { <del> if (tradeBundle != null) { <del> return tradeBundle.getName(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param tradeBundle the TradeBundle <del> * @return the String with TradeBundle type. <del> */ <del> String getTradeBundleType(final TradeBundle tradeBundle) { <del> if (tradeBundle != null) { <del> return tradeBundle.getType(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param tradeBundle the TradeBundle <del> * @return the boolean value of TradeBundle OneMessage. <del> */ <del> boolean getTradeBundleOneMessage(final TradeBundle tradeBundle) { <del> if (tradeBundle != null) { <del> return tradeBundle.getOneMessage(); <del> } <del> return false; <del> } <del> <del> /** <del> * @param legalEntity the LegalEntity <del> * @return the String with LegalEntity code <del> */ <del> String getCounterParty(final com.calypso.tk.core.LegalEntity legalEntity) { <del> if (legalEntity != null) { <del> return legalEntity.getCode(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param reoundingMethod the rounding method <del> * @return the String with rounding method name. <del> */ <del> String getRoundingMethod(final com.calypso.tk.core.RoundingMethod reoundingMethod) { <del> if (reoundingMethod != null) { <del> return reoundingMethod.toString(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param reconventionType the reconvention type <del> * @return the string with reconvention type name <del> */ <del> String getReconventionType(final com.calypso.tk.product.reconvention.ReconventionType reconventionType) { <del> if (reconventionType != null) { <del> return reconventionType.toString(); <del> } <del> return null; <del> } <del> <del> /** <del> * @param product the product <del> * @return the HolidayCode with holiday data. <del> */ <del> HolidayCode getHolidayCode(final com.calypso.tk.core.Product product) { <del> if(product.getRateIndex()!=null){ <del> @SuppressWarnings("unchecked") <del> Vector<String> holidays = product.getHolidays(); <del> HolidayCode holidayCode = new HolidayCode(); <del> List<String> list = holidayCode.getHoliday(); <del> if (!holidays.isEmpty()) { <del> for (int i=0; i<holidays.size(); i++) { <del> String holiday = holidays.get(i); <del> list.add(holiday); <del> } <del> return holidayCode; <del> } <del> } <del> return null; <del> } <del> <del> /** <del> * Parse JDate to XMLGregorianCalendar <del> * <del> * @param jdate the JDate object <del> * @return the XMLGregorianCalendar object with JDate data. <del> */ <del> XMLGregorianCalendar getXmlGregorianCalendarFromDate(final JDate jdate) { <del> if (jdate != null) { <del> GregorianCalendar calendar = new GregorianCalendar(); <del> calendar.set(jdate.getYear(), jdate.getMonth() - 1, jdate.getDayOfMonth()); <del> try { <del> return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); <del> } catch (DatatypeConfigurationException e) { <del> Log.error(this, e.getMessage()); <del> return null; <del> } <del> } <del> return null; <del> } <del> <del> /** <del> * @param time the time in millis <del> * @return the XMLGregorianCalendar object with time data. <del> */ <del> XMLGregorianCalendar getXmlGregorianCalendarFromTime(final int time) { <del> GregorianCalendar calendar = new GregorianCalendar(); <del> calendar.setTimeInMillis(time); <del> try { <del> return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); <del> } catch (DatatypeConfigurationException e) { <del> Log.error(this, e.getMessage()); <del> return null; <del> } <del> } <del> <del> /** <del> * @param time the Time in format int. <del> * @return the time in millis <del> */ <del> int twentyFourHourTimeToMilliseconds(final int time) { <del> return (((time / HUNDRED) * SIXTY) + (time % HUNDRED)) * SIXTY_THOUSAND; <del> } <add> <add> /** <add> * Fill some data header that are general to all trades. <add> * <add> * @param trade the trade <add> * @param calypsoTrade the method modifies the calypsoTrade to add the trade data <add> */ <add> @Override <add> public void fillTradeHeader(final PricingEnv pricingEnv, final Trade trade, final CalypsoTrade calypsoTrade) { <add> calypsoTrade.setAction(getAction(trade.getAction())); // required <add> calypsoTrade.setBuySell(getBuySell(trade.getQuantity())); // required <add> calypsoTrade.setComment(trade.getComment()); // required <add> calypsoTrade.setCounterPartyRole(trade.getRole()); // required <add> calypsoTrade.setExternalReference(trade.getExternalReference()); // required <add> calypsoTrade.setInternalReference(trade.getInternalReference()); // required <add> // The cash settle info is a particular property of some products like swaps, then it should not be here but in the irs <add> // generator. It is possible to call the super.fillTradeHeader() and then fill the gaps for the particular product. <add> // calypsoTrade.setCashSettlementInfo() <add> // Trade Notional and StartDate information is from product data, then now it is in the FRA and IRS fillTradeHeader <add> // method. <add> // calypsoTrade.setTradeNotional(); <add> // calypsoTrade.setStartDate(trade.get); //required <add> calypsoTrade.setSalesPerson(trade.getSalesPerson()); // required <add> calypsoTrade.setTradeBook(getBook(trade.getBook())); // required <add> calypsoTrade.setTradeCounterParty(getCounterParty(trade.getCounterParty())); // required <add> calypsoTrade.setTradeCurrency(trade.getTradeCurrency()); // required <add> calypsoTrade.setTradeDateTime(getXmlGregorianCalendarFromDate(getTradeDateJDate(trade.getTradeDate()))); // required <add> calypsoTrade.setTradeSettleDate(getXmlGregorianCalendarFromDate(trade.getSettleDate())); // required <add> calypsoTrade.setTraderName(trade.getTraderName()); // required <add> calypsoTrade.setHolidayCode(getHolidayCode(trade.getProduct())); // required <add> calypsoTrade.setTradeBundleName(getTradeBundle(trade.getBundle())); // required <add> calypsoTrade.setTradeBundleType(getTradeBundleType(trade.getBundle())); // required <add> calypsoTrade.setTradeBundleOneMsg(getTradeBundleOneMessage(trade.getBundle())); <add> calypsoTrade.setMarketType(trade.getMarketType()); <add> calypsoTrade.setMaturityDate(getXmlGregorianCalendarFromDate(trade.getMaturityDate())); <add> calypsoTrade.setMirrorBook(getBook(trade.getMirrorBook())); <add> calypsoTrade.setNegotiatedCurrency(trade.getNegotiatedCurrency()); <add> calypsoTrade.setMarketPlace(getCounterPartyCountry(trade.getCounterParty())); <add> <add> calypsoTrade.setProductSubType(trade.getProductSubType()); // required //nillable <add> calypsoTrade.setTradeId(Integer.valueOf(trade.getId())); // required //nillable <add> calypsoTrade.setTradeKeywords(getTradeKeywords(trade)); <add> <add> calypsoTrade.setReconventionList(getReconventionList(trade.getProduct())); <add> <add> // TODO: calypsoTrade.setTemplateName(); //required <add> // TODO: calypsoTrade.setAllegeActionB(); <add> // TODO: calypsoTrade.setCancelAction(); <add> // TODO: calypsoTrade.setNovation(); <add> // TODO: calypsoTrade.setReprice(); <add> // TODO: calypsoTrade.setReRate(); <add> // TODO: calypsoTrade.setRollDetails(); <add> // TODO: calypsoTrade.setTermination(); <add> // TODO: calypsoTrade.setExercise(); <add> // TODO: calypsoTrade.setFeeReRate(); <add> // TODO: calypsoTrade.setInterestCleanup(); <add> // TODO: calypsoTrade.setTradeEventsInSameBundle(); <add> } <add> <add> /** <add> * @param legalEntity the legal entity <add> * @return the String with legal entity country name. <add> */ <add> String getCounterPartyCountry(final com.calypso.tk.core.LegalEntity legalEntity) { <add> if (legalEntity != null) { <add> return legalEntity.getCountry(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param action the action object <add> * @return the String with action name <add> */ <add> String getAction(final com.calypso.tk.core.Action action) { <add> if (action != null) { <add> return action.toString(); <add> } <add> return null; <add> } <add> <add> /** <add> * Get JDate from JDateTime <add> * <add> * @param jDateTime the JDateTime <add> * @return the JDate Object <add> */ <add> JDate getTradeDateJDate(final com.calypso.tk.core.JDatetime jDateTime) { <add> if (jDateTime != null) { <add> return jDateTime.getJDate(null); <add> } <add> return null; <add> } <add> <add> /** <add> * Get all keywords values in TradeKeywords Object. <add> * <add> * @param trade the trade <add> * @return the TradeKeywords object with all keywords values. <add> */ <add> com.calypso.tk.upload.jaxb.TradeKeywords getTradeKeywords(final Trade trade) { <add> com.calypso.tk.upload.jaxb.TradeKeywords keywords = new com.calypso.tk.upload.jaxb.TradeKeywords(); <add> List<Keyword> kwList = keywords.getKeyword(); <add> <add> @SuppressWarnings("unchecked") <add> Map<String, String> tradeKeywords = trade.getKeywords(); <add> if (tradeKeywords != null) { <add> Set<Entry<String, String>> kwSet = tradeKeywords.entrySet(); <add> for (Entry<String, String> entry : kwSet) { <add> Keyword keyword = new Keyword(); <add> keyword.setKeywordName(entry.getKey()); <add> keyword.setKeywordValue(entry.getValue()); <add> kwList.add(keyword); <add> } <add> } <add> return keywords; <add> } <add> <add> /** <add> * Fill a ReconventionList with data product. <add> * <add> * @param product the product <add> * @return the ReconventionList of product <add> */ <add> com.calypso.tk.upload.jaxb.ReconventionList getReconventionList(final com.calypso.tk.core.Product product) { <add> com.calypso.tk.upload.jaxb.ReconventionList reconventionList = new com.calypso.tk.upload.jaxb.ReconventionList(); <add> List<com.calypso.tk.upload.jaxb.ReconventionDetails> listReconventionDetails = reconventionList.getReconventionDetails(); <add> List<com.calypso.tk.product.reconvention.Reconvention> reconventions = com.calypso.tk.product.reconvention.impl.ReconventionUtil.getReconventions(product); <add> <add> for (com.calypso.tk.product.reconvention.Reconvention reconvention : reconventions) { <add> com.calypso.tk.upload.jaxb.ReconventionDetails reconventionDetails = new com.calypso.tk.upload.jaxb.ReconventionDetails(); <add> reconventionDetails.setEffectiveDate(getXmlGregorianCalendarFromDate(reconvention.getEffectiveDate())); <add> reconventionDetails.setParameters(getReconventionParameters(reconvention)); <add> reconventionDetails.setPreScheduledB(reconvention.getIsPrescheduled()); <add> // TODO: reconventionDetails.setPrincipalStructure(); <add> reconventionDetails.setReconventionDatetime(getXmlGregorianCalendarFromDate(reconvention.getReconventionDatetime().getJDate(null))); <add> reconventionDetails.setType(getReconventionType(reconvention.getReconventionType())); <add> listReconventionDetails.add(reconventionDetails); <add> } <add> return null; <add> } <add> <add> /** <add> * Fill Parameters Object with reconvention data. <add> * <add> * @param reconvention the reconvention <add> * @return the Parameters Object with reconvention data. <add> */ <add> com.calypso.tk.upload.jaxb.Parameters getReconventionParameters(final com.calypso.tk.product.reconvention.Reconvention reconvention) { <add> com.calypso.tk.upload.jaxb.Parameters parameters = new com.calypso.tk.upload.jaxb.Parameters(); <add> List<com.calypso.tk.upload.jaxb.Parameter> listParameters = parameters.getParameter(); <add> List<com.calypso.tk.product.reconvention.ReconventionParameter<?>> reconventionParameters = reconvention.getReconventionParameters(); <add> for (com.calypso.tk.product.reconvention.ReconventionParameter<?> reconventionParameter : reconventionParameters) { <add> com.calypso.tk.upload.jaxb.Parameter parameter = new com.calypso.tk.upload.jaxb.Parameter(); <add> parameter.setParameterName(reconventionParameter.getName()); <add> parameter.setParameterValue(String.valueOf(reconventionParameter.getValue())); <add> listParameters.add(parameter); <add> } <add> return parameters; <add> } <add> <add> /** <add> * Get de cash flows of product <add> * <add> * @param pricingEnv the pricing enviroment <add> * @param product the product <add> * @return the CashFlows of product <add> */ <add> com.calypso.tk.upload.jaxb.CashFlows getCashflows(final PricingEnv pricingEnv, final com.calypso.tk.core.Product product) { <add> com.calypso.tk.upload.jaxb.CashFlows cashflows = new com.calypso.tk.upload.jaxb.CashFlows(); <add> List<com.calypso.tk.upload.jaxb.Cashflow> cfList = cashflows.getCashFlow(); <add> <add> CashFlowSet cfSet = null; <add> if (product != null) { <add> if (product.getCustomFlowsB()) { <add> cfSet = product.getFlows(); <add> } else { <add> try { <add> if ((pricingEnv != null) && (JDate.getNow() != null)) { <add> cfSet = product.generateFlows(JDate.getNow()); <add> product.calculateAll(cfSet, pricingEnv, JDate.getNow()); <add> } <add> } catch (FlowGenerationException e) { <add> Log.error(this, e.getMessage(), e); <add> } <add> } <add> } <add> if (cfSet != null) { <add> Iterator<CashFlow> iterator = cfSet.iterator(); <add> while (iterator.hasNext()) { <add> CashFlow cashflow = iterator.next(); <add> com.calypso.tk.upload.jaxb.Cashflow jaxbCashflow = new com.calypso.tk.upload.jaxb.Cashflow(); <add> jaxbCashflow.setAmount(cashflow.getAmount()); <add> jaxbCashflow.setDiscountFactor(cashflow.getDf()); <add> jaxbCashflow.setDate(getXmlGregorianCalendarFromDate(cashflow.getDate())); <add> jaxbCashflow.setEndDate(getXmlGregorianCalendarFromDate(cashflow.getEndDate())); <add> jaxbCashflow.setStartDate(getXmlGregorianCalendarFromDate(cashflow.getStartDate())); <add> jaxbCashflow.setRoundingMethod(getRoundingMethod(cashflow.getRoundingMethod())); <add> jaxbCashflow.setFlowType(cashflow.getType()); <add> cfList.add(jaxbCashflow); <add> } <add> } <add> return cashflows; <add> } <add> <add> /** <add> * Get the direction of trade <add> * <add> * @param quantity the quantity <add> * @return buy if quantity is higher and sell if is smaller. <add> */ <add> String getBuySell(final double quantity) { <add> if (quantity > 0) { <add> return "BUY"; <add> } else { <add> return "SELL"; <add> } <add> } <add> <add> /** <add> * @param book the book <add> * @return the String with Book name. <add> */ <add> String getBook(final com.calypso.tk.core.Book book) { <add> if (book != null) { <add> return book.getName(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param tradeBundle the TradeBundle <add> * @return the String with TradeBundle name. <add> */ <add> String getTradeBundle(final TradeBundle tradeBundle) { <add> if (tradeBundle != null) { <add> return tradeBundle.getName(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param tradeBundle the TradeBundle <add> * @return the String with TradeBundle type. <add> */ <add> String getTradeBundleType(final TradeBundle tradeBundle) { <add> if (tradeBundle != null) { <add> return tradeBundle.getType(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param tradeBundle the TradeBundle <add> * @return the boolean value of TradeBundle OneMessage. <add> */ <add> boolean getTradeBundleOneMessage(final TradeBundle tradeBundle) { <add> if (tradeBundle != null) { <add> return tradeBundle.getOneMessage(); <add> } <add> return false; <add> } <add> <add> /** <add> * @param legalEntity the LegalEntity <add> * @return the String with LegalEntity code <add> */ <add> String getCounterParty(final com.calypso.tk.core.LegalEntity legalEntity) { <add> if (legalEntity != null) { <add> return legalEntity.getCode(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param reoundingMethod the rounding method <add> * @return the String with rounding method name. <add> */ <add> String getRoundingMethod(final com.calypso.tk.core.RoundingMethod reoundingMethod) { <add> if (reoundingMethod != null) { <add> return reoundingMethod.toString(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param reconventionType the reconvention type <add> * @return the string with reconvention type name <add> */ <add> String getReconventionType(final com.calypso.tk.product.reconvention.ReconventionType reconventionType) { <add> if (reconventionType != null) { <add> return reconventionType.toString(); <add> } <add> return null; <add> } <add> <add> /** <add> * @param product the product <add> * @return the HolidayCode with holiday data. <add> */ <add> HolidayCode getHolidayCode(final com.calypso.tk.core.Product product) { <add> if (product.getRateIndex() != null) { <add> @SuppressWarnings("unchecked") <add> Vector<String> holidays = product.getHolidays(); <add> HolidayCode holidayCode = new HolidayCode(); <add> List<String> list = holidayCode.getHoliday(); <add> if (!holidays.isEmpty()) { <add> for (int i = 0; i < holidays.size(); i++) { <add> String holiday = holidays.get(i); <add> list.add(holiday); <add> } <add> return holidayCode; <add> } <add> } <add> return null; <add> } <add> <add> /** <add> * Parse JDate to XMLGregorianCalendar <add> * <add> * @param jdate the JDate object <add> * @return the XMLGregorianCalendar object with JDate data. <add> */ <add> XMLGregorianCalendar getXmlGregorianCalendarFromDate(final JDate jdate) { <add> if (jdate != null) { <add> GregorianCalendar calendar = new GregorianCalendar(); <add> calendar.set(jdate.getYear(), jdate.getMonth() - 1, jdate.getDayOfMonth()); <add> try { <add> return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); <add> } catch (DatatypeConfigurationException e) { <add> Log.error(this, e.getMessage()); <add> return null; <add> } <add> } <add> return null; <add> } <add> <add> /** <add> * @param time the time in millis <add> * @return the XMLGregorianCalendar object with time data. <add> */ <add> XMLGregorianCalendar getXmlGregorianCalendarFromTime(final int time) { <add> GregorianCalendar calendar = new GregorianCalendar(); <add> calendar.setTimeInMillis(time); <add> try { <add> return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); <add> } catch (DatatypeConfigurationException e) { <add> Log.error(this, e.getMessage()); <add> return null; <add> } <add> } <add> <add> /** <add> * @param time the Time in format int. <add> * @return the time in millis <add> */ <add> int twentyFourHourTimeToMilliseconds(final int time) { <add> return (((time / HUNDRED) * SIXTY) + (time % HUNDRED)) * SIXTY_THOUSAND; <add> } <ide> <ide> }
Java
apache-2.0
d498d7d51ee53e7d2323adb5db7f956278e7165a
0
eFaps/eFaps-Kernel-Install,eFaps/eFaps-Kernel-Install
/* * Copyright 2003 - 2010 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.admin.common.message; import java.util.HashMap; import java.util.Map; import org.efaps.admin.datamodel.Status; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.EventExecution; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Return; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.admin.program.esjp.EFapsRevision; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.db.Context; import org.efaps.db.Insert; import org.efaps.db.Instance; import org.efaps.db.InstanceQuery; import org.efaps.db.QueryBuilder; import org.efaps.util.EFapsException; /** * TODO comment! * * @author The eFaps Team * @version $Id$ */ @EFapsUUID("6e4c3e39-5a28-4c5e-9485-f4a0028827db") @EFapsRevision("$Rev$") public class SystemMessage implements EventExecution { /** * Method for create a new connection of user's. * @param _parameter Parameter as passed from the eFaps API. * @return new empty Return. * @throws EFapsException on error. */ public Return execute(final Parameter _parameter) throws EFapsException { final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES); final Instance parent = (Instance) _parameter.get(ParameterValues.INSTANCE); final Map<?, ?> others = (HashMap<?, ?>) _parameter.get(ParameterValues.OTHERS); final String[] childOids = (String[]) others.get("selectedRow"); if (childOids != null) { final String type = (String) properties.get("ConnectType"); final String childAttr = (String) properties.get("ConnectChildAttribute"); final String parentAttr = (String) properties.get("ConnectParentAttribute"); for (final String childOid : childOids) { final Instance child = Instance.get(childOid); final Insert insert = new Insert(type); insert.add(parentAttr, "" + parent.getId()); insert.add(childAttr, "" + child.getId()); insert.add("StatusAbstract", Status.find("Admin_Common_SystemMessageStatus", "Unread").getId()); insert.execute(); } } return new Return(); } /** * Method for show alerts message of any user in case existing. * @param _parameter Parameter as passed from the eFaps API. * @return ret Return. * @throws EFapsException on error. */ public Return showAlertMessage(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES); final String types = (String) properties.get("Types"); final QueryBuilder queryBldr = new QueryBuilder(Type.get(types)); queryBldr.addWhereAttrEqValue("UserLink", Context.getThreadContext().getPerson().getId()); final InstanceQuery query = queryBldr.getQuery(); query.execute(); ret.put(ReturnValues.VALUES, query.getInstances()); return ret; } }
src/main/efaps/ESJP/org/efaps/esjp/admin/common/message/SystemMessage.java
/* * Copyright 2003 - 2010 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.admin.common.message; import java.util.HashMap; import java.util.Map; import org.efaps.admin.datamodel.Status; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.EventExecution; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Return; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.event.Return.ReturnValues; import org.efaps.admin.program.esjp.EFapsRevision; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.db.Context; import org.efaps.db.Insert; import org.efaps.db.Instance; import org.efaps.db.InstanceQuery; import org.efaps.db.QueryBuilder; import org.efaps.util.EFapsException; /** * TODO comment! * * @author The eFaps Team * @version $Id$ */ @EFapsUUID("6e4c3e39-5a28-4c5e-9485-f4a0028827db") @EFapsRevision("$Rev$") public class SystemMessage implements EventExecution { /** * Method used to set the value for the NumberGenerator. * @param _parameter Parameter as passed from the eFaps API. * @return new empty Return * @throws EFapsException */ public Return execute(final Parameter _parameter) throws EFapsException { final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES); final Instance parent = (Instance) _parameter.get(ParameterValues.INSTANCE); final Map<?, ?> others = (HashMap<?, ?>) _parameter.get(ParameterValues.OTHERS); final String[] childOids = (String[]) others.get("selectedRow"); if (childOids != null) { final String type = (String) properties.get("ConnectType"); final String childAttr = (String) properties.get("ConnectChildAttribute"); final String parentAttr = (String) properties.get("ConnectParentAttribute"); for (final String childOid : childOids) { final Instance child = Instance.get(childOid); final Insert insert = new Insert(type); insert.add(parentAttr, "" + parent.getId()); insert.add(childAttr, "" + child.getId()); insert.add("StatusAbstract", Status.find("Admin_Common_SystemMessageStatus", "Unread").getId()); insert.execute(); } } return new Return(); } public Return showAlertMessage(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES); final String types = (String) properties.get("Types"); final QueryBuilder queryBldr = new QueryBuilder(Type.get(types)); queryBldr.addWhereAttrEqValue("UserLink", Context.getThreadContext().getPerson().getId()); final InstanceQuery query = queryBldr.getQuery(); query.execute(); ret.put(ReturnValues.VALUES, query.getInstances()); return ret; } }
- adding comments for methods. git-svn-id: 4afd028e37a0ecb7b60cc6a38eb25d9930f4ee19@4540 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
src/main/efaps/ESJP/org/efaps/esjp/admin/common/message/SystemMessage.java
- adding comments for methods.
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/admin/common/message/SystemMessage.java <ide> public class SystemMessage implements EventExecution <ide> { <ide> /** <del> * Method used to set the value for the NumberGenerator. <add> * Method for create a new connection of user's. <ide> * @param _parameter Parameter as passed from the eFaps API. <del> * @return new empty Return <del> * @throws EFapsException <add> * @return new empty Return. <add> * @throws EFapsException on error. <ide> */ <ide> public Return execute(final Parameter _parameter) <ide> throws EFapsException <ide> return new Return(); <ide> } <ide> <add> /** <add> * Method for show alerts message of any user in case existing. <add> * @param _parameter Parameter as passed from the eFaps API. <add> * @return ret Return. <add> * @throws EFapsException on error. <add> */ <ide> public Return showAlertMessage(final Parameter _parameter) <ide> throws EFapsException <ide> {
JavaScript
mit
b4e55a84c6ae7761aa7af7da2b02e57657f01a74
0
cloudfour/core-hbs-helpers
'use strict'; var timestamp = require('../').timestamp; var tape = require('tape'); var Handlebars = require('handlebars'); var moment = require('moment'); Handlebars.registerHelper(timestamp.name, timestamp); tape('timestamp', function (test) { var template; var actual; var expected; var today = new Date(); test.plan(7); template = Handlebars.compile('{{timestamp}}'); test.ok(moment(template()).isValid(), 'Works'); template = Handlebars.compile('{{timestamp format="YYYY"}}'); expected = today.getFullYear().toString(); actual = template(); test.equal(actual, expected, 'Works with a specified format'); template = Handlebars.compile('{{timestamp date format="MMM Do YY"}}'); expected = 'Aug 9th 95'; actual = template({ date: new Date('Aug 9, 1995') }); test.equal(actual, expected, 'Works with Date input'); template = Handlebars.compile('{{timestamp date format="MMM Do, YYYY"}}'); expected = 'Oct 21st, 2015'; actual = template({ date: '2015-10-21' }); test.equal(actual, expected, 'Works with string input'); template = Handlebars.compile('{{timestamp date inputFormat="MMM DD YY" format="YYYY-MM-DD"}}'); expected = '2015-10-21'; actual = template({ date: 'Oct 21 15' }); test.equal(actual, expected, 'Works with custom input format'); template = Handlebars.compile('{{timestamp format="ZZ" utc=false}}'); expected = (function (date) { var offset = today.getTimezoneOffset() / 0.6; var result = ''; if (offset > 0) { result += '-'; if (offset.toString().length < 4) { result += '0'; } result += offset; } return result; })(today); actual = template(); test.equal(actual, expected, 'Maintains timezone offset in non-UTC mode'); template = Handlebars.compile('{{timestamp date}}'); test.throws( function () { template({ date: 'abc123' }); }, /valid Date-like value\.$/, 'Errors when passed an invalid date value' ); });
test/timestamp.spec.js
'use strict'; var timestamp = require('../').timestamp; var tape = require('tape'); var Handlebars = require('handlebars'); Handlebars.registerHelper(timestamp.name, timestamp); tape('timestamp', function (test) { var template; var actual; var expected; var iso8601 = /(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})[+-](\d{2})\:(\d{2})/; var today = new Date(); test.plan(7); template = Handlebars.compile('{{timestamp}}'); test.ok(template().match(iso8601).length > 0, 'Works'); template = Handlebars.compile('{{timestamp format="YYYY"}}'); expected = today.getFullYear().toString(); actual = template(); test.equal(actual, expected, 'Works with a specified format'); template = Handlebars.compile('{{timestamp date format="MMM Do YY"}}'); expected = 'Aug 9th 95'; actual = template({ date: new Date('Aug 9, 1995') }); test.equal(actual, expected, 'Works with Date input'); template = Handlebars.compile('{{timestamp date format="MMM Do, YYYY"}}'); expected = 'Oct 21st, 2015'; actual = template({ date: '2015-10-21' }); test.equal(actual, expected, 'Works with string input'); template = Handlebars.compile('{{timestamp date inputFormat="MMM DD YY" format="YYYY-MM-DD"}}'); expected = '2015-10-21'; actual = template({ date: 'Oct 21 15' }); test.equal(actual, expected, 'Works with custom input format'); template = Handlebars.compile('{{timestamp format="ZZ" utc=false}}'); expected = (function (date) { var offset = today.getTimezoneOffset() / 0.6; var result = ''; if (offset > 0) { result += '-'; if (offset.toString().length < 4) { result += '0'; } result += offset; } return result; })(today); actual = template(); test.equal(actual, expected, 'Maintains timezone offset in non-UTC mode'); template = Handlebars.compile('{{timestamp date}}'); test.throws( function () { template({ date: 'abc123' }); }, /valid Date-like value\.$/, 'Errors when passed an invalid date value' ); });
Fix test to use moment.isValid instead
test/timestamp.spec.js
Fix test to use moment.isValid instead
<ide><path>est/timestamp.spec.js <ide> var timestamp = require('../').timestamp; <ide> var tape = require('tape'); <ide> var Handlebars = require('handlebars'); <add>var moment = require('moment'); <ide> <ide> Handlebars.registerHelper(timestamp.name, timestamp); <ide> <ide> var template; <ide> var actual; <ide> var expected; <del> var iso8601 = /(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})[+-](\d{2})\:(\d{2})/; <ide> var today = new Date(); <ide> <ide> test.plan(7); <ide> <ide> template = Handlebars.compile('{{timestamp}}'); <del> test.ok(template().match(iso8601).length > 0, 'Works'); <add> test.ok(moment(template()).isValid(), 'Works'); <ide> <ide> template = Handlebars.compile('{{timestamp format="YYYY"}}'); <ide> expected = today.getFullYear().toString();
Java
agpl-3.0
31b6c24c995f32c5a7ff5d74ad8cbfa034546229
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
89682658-2e61-11e5-9284-b827eb9e62be
hello.java
8962b006-2e61-11e5-9284-b827eb9e62be
89682658-2e61-11e5-9284-b827eb9e62be
hello.java
89682658-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>8962b006-2e61-11e5-9284-b827eb9e62be <add>89682658-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
f8de5941abeb83a49699cc8365d0ecc6161dcfdf
0
MetSystem/jbpm-designer,jomarko/jbpm-designer,jhrcek/jbpm-designer,Hasys/jbpm-designer,MetSystem/jbpm-designer,droolsjbpm/jbpm-designer,tsurdilo/jbpm-designer,manstis/jbpm-designer,porcelli-forks/jbpm-designer,xingguang2013/jbpm-designer,porcelli-forks/jbpm-designer,Hasys/jbpm-designer,xingguang2013/jbpm-designer,manstis/jbpm-designer,droolsjbpm/jbpm-designer,jomarko/jbpm-designer,Hasys/jbpm-designer,manstis/jbpm-designer,jomarko/jbpm-designer,jhrcek/jbpm-designer,tsurdilo/jbpm-designer,droolsjbpm/jbpm-designer,droolsjbpm/jbpm-designer,porcelli-forks/jbpm-designer,jhrcek/jbpm-designer,tsurdilo/jbpm-designer,jhrcek/jbpm-designer,xingguang2013/jbpm-designer,porcelli-forks/jbpm-designer,jomarko/jbpm-designer,MetSystem/jbpm-designer,xingguang2013/jbpm-designer,manstis/jbpm-designer,tsurdilo/jbpm-designer,MetSystem/jbpm-designer,Hasys/jbpm-designer
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.designer.bpmn2.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import bpsim.*; import bpsim.impl.BpsimPackageImpl; import org.jboss.drools.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.eclipse.bpmn2.*; import org.eclipse.bpmn2.Error; import org.eclipse.bpmn2.Process; import org.eclipse.bpmn2.di.BPMNDiagram; import org.eclipse.bpmn2.di.BPMNEdge; import org.eclipse.bpmn2.di.BPMNPlane; import org.eclipse.bpmn2.di.BPMNShape; import org.eclipse.dd.dc.Bounds; import org.eclipse.dd.dc.Point; import org.eclipse.dd.di.DiagramElement; import org.eclipse.emf.ecore.util.FeatureMap; import org.jboss.drools.impl.DroolsPackageImpl; import org.jbpm.designer.web.profile.IDiagramProfile; /** * @author Antoine Toulme * @author Surdilovic * * a marshaller to transform BPMN 2.0 elements into JSON format. * */ public class Bpmn2JsonMarshaller { public static final String defaultBgColor_Activities = "#fafad2"; public static final String defaultBgColor_Events = "#f5deb3"; public static final String defaultBgColor_StartEvents = "#9acd32"; public static final String defaultBgColor_EndEvents = "#ff6347"; public static final String defaultBgColor_DataObjects = "#C0C0C0"; public static final String defaultBgColor_CatchingEvents = "#f5deb3"; public static final String defaultBgColor_ThrowingEvents = "#8cabff"; public static final String defaultBgColor_Gateways = "#f0e68c"; public static final String defaultBgColor_Swimlanes = "#ffffff"; public static final String defaultBrColor = "#000000"; public static final String defaultBrColor_CatchingEvents = "#a0522d"; public static final String defaultBrColor_ThrowingEvents = "#008cec"; public static final String defaultBrColor_Gateways = "#a67f00"; public static final String defaultFontColor = "#000000"; public static final String defaultSequenceflowColor = "#000000"; private static final List<String> defaultTypesList = Arrays.asList("Object", "Boolean", "Float", "Integer", "List", "String"); private Map<String, DiagramElement> _diagramElements = new HashMap<String, DiagramElement>(); private Map<String,Association> _diagramAssociations = new HashMap<String, Association>(); private Scenario _simulationScenario = null; private static final Logger _logger = LoggerFactory.getLogger(Bpmn2JsonMarshaller.class); private IDiagramProfile profile; private boolean coordianteManipulation = true; public void setProfile(IDiagramProfile profile) { this.profile = profile; } public String marshall(Definitions def, String preProcessingData) throws IOException { DroolsPackageImpl.init(); BpsimPackageImpl.init(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createJsonGenerator(baos, JsonEncoding.UTF8); if(def.getRelationships() != null && def.getRelationships().size() > 0) { // current support for single relationship Relationship relationship = def.getRelationships().get(0); for(ExtensionAttributeValue extattrval : relationship.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<BPSimDataType> bpsimExtensions = (List<BPSimDataType>) extensionElements.get(BpsimPackage.Literals.DOCUMENT_ROOT__BP_SIM_DATA, true); if(bpsimExtensions != null && bpsimExtensions.size() > 0) { BPSimDataType processAnalysis = bpsimExtensions.get(0); if(processAnalysis.getScenario() != null && processAnalysis.getScenario().size() > 0) { _simulationScenario = processAnalysis.getScenario().get(0); } } } } if(preProcessingData == null || preProcessingData.length() < 1) { preProcessingData = "ReadOnlyService"; } // this is a temp way to determine if // coordinate system changes are necessary String bpmn2Exporter = def.getExporter(); String bpmn2ExporterVersion = def.getExporterVersion(); boolean haveExporter = bpmn2Exporter != null && bpmn2ExporterVersion != null; if(_simulationScenario != null && !haveExporter ) { coordianteManipulation = false; } marshallDefinitions(def, generator, preProcessingData); generator.close(); return baos.toString("UTF-8"); } private void linkSequenceFlows(List<FlowElement> flowElements) { Map<String, FlowNode> nodes = new HashMap<String, FlowNode>(); for (FlowElement flowElement: flowElements) { if (flowElement instanceof FlowNode) { nodes.put(flowElement.getId(), (FlowNode) flowElement); if (flowElement instanceof SubProcess) { linkSequenceFlows(((SubProcess) flowElement).getFlowElements()); } } } for (FlowElement flowElement: flowElements) { if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; if (sequenceFlow.getSourceRef() == null && sequenceFlow.getTargetRef() == null) { String id = sequenceFlow.getId(); try { String[] subids = id.split("-_"); String id1 = subids[0]; String id2 = "_" + subids[1]; FlowNode source = nodes.get(id1); if (source != null) { sequenceFlow.setSourceRef(source); } FlowNode target = nodes.get(id2); if (target != null) { sequenceFlow.setTargetRef(target); } } catch (Throwable t) { // Do nothing } } } } } protected void marshallDefinitions(Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException { try{ generator.writeStartObject(); generator.writeObjectField("resourceId", def.getId()); /** * "properties":{"name":"", * "documentation":"", * "auditing":"", * "monitoring":"", * "executable":"true", * "package":"com.sample", * "vardefs":"a,b,c,d", * "lanes" : "a,b,c", * "id":"", * "version":"", * "author":"", * "language":"", * "namespaces":"", * "targetnamespace":"", * "expressionlanguage":"", * "typelanguage":"", * "creationdate":"", * "modificationdate":"" * } */ Map<String, Object> props = new LinkedHashMap<String, Object>(); props.put("namespaces", ""); //props.put("targetnamespace", def.getTargetNamespace()); props.put("targetnamespace", "http://www.omg.org/bpmn20"); props.put("typelanguage", def.getTypeLanguage()); props.put("name",unescapeXML(def.getName())); props.put("id", def.getId()); props.put("expressionlanguage", def.getExpressionLanguage()); // backwards compat for BZ 1048191 if( def.getDocumentation() != null && def.getDocumentation().size() > 0 ) { props.put("documentation", def.getDocumentation().get(0).getText()); } for (RootElement rootElement : def.getRootElements()) { if (rootElement instanceof Process) { // have to wait for process node to finish properties and stencil marshalling props.put("executable", ((Process) rootElement).isIsExecutable() + ""); props.put("id", rootElement.getId()); if( rootElement.getDocumentation() != null && rootElement.getDocumentation().size() > 0 ) { props.put("documentation", rootElement.getDocumentation().get(0).getText()); } Process pr = (Process) rootElement; if(pr.getName() != null && pr.getName().length() > 0) { props.put("processn", unescapeXML(((Process) rootElement).getName())); } List<Property> processProperties = ((Process) rootElement).getProperties(); if(processProperties != null && processProperties.size() > 0) { String propVal = ""; for(int i=0; i<processProperties.size(); i++) { Property p = processProperties.get(i); propVal += p.getId(); // check the structureRef value if(p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) { propVal += ":" + p.getItemSubjectRef().getStructureRef(); } if(i != processProperties.size()-1) { propVal += ","; } } props.put("vardefs", propVal); } // packageName and version and adHoc are jbpm-specific extension attribute Iterator<FeatureMap.Entry> iter = ((Process) rootElement).getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("packageName")) { props.put("package", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("version")) { props.put("version", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("adHoc")) { props.put("adhocprocess", entry.getValue()); } } // process imports, custom description and globals extension elements String allImports = ""; if((rootElement).getExtensionValues() != null && (rootElement).getExtensionValues().size() > 0) { String importsStr = ""; String globalsStr = ""; for(ExtensionAttributeValue extattrval : rootElement.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<ImportType> importExtensions = (List<ImportType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__IMPORT, true); @SuppressWarnings("unchecked") List<GlobalType> globalExtensions = (List<GlobalType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__GLOBAL, true); List<MetaDataType> metadataExtensions = (List<MetaDataType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__META_DATA, true); for(ImportType importType : importExtensions) { importsStr += importType.getName(); importsStr += "|default,"; } for(GlobalType globalType : globalExtensions) { globalsStr += (globalType.getIdentifier() + ":" + globalType.getType()); globalsStr += ","; } for(MetaDataType metaType : metadataExtensions) { props.put("customdescription", metaType.getMetaValue()); } } allImports += importsStr; if(globalsStr.length() > 0) { if(globalsStr.endsWith(",")) { globalsStr = globalsStr.substring(0, globalsStr.length() - 1); } props.put("globals", globalsStr); } } // definitions imports (wsdl) List<org.eclipse.bpmn2.Import> wsdlImports = def.getImports(); if(wsdlImports != null) { for(org.eclipse.bpmn2.Import imp : wsdlImports) { allImports += imp.getLocation() + "|" + imp.getNamespace() + "|wsdl,"; } } if(allImports.endsWith(",")) { allImports = allImports.substring(0, allImports.length() - 1); } props.put("imports", allImports); // simulation if(_simulationScenario != null && _simulationScenario.getScenarioParameters() != null) { props.put("currency", _simulationScenario.getScenarioParameters().getBaseCurrencyUnit() == null ? "" : _simulationScenario.getScenarioParameters().getBaseCurrencyUnit()); props.put("timeunit", _simulationScenario.getScenarioParameters().getBaseTimeUnit().getName()); } marshallProperties(props, generator); marshallStencil("BPMNDiagram", generator); linkSequenceFlows(((Process) rootElement).getFlowElements()); marshallProcess((Process) rootElement, def, generator, preProcessingData); } else if (rootElement instanceof Interface) { // TODO } else if (rootElement instanceof ItemDefinition) { // TODO } else if (rootElement instanceof Resource) { // TODO } else if (rootElement instanceof Error) { // TODO } else if (rootElement instanceof Message) { // TODO } else if (rootElement instanceof Signal) { // TODO } else if (rootElement instanceof Escalation) { // TODO } else if (rootElement instanceof Collaboration) { } else { _logger.warn("Unknown root element " + rootElement + ". This element will not be parsed."); } } generator.writeObjectFieldStart("stencilset"); generator.writeObjectField("url", this.profile.getStencilSetURL()); generator.writeObjectField("namespace", this.profile.getStencilSetNamespaceURL()); generator.writeEndObject(); generator.writeArrayFieldStart("ssextensions"); generator.writeObject(this.profile.getStencilSetExtensionURL()); generator.writeEndArray(); generator.writeEndObject(); } finally { _diagramElements.clear(); } } /** protected void marshallMessage(Message message, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); generator.writeStartObject(); generator.writeObjectField("resourceId", message.getId()); properties.put("name", message.getName()); if(message.getDocumentation() != null && message.getDocumentation().size() > 0) { properties.put("documentation", message.getDocumentation().get(0).getText()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Message"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeEndArray(); generator.writeEndObject(); } **/ protected void marshallCallableElement(CallableElement callableElement, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", callableElement.getId()); if (callableElement instanceof Choreography) { marshallChoreography((Choreography) callableElement, generator); } else if (callableElement instanceof Conversation) { marshallConversation((Conversation) callableElement, generator); } else if (callableElement instanceof GlobalChoreographyTask) { marshallGlobalChoreographyTask((GlobalChoreographyTask) callableElement, generator); } else if (callableElement instanceof GlobalTask) { marshallGlobalTask((GlobalTask) callableElement, generator); } else if (callableElement instanceof Process) { marshallProcess((Process) callableElement, def, generator, ""); } else { throw new UnsupportedOperationException("TODO"); //TODO! } generator.writeEndObject(); } protected void marshallProcess(Process process, Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException { BPMNPlane plane = null; for (BPMNDiagram d: def.getDiagrams()) { if (d != null) { BPMNPlane p = d.getPlane(); if (p != null) { if (p.getBpmnElement() == process) { plane = p; break; } } } } if (plane == null) { throw new IllegalArgumentException("Could not find BPMNDI information"); } generator.writeArrayFieldStart("childShapes"); List<String> laneFlowElementsIds = new ArrayList<String>(); for(LaneSet laneSet : process.getLaneSets()) { for(Lane lane : laneSet.getLanes()) { // we only want to marshall lanes if we have the bpmndi info for them! if(findDiagramElement(plane, lane) != null) { laneFlowElementsIds.addAll( marshallLanes(lane, plane, generator, 0, 0, preProcessingData, def) ); } } } for (FlowElement flowElement: process.getFlowElements()) { if( !laneFlowElementsIds.contains(flowElement.getId()) ) { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } for (Artifact artifact: process.getArtifacts()) { marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def); } generator.writeEndArray(); } private void setCatchEventProperties(CatchEvent event, Map<String, Object> properties) { if(event.getOutputSet() != null) { List<DataOutput> dataOutputs = event.getOutputSet().getDataOutputRefs(); StringBuffer doutbuff = new StringBuffer(); for(DataOutput dout : dataOutputs) { doutbuff.append(dout.getName()); doutbuff.append(","); } if(doutbuff.length() > 0) { doutbuff.setLength(doutbuff.length() - 1); } properties.put("dataoutput", doutbuff.toString()); List<DataOutputAssociation> outputAssociations = event.getDataOutputAssociation(); StringBuffer doutassociationbuff = new StringBuffer(); for(DataOutputAssociation doa : outputAssociations) { String doaName = ((DataOutput)doa.getSourceRef().get(0)).getName(); if(doaName != null && doaName.length() > 0) { doutassociationbuff.append("[dout]" + ((DataOutput)doa.getSourceRef().get(0)).getName()); doutassociationbuff.append("->"); doutassociationbuff.append(doa.getTargetRef().getId()); doutassociationbuff.append(","); } } if(doutassociationbuff.length() > 0) { doutassociationbuff.setLength(doutassociationbuff.length() - 1); } properties.put("dataoutputassociations", doutassociationbuff.toString()); } // event definitions List<EventDefinition> eventdefs = event.getEventDefinitions(); for(EventDefinition ed : eventdefs) { if(ed instanceof TimerEventDefinition) { TimerEventDefinition ted = (TimerEventDefinition) ed; // if(ted.getTimeDate() != null) { // properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody()); // } if(ted.getTimeDuration() != null) { properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody()); } if(ted.getTimeCycle() != null) { properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody()); if(((FormalExpression) ted.getTimeCycle()).getLanguage() != null) { properties.put("timecyclelanguage", ((FormalExpression) ted.getTimeCycle()).getLanguage()); } } } else if( ed instanceof SignalEventDefinition) { if(((SignalEventDefinition) ed).getSignalRef() != null) { properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef()); } else { properties.put("signalref", ""); } } else if( ed instanceof ErrorEventDefinition) { if(((ErrorEventDefinition) ed).getErrorRef() != null && ((ErrorEventDefinition) ed).getErrorRef().getErrorCode() != null) { properties.put("errorref", ((ErrorEventDefinition) ed).getErrorRef().getErrorCode()); } else { properties.put("errorref", ""); } } else if( ed instanceof ConditionalEventDefinition ) { FormalExpression conditionalExp = (FormalExpression) ((ConditionalEventDefinition) ed).getCondition(); if(conditionalExp.getBody() != null) { properties.put("conditionexpression", conditionalExp.getBody().replaceAll("\n", "\\\\n")); } if(conditionalExp.getLanguage() != null) { String languageVal = conditionalExp.getLanguage(); if(languageVal.equals("http://www.jboss.org/drools/rule")) { properties.put("conditionlanguage", "drools"); } else if(languageVal.equals("http://www.mvel.org/2.0")) { properties.put("conditionlanguage", "mvel"); } else { // default to drools properties.put("conditionlanguage", "drools"); } } } else if( ed instanceof EscalationEventDefinition ) { if(((EscalationEventDefinition) ed).getEscalationRef() != null) { Escalation esc = ((EscalationEventDefinition) ed).getEscalationRef(); if(esc.getEscalationCode() != null && esc.getEscalationCode().length() > 0) { properties.put("escalationcode", esc.getEscalationCode()); } else { properties.put("escalationcode", ""); } } } else if( ed instanceof MessageEventDefinition) { if(((MessageEventDefinition) ed).getMessageRef() != null) { Message msg = ((MessageEventDefinition) ed).getMessageRef(); properties.put("messageref", msg.getId()); } } else if( ed instanceof CompensateEventDefinition) { if(((CompensateEventDefinition) ed).getActivityRef() != null) { Activity act = ((CompensateEventDefinition) ed).getActivityRef(); properties.put("activityref", act.getName()); } } } } private void setThrowEventProperties(ThrowEvent event, Map<String, Object> properties) { if(event.getInputSet() != null) { List<DataInput> dataInputs = event.getInputSet().getDataInputRefs(); StringBuffer dinbuff = new StringBuffer(); for(DataInput din : dataInputs) { dinbuff.append(din.getName()); dinbuff.append(","); } if(dinbuff.length() > 0) { dinbuff.setLength(dinbuff.length() - 1); } properties.put("datainput", dinbuff.toString()); StringBuilder associationBuff = new StringBuilder(); List<String> uniDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : event.getDataInputAssociation()) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } String replacer = associationValue.replaceAll(",", "##"); associationBuff.append("[din]" + rhsAssociation).append("=").append(replacer); associationBuff.append(","); } } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("datainputassociations", assignmentString); } // event definitions List<EventDefinition> eventdefs = event.getEventDefinitions(); for(EventDefinition ed : eventdefs) { if(ed instanceof TimerEventDefinition) { TimerEventDefinition ted = (TimerEventDefinition) ed; // if(ted.getTimeDate() != null) { // properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody()); // } if(ted.getTimeDuration() != null) { properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody()); } if(ted.getTimeCycle() != null) { properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody()); if(((FormalExpression) ted.getTimeCycle()).getLanguage() != null) { properties.put("timecyclelanguage", ((FormalExpression) ted.getTimeCycle()).getLanguage()); } } } else if( ed instanceof SignalEventDefinition) { if(((SignalEventDefinition) ed).getSignalRef() != null) { properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef()); } else { properties.put("signalref", ""); } } else if( ed instanceof ErrorEventDefinition) { if(((ErrorEventDefinition) ed).getErrorRef() != null && ((ErrorEventDefinition) ed).getErrorRef().getErrorCode() != null) { properties.put("errorref", ((ErrorEventDefinition) ed).getErrorRef().getErrorCode()); } else { properties.put("errorref", ""); } } else if( ed instanceof ConditionalEventDefinition ) { FormalExpression conditionalExp = (FormalExpression) ((ConditionalEventDefinition) ed).getCondition(); if(conditionalExp.getBody() != null) { properties.put("conditionexpression", conditionalExp.getBody()); } if(conditionalExp.getLanguage() != null) { String languageVal = conditionalExp.getLanguage(); if(languageVal.equals("http://www.jboss.org/drools/rule")) { properties.put("conditionlanguage", "drools"); } else if(languageVal.equals("http://www.mvel.org/2.0")) { properties.put("conditionlanguage", "mvel"); } else { // default to drools properties.put("conditionlanguage", "drools"); } } } else if( ed instanceof EscalationEventDefinition ) { if(((EscalationEventDefinition) ed).getEscalationRef() != null) { Escalation esc = ((EscalationEventDefinition) ed).getEscalationRef(); if(esc.getEscalationCode() != null && esc.getEscalationCode().length() > 0) { properties.put("escalationcode", esc.getEscalationCode()); } else { properties.put("escalationcode", ""); } } } else if( ed instanceof MessageEventDefinition) { if(((MessageEventDefinition) ed).getMessageRef() != null) { Message msg = ((MessageEventDefinition) ed).getMessageRef(); properties.put("messageref", msg.getId()); } } else if( ed instanceof CompensateEventDefinition) { if(((CompensateEventDefinition) ed).getActivityRef() != null) { Activity act = ((CompensateEventDefinition) ed).getActivityRef(); properties.put("activityref", act.getName()); } } } } private List<String> marshallLanes(Lane lane, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { Bounds bounds = ((BPMNShape) findDiagramElement(plane, lane)).getBounds(); List<String> nodeRefIds = new ArrayList<String>(); if(bounds != null) { generator.writeStartObject(); generator.writeObjectField("resourceId", lane.getId()); Map<String, Object> laneProperties = new LinkedHashMap<String, Object>(); if(lane.getName() != null) { laneProperties.put("name", unescapeXML(lane.getName())); } else { laneProperties.put("name", ""); } Iterator<FeatureMap.Entry> iter = lane.getAnyAttribute().iterator(); boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("background-color")) { laneProperties.put("bgcolor", entry.getValue()); foundBgColor = true; } if(entry.getEStructuralFeature().getName().equals("border-color")) { laneProperties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { laneProperties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { laneProperties.put("fontcolor", entry.getValue()); foundFontColor = true; } if(entry.getEStructuralFeature().getName().equals("selectable")) { laneProperties.put("isselectable", entry.getValue()); foundSelectable = true; } } if(!foundBgColor) { laneProperties.put("bgcolor", defaultBgColor_Swimlanes); } if(!foundBrColor) { laneProperties.put("bordercolor", defaultBrColor); } if(!foundFontColor) { laneProperties.put("fontcolor", defaultFontColor); } if(!foundSelectable) { laneProperties.put("isselectable", "true"); } marshallProperties(laneProperties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Lane"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); for (FlowElement flowElement: lane.getFlowNodeRefs()) { nodeRefIds.add(flowElement.getId()); if(coordianteManipulation) { marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeEndArray(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); generator.writeEndObject(); } else { // dont marshall the lane unless it has BPMNDI info (eclipse editor does not generate it for lanes currently. for (FlowElement flowElement: lane.getFlowNodeRefs()) { nodeRefIds.add(flowElement.getId()); // we dont want an offset here! marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } return nodeRefIds; } protected void marshallFlowElement(FlowElement flowElement, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", flowElement.getId()); Map<String, Object> flowElementProperties = new LinkedHashMap<String, Object>(); Iterator<FeatureMap.Entry> iter = flowElement.getAnyAttribute().iterator(); boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("background-color")) { flowElementProperties.put("bgcolor", entry.getValue()); foundBgColor = true; } if(entry.getEStructuralFeature().getName().equals("border-color")) { flowElementProperties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { flowElementProperties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { flowElementProperties.put("fontcolor", entry.getValue()); foundFontColor = true; } if(entry.getEStructuralFeature().getName().equals("selectable")) { flowElementProperties.put("isselectable", entry.getValue()); foundSelectable = true; } } if(!foundBgColor) { if(flowElement instanceof Activity || flowElement instanceof SubProcess ) { flowElementProperties.put("bgcolor", defaultBgColor_Activities); } else if(flowElement instanceof StartEvent) { flowElementProperties.put("bgcolor", defaultBgColor_StartEvents); } else if(flowElement instanceof EndEvent) { flowElementProperties.put("bgcolor", defaultBgColor_EndEvents); } else if(flowElement instanceof DataObject) { flowElementProperties.put("bgcolor", defaultBgColor_DataObjects); } else if(flowElement instanceof CatchEvent) { flowElementProperties.put("bgcolor", defaultBgColor_CatchingEvents); } else if(flowElement instanceof ThrowEvent) { flowElementProperties.put("bgcolor", defaultBgColor_ThrowingEvents); } else if(flowElement instanceof Gateway) { flowElementProperties.put("bgcolor", defaultBgColor_Gateways); } else if(flowElement instanceof Lane) { flowElementProperties.put("bgcolor", defaultBgColor_Swimlanes); } else { flowElementProperties.put("bgcolor", defaultBgColor_Events); } } if(!foundBrColor) { if(flowElement instanceof CatchEvent && !(flowElement instanceof StartEvent)) { flowElementProperties.put("bordercolor", defaultBrColor_CatchingEvents); } else if(flowElement instanceof ThrowEvent && !(flowElement instanceof EndEvent)) { flowElementProperties.put("bordercolor", defaultBrColor_ThrowingEvents); } else if(flowElement instanceof Gateway) { flowElementProperties.put("bordercolor", defaultBrColor_Gateways); } else { flowElementProperties.put("bordercolor", defaultBrColor); } } if(!foundFontColor) { flowElementProperties.put("fontcolor", defaultFontColor); } if(!foundSelectable) { flowElementProperties.put("isselectable", "true"); } Map<String, Object> catchEventProperties = new LinkedHashMap<String, Object>(flowElementProperties); Map<String, Object> throwEventProperties = new LinkedHashMap<String, Object>(flowElementProperties); if(flowElement instanceof CatchEvent) { setCatchEventProperties((CatchEvent) flowElement, catchEventProperties); } if(flowElement instanceof ThrowEvent) { setThrowEventProperties((ThrowEvent) flowElement, throwEventProperties); } if (flowElement instanceof StartEvent) { marshallStartEvent((StartEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof EndEvent) { marshallEndEvent((EndEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties); } else if (flowElement instanceof IntermediateThrowEvent) { marshallIntermediateThrowEvent((IntermediateThrowEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties); } else if (flowElement instanceof IntermediateCatchEvent) { marshallIntermediateCatchEvent((IntermediateCatchEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof BoundaryEvent) { marshallBoundaryEvent((BoundaryEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof Task) { marshallTask((Task) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties); } else if (flowElement instanceof SequenceFlow) { marshallSequenceFlow((SequenceFlow) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof ParallelGateway) { marshallParallelGateway((ParallelGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof ExclusiveGateway) { marshallExclusiveGateway((ExclusiveGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof InclusiveGateway) { marshallInclusiveGateway((InclusiveGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof EventBasedGateway) { marshallEventBasedGateway((EventBasedGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof ComplexGateway) { marshallComplexGateway((ComplexGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof CallActivity) { marshallCallActivity((CallActivity) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof SubProcess) { if(flowElement instanceof AdHocSubProcess) { marshallSubProcess((AdHocSubProcess) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties); } else { marshallSubProcess((SubProcess) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties); } } else if (flowElement instanceof DataObject) { // only marshall if we can find DI info for it - BZ 800346 if(findDiagramElement(plane, (DataObject) flowElement) != null) { marshallDataObject((DataObject) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else { _logger.info("Could not marshall Data Object " + (DataObject) flowElement + " because no DI information could be found."); } } else { throw new UnsupportedOperationException("Unknown flow element " + flowElement); } generator.writeEndObject(); } protected void marshallStartEvent(StartEvent startEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = startEvent.getEventDefinitions(); properties.put("isinterrupting", startEvent.isIsInterrupting()); if (eventDefinitions == null || eventDefinitions.size() == 0) { marshallNode(startEvent, properties, "StartNoneEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof ConditionalEventDefinition) { marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof SignalEventDefinition) { marshallNode(startEvent, properties, "StartSignalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(startEvent, properties, "StartMessageEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(startEvent, properties, "StartTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(startEvent, properties, "StartErrorEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof ConditionalEventDefinition) { marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof EscalationEventDefinition) { marshallNode(startEvent, properties, "StartEscalationEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof CompensateEventDefinition) { marshallNode(startEvent, properties, "StartCompensationEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Multiple event definitions not supported for start event"); } } protected void marshallEndEvent(EndEvent endEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = endEvent.getEventDefinitions(); if (eventDefinitions == null || eventDefinitions.size() == 0) { marshallNode(endEvent, properties, "EndNoneEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof TerminateEventDefinition) { marshallNode(endEvent, properties, "EndTerminateEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof SignalEventDefinition) { marshallNode(endEvent, properties, "EndSignalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(endEvent, properties, "EndMessageEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(endEvent, properties, "EndErrorEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(endEvent, properties, "EndEscalationEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(endEvent, properties, "EndCompensationEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof CancelEventDefinition) { marshallNode(endEvent, properties, "EndCancelEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Multiple event definitions not supported for end event"); } } protected void marshallIntermediateCatchEvent(IntermediateCatchEvent catchEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = catchEvent.getEventDefinitions(); // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(catchEvent.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); if (processingTime == null) { continue; } ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 has not support for random distribution type // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } } } } if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(catchEvent, properties, "IntermediateSignalEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(catchEvent, properties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(catchEvent, properties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ConditionalEventDefinition) { marshallNode(catchEvent, properties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof ErrorEventDefinition) { marshallNode(catchEvent, properties, "IntermediateErrorEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof EscalationEventDefinition) { marshallNode(catchEvent, properties, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof CompensateEventDefinition) { marshallNode(catchEvent, properties, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Intermediate catch event does not have event definition."); } } protected void marshallBoundaryEvent(BoundaryEvent boundaryEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> catchEventProperties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = boundaryEvent.getEventDefinitions(); if(boundaryEvent.isCancelActivity()) { catchEventProperties.put("boundarycancelactivity", "true"); } else { catchEventProperties.put("boundarycancelactivity", "false"); } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(boundaryEvent.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); if (processingTime == null) { continue; } ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; catchEventProperties.put("mean", ndt.getMean()); catchEventProperties.put("standarddeviation", ndt.getStandardDeviation()); catchEventProperties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; catchEventProperties.put("min", udt.getMin()); catchEventProperties.put("max", udt.getMax()); catchEventProperties.put("distributiontype", "uniform"); // bpsim 1.0 has not support for random distribution type // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; catchEventProperties.put("mean", pdt.getMean()); catchEventProperties.put("distributiontype", "poisson"); } ControlParameters controlParams = eleType.getControlParameters(); if(controlParams != null) { Parameter probabilityParam = controlParams.getProbability(); if(probabilityParam != null && probabilityParam.getParameterValue() != null) { FloatingParameterType valType = (FloatingParameterType) probabilityParam.getParameterValue().get(0); catchEventProperties.put("probability", valType.getValue()); } } } } } if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateSignalEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateErrorEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof ConditionalEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof MessageEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset); }else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for boundary event"); } } protected void marshallIntermediateThrowEvent(IntermediateThrowEvent throwEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = throwEvent.getEventDefinitions(); // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(throwEvent.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); if (processingTime == null) { continue; } ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 has not support for random distribution type // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } } } } if (eventDefinitions.size() == 0) { marshallNode(throwEvent, properties, "IntermediateEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(throwEvent, properties, "IntermediateSignalEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(throwEvent, properties, "IntermediateMessageEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(throwEvent, properties, "IntermediateEscalationEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(throwEvent, properties, "IntermediateCompensationEventThrowing", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for intermediate throw event"); } } protected void marshallCallActivity(CallActivity callActivity, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); Iterator<FeatureMap.Entry> iter = callActivity.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("independent")) { properties.put("independent", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("waitForCompletion")) { properties.put("waitforcompletion", entry.getValue()); } } if(callActivity.getCalledElement() != null && callActivity.getCalledElement().length() > 0) { properties.put("calledelement", callActivity.getCalledElement()); } // data inputs if(callActivity.getIoSpecification() != null) { List<InputSet> inputSetList = callActivity.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { if(dataIn.getName() != null) { dataInBuffer.append(dataIn.getName()); if(dataIn.getItemSubjectRef() != null && dataIn.getItemSubjectRef().getStructureRef() != null && dataIn.getItemSubjectRef().getStructureRef().length() > 0) { dataInBuffer.append(":").append(dataIn.getItemSubjectRef().getStructureRef()); } dataInBuffer.append(","); } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(callActivity.getIoSpecification() != null) { List<OutputSet> outputSetList = callActivity.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { dataOutBuffer.append(dataOut.getName()); if(dataOut.getItemSubjectRef() != null && dataOut.getItemSubjectRef().getStructureRef() != null && dataOut.getItemSubjectRef().getStructureRef().length() > 0) { dataOutBuffer.append(":").append(dataOut.getItemSubjectRef().getStructureRef()); } dataOutBuffer.append(","); } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = callActivity.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = callActivity.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); //List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } // else { // // check if this is a bi-directional association // for(DataOutputAssociation dataout : outputAssociations) { // if(dataout.getTargetRef().getId().equals(lhsAssociation) && // ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { // isBiDirectional = true; // break; // } // } // } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } String replacer = associationValue.replaceAll(",", "##"); associationBuff.append(rhsAssociation).append("=").append(replacer); associationBuff.append(","); } } // else if(isBiDirectional) { // associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); // associationBuff.append(","); // biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } } } for(DataOutputAssociation dataout : outputAssociations) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional // for(String bda : biDirectionalAssociations) { // String[] dbaparts = bda.split( ",\\s*" ); // if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { // wasBiDirectional = true; // break; // } // } if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) { rhsAssociation = dataout.getTransformation().getBody().replaceAll("=", "||"); } if(!wasBiDirectional) { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[dout]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); } } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions if(callActivity.getExtensionValues() != null && callActivity.getExtensionValues().size() > 0) { String onEntryStr = ""; String onExitStr = ""; for(ExtensionAttributeValue extattrval : callActivity.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true); @SuppressWarnings("unchecked") List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true); for(OnEntryScriptType onEntryScript : onEntryExtensions) { onEntryStr += onEntryScript.getScript(); onEntryStr += "|"; if(onEntryScript.getScriptFormat() != null) { String format = onEntryScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } properties.put("script_language", formatToWrite); } } for(OnExitScriptType onExitScript : onExitExtensions) { onExitStr += onExitScript.getScript(); onExitStr += "|"; if(onExitScript.getScriptFormat() != null) { String format = onExitScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } if(properties.get("script_language") == null) { properties.put("script_language", formatToWrite); } } } } if(onEntryStr.length() > 0) { if(onEntryStr.endsWith("|")) { onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1); } properties.put("onentryactions", onEntryStr); } if(onExitStr.length() > 0) { if(onExitStr.endsWith("|")) { onExitStr = onExitStr.substring(0, onExitStr.length() - 1); } properties.put("onexitactions", onExitStr); } } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(callActivity.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 does not support random distribution // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } if(timeParams.getWaitTime() != null) { FloatingParameterType waittimeType = (FloatingParameterType) timeParams.getWaitTime().getParameterValue().get(0); properties.put("waittime", waittimeType.getValue()); } CostParameters costParams = eleType.getCostParameters(); if(costParams != null) { if(costParams.getUnitCost() != null) { FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); } // bpsim 1.0 does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); } } } } marshallNode(callActivity, properties, "ReusableSubprocess", plane, generator, xOffset, yOffset); } protected void marshallTask(Task task, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); String taskType = "None"; if (task instanceof BusinessRuleTask) { taskType = "Business Rule"; Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("ruleFlowGroup")) { properties.put("ruleflowgroup", entry.getValue()); } } } else if (task instanceof ScriptTask) { ScriptTask scriptTask = (ScriptTask) task; properties.put("script", scriptTask.getScript() != null ? scriptTask.getScript().replace("\\", "\\\\").replace("\n", "\\n") : ""); String format = scriptTask.getScriptFormat(); if(format != null && format.length() > 0) { String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { // default to java formatToWrite = "java"; } properties.put("script_language", formatToWrite); } taskType = "Script"; } else if (task instanceof ServiceTask) { taskType = "Service"; ServiceTask serviceTask = (ServiceTask) task; if(serviceTask.getOperationRef() != null && serviceTask.getImplementation() != null) { properties.put("serviceimplementation", serviceTask.getImplementation()); properties.put("serviceoperation", serviceTask.getOperationRef().getName() == null ? serviceTask.getOperationRef().getImplementationRef() : serviceTask.getOperationRef().getName()); if(def != null) { List<RootElement> roots = def.getRootElements(); for(RootElement root : roots) { if(root instanceof Interface) { Interface inter = (Interface) root; List<Operation> interOperations = inter.getOperations(); for(Operation interOper : interOperations) { if(interOper.getId().equals(serviceTask.getOperationRef().getId())) { properties.put("serviceinterface", inter.getName() == null ? inter.getImplementationRef() : inter.getName()); } } } } } } } else if (task instanceof ManualTask) { taskType = "Manual"; } else if (task instanceof UserTask) { taskType = "User"; // get the user task actors List<ResourceRole> roles = task.getResources(); StringBuilder sb = new StringBuilder(); for(ResourceRole role : roles) { if(role instanceof PotentialOwner) { FormalExpression fe = (FormalExpression) ( (PotentialOwner)role).getResourceAssignmentExpression().getExpression(); if(fe.getBody() != null && fe.getBody().length() > 0) { sb.append(fe.getBody()); sb.append(","); } } } if(sb.length() > 0) { sb.setLength(sb.length() - 1); } properties.put("actors", sb.toString()); // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(task.getId())) { CostParameters costParams = eleType.getCostParameters(); FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); // bpsim does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); ResourceParameters resourceParams = eleType.getResourceParameters(); FloatingParameterType quantityVal = (FloatingParameterType) resourceParams.getQuantity().getParameterValue().get(0); properties.put("quantity", quantityVal.getValue()); FloatingParameterType workingHoursVal = (FloatingParameterType) resourceParams.getAvailability().getParameterValue().get(0); properties.put("workinghours", workingHoursVal.getValue()); } } } } else if (task instanceof SendTask) { taskType = "Send"; SendTask st = (SendTask) task; if(st.getMessageRef() != null) { properties.put("messageref", st.getMessageRef().getId()); } } else if (task instanceof ReceiveTask) { taskType = "Receive"; ReceiveTask rt = (ReceiveTask) task; if(rt.getMessageRef() != null) { properties.put("messageref", rt.getMessageRef().getId()); } } // backwards compatibility with jbds editor boolean foundTaskName = false; if(task.getIoSpecification() != null && task.getIoSpecification().getDataInputs() != null) { List<DataInput> taskDataInputs = task.getIoSpecification().getDataInputs(); for(DataInput din : taskDataInputs) { if(din.getName() != null && din.getName().equals("TaskName")) { List<DataInputAssociation> taskDataInputAssociations = task.getDataInputAssociations(); for(DataInputAssociation dia : taskDataInputAssociations) { if(dia.getTargetRef() != null && dia.getTargetRef().getId().equals(din.getId())) { properties.put("taskname", ((FormalExpression) dia.getAssignment().get(0).getFrom()).getBody()); foundTaskName = true; } } break; } } } if(!foundTaskName) { // try the drools specific attribute set on the task Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("taskName")) { String tname = (String) entry.getValue(); if(tname != null && tname.length() > 0) { properties.put("taskname", tname); } } } } // check if we are dealing with a custom task if(isCustomElement((String) properties.get("taskname"), preProcessingData)) { properties.put("tasktype", properties.get("taskname")); } else { properties.put("tasktype", taskType); } // multiple instance if(task.getLoopCharacteristics() != null) { properties.put("multipleinstance", "true"); MultiInstanceLoopCharacteristics taskmi = (MultiInstanceLoopCharacteristics) task.getLoopCharacteristics(); if(taskmi.getLoopDataInputRef() != null) { ItemAwareElement iedatainput = taskmi.getLoopDataInputRef(); List<DataInputAssociation> taskInputAssociations = task.getDataInputAssociations(); for(DataInputAssociation dia : taskInputAssociations) { if(dia.getTargetRef().equals(iedatainput)) { properties.put("multipleinstancecollectioninput", dia.getSourceRef().get(0).getId()); break; } } } if(taskmi.getLoopDataOutputRef() != null) { ItemAwareElement iedataoutput = taskmi.getLoopDataOutputRef(); List<DataOutputAssociation> taskOutputAssociations = task.getDataOutputAssociations(); for(DataOutputAssociation dout : taskOutputAssociations) { if(dout.getSourceRef().get(0).equals(iedataoutput)) { properties.put("multipleinstancecollectionoutput", dout.getTargetRef().getId()); break; } } } if(taskmi.getInputDataItem() != null && taskmi.getInputDataItem().getItemSubjectRef() != null) { List<DataInput> taskDataInputs = task.getIoSpecification().getDataInputs(); for(DataInput din: taskDataInputs) { if(din != null && din.getItemSubjectRef() != null && taskmi.getInputDataItem() != null && taskmi.getInputDataItem().getItemSubjectRef() != null ) { if(din.getItemSubjectRef().getId().equals(taskmi.getInputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedatainput", din.getName()); } } } } if(taskmi.getOutputDataItem() != null && taskmi.getOutputDataItem().getItemSubjectRef() != null) { List<DataOutput> taskDataOutputs = task.getIoSpecification().getDataOutputs(); for(DataOutput dout : taskDataOutputs) { if(dout != null && dout.getItemSubjectRef() != null && taskmi.getOutputDataItem() != null && taskmi.getOutputDataItem().getItemSubjectRef() != null) { if(dout.getItemSubjectRef().getId().equals(taskmi.getOutputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedataoutput", dout.getName()); } } } } if(taskmi.getCompletionCondition() != null) { if (taskmi.getCompletionCondition() instanceof FormalExpression) { properties.put("multipleinstancecompletioncondition", ((FormalExpression)taskmi.getCompletionCondition()).getBody()); } } } else { properties.put("multipleinstance", "false"); } // data inputs DataInput groupDataInput = null; DataInput skippableDataInput = null; DataInput commentDataInput = null; DataInput contentDataInput = null; DataInput priorityDataInput = null; DataInput localeDataInput = null; DataInput createdByDataInput = null; DataInput notCompletedReassignInput = null; DataInput notStartedReassignInput = null; DataInput notCompletedNotificationInput = null; DataInput notStartedNotificationInput = null; if(task.getIoSpecification() != null) { List<InputSet> inputSetList = task.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { // dont add "TaskName" as that is added manually if(dataIn.getName() != null && !dataIn.getName().equals("TaskName") && !dataIn.getName().equals("miinputCollection")) { dataInBuffer.append(dataIn.getName()); if(dataIn.getItemSubjectRef() != null && dataIn.getItemSubjectRef().getStructureRef() != null && dataIn.getItemSubjectRef().getStructureRef().length() > 0) { dataInBuffer.append(":").append(dataIn.getItemSubjectRef().getStructureRef()); } dataInBuffer.append(","); } if(dataIn.getName() != null && dataIn.getName().equals("GroupId")) { groupDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Skippable")) { skippableDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Comment")) { commentDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Content")) { contentDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Priority")) { priorityDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Locale")) { localeDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("CreatedBy")) { createdByDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotCompletedReassign")) { notCompletedReassignInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotStartedReassign")) { notStartedReassignInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotCompletedNotify")) { notCompletedNotificationInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotStartedNotify")) { notStartedNotificationInput = dataIn; } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(task.getIoSpecification() != null) { List<OutputSet> outputSetList = task.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { if(!dataOut.getName().equals("mioutputCollection")) { dataOutBuffer.append(dataOut.getName()); if(dataOut.getItemSubjectRef() != null && dataOut.getItemSubjectRef().getStructureRef() != null && dataOut.getItemSubjectRef().getStructureRef().length() > 0) { dataOutBuffer.append(":").append(dataOut.getItemSubjectRef().getStructureRef()); } dataOutBuffer.append(","); } } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = task.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = task.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); //List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { boolean proceed = true; if(task.getLoopCharacteristics() != null) { MultiInstanceLoopCharacteristics taskMultiLoop = (MultiInstanceLoopCharacteristics) task.getLoopCharacteristics(); // dont include associations that include mi loop data inputs if(taskMultiLoop.getInputDataItem() != null && taskMultiLoop.getInputDataItem().getId() != null) { if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0 && datain.getSourceRef().get(0).getId().equals(taskMultiLoop.getInputDataItem().getId())) { proceed = false; } } // dont include associations that include loopDataInputRef as target if(taskMultiLoop.getLoopDataInputRef() != null ) { if(datain.getTargetRef().equals(taskMultiLoop.getLoopDataInputRef())) { proceed = false; } } } if(proceed) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } // else { // // check if this is a bi-directional association // for(DataOutputAssociation dataout : outputAssociations) { // if(dataout.getTargetRef().getId().equals(lhsAssociation) && // ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { // isBiDirectional = true; // break; // } // } // } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } // don't include properties that have their independent input editors: if(!(rhsAssociation.equals("GroupId") || rhsAssociation.equals("Skippable") || rhsAssociation.equals("Comment") || rhsAssociation.equals("Priority") || rhsAssociation.equals("Content") || rhsAssociation.equals("TaskName") || rhsAssociation.equals("Locale") || rhsAssociation.equals("CreatedBy") || rhsAssociation.equals("NotCompletedReassign") || rhsAssociation.equals("NotStartedReassign") || rhsAssociation.equals("NotCompletedNotify") || rhsAssociation.equals("NotStartedNotify") )) { String replacer = associationValue.replaceAll(",", "##"); associationBuff.append("[din]" + rhsAssociation).append("=").append(replacer); associationBuff.append(","); } if(rhsAssociation.equalsIgnoreCase("TaskName")) { properties.put("taskname", associationValue); } if (groupDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(groupDataInput.getId())) { properties.put("groupid", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody() == null ? "" : ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (skippableDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(skippableDataInput.getId())) { properties.put("skippable", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (commentDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(commentDataInput.getId())) { properties.put("comment", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (priorityDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(priorityDataInput.getId())) { properties.put("priority", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody() == null ? "" : ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (contentDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(contentDataInput.getId())) { properties.put("content", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (localeDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(localeDataInput.getId())) { properties.put("locale", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (createdByDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(createdByDataInput.getId())) { properties.put("createdby", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (notCompletedReassignInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notCompletedReassignInput.getId())) { properties.put("tmpreassignmentnotcompleted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-completed" )); } if (notStartedReassignInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notStartedReassignInput.getId())) { properties.put("tmpreassignmentnotstarted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-started" )); } if (notCompletedNotificationInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notCompletedNotificationInput.getId())) { properties.put("tmpnotificationnotcompleted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-completed" )); } if (notStartedNotificationInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notStartedNotificationInput.getId())) { properties.put("tmpnotificationnotstarted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-started" )); } } } // else if(isBiDirectional) { // associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); // associationBuff.append(","); // biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // if(contentDataInput != null) { // if(rhsAssociation.equals(contentDataInput.getName())) { // properties.put("content", lhsAssociation); // } // } } } } if(properties.get("tmpreassignmentnotcompleted") != null && ((String)properties.get("tmpreassignmentnotcompleted")).length() > 0 && properties.get("tmpreassignmentnotstarted") != null && ((String) properties.get("tmpreassignmentnotstarted")).length() > 0) { properties.put("reassignment", properties.get("tmpreassignmentnotcompleted") + "^" + properties.get("tmpreassignmentnotstarted")); } else if(properties.get("tmpreassignmentnotcompleted") != null && ((String) properties.get("tmpreassignmentnotcompleted")).length() > 0) { properties.put("reassignment", properties.get("tmpreassignmentnotcompleted")); } else if(properties.get("tmpreassignmentnotstarted") != null && ((String) properties.get("tmpreassignmentnotstarted")).length() > 0) { properties.put("reassignment", properties.get("tmpreassignmentnotstarted")); } if(properties.get("tmpnotificationnotcompleted") != null && ((String)properties.get("tmpnotificationnotcompleted")).length() > 0 && properties.get("tmpnotificationnotstarted") != null && ((String) properties.get("tmpnotificationnotstarted")).length() > 0) { properties.put("notifications", properties.get("tmpnotificationnotcompleted") + "^" + properties.get("tmpnotificationnotstarted")); } else if(properties.get("tmpnotificationnotcompleted") != null && ((String) properties.get("tmpnotificationnotcompleted")).length() > 0) { properties.put("notifications", properties.get("tmpnotificationnotcompleted")); } else if(properties.get("tmpnotificationnotstarted") != null && ((String) properties.get("tmpnotificationnotstarted")).length() > 0) { properties.put("notifications", properties.get("tmpnotificationnotstarted")); } for(DataOutputAssociation dataout : outputAssociations) { boolean proceed = true; if(task.getLoopCharacteristics() != null) { MultiInstanceLoopCharacteristics taskMultiLoop = (MultiInstanceLoopCharacteristics) task.getLoopCharacteristics(); // dont include associations that include mi loop data outputs if(taskMultiLoop.getOutputDataItem() != null && taskMultiLoop.getOutputDataItem().getId() != null) { if(dataout.getTargetRef().getId().equals(taskMultiLoop.getOutputDataItem().getId())) { proceed = false; } } // dont include associations that include loopDataOutputRef as source if(taskMultiLoop.getLoopDataOutputRef() != null) { if(dataout.getSourceRef().get(0).equals(taskMultiLoop.getLoopDataOutputRef())) { proceed = false; } } } if(proceed) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional // for(String bda : biDirectionalAssociations) { // String[] dbaparts = bda.split( ",\\s*" ); // if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { // wasBiDirectional = true; // break; // } // } if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) { rhsAssociation = dataout.getTransformation().getBody().replaceAll("=", "||"); } if(!wasBiDirectional) { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[dout]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); } } } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions if(task.getExtensionValues() != null && task.getExtensionValues().size() > 0) { String onEntryStr = ""; String onExitStr = ""; for(ExtensionAttributeValue extattrval : task.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true); @SuppressWarnings("unchecked") List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true); for(OnEntryScriptType onEntryScript : onEntryExtensions) { onEntryStr += onEntryScript.getScript(); onEntryStr += "|"; if(onEntryScript.getScriptFormat() != null) { String format = onEntryScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } properties.put("script_language", formatToWrite); } } for(OnExitScriptType onExitScript : onExitExtensions) { onExitStr += onExitScript.getScript(); onExitStr += "|"; if(onExitScript.getScriptFormat() != null) { String format = onExitScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } if(properties.get("script_language") == null) { properties.put("script_language", formatToWrite); } } } } if(onEntryStr.length() > 0) { if(onEntryStr.endsWith("|")) { onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1); } properties.put("onentryactions", onEntryStr); } if(onExitStr.length() > 0) { if(onExitStr.endsWith("|")) { onExitStr = onExitStr.substring(0, onExitStr.length() - 1); } properties.put("onexitactions", onExitStr); } } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(task.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 does not support random distribution // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } if(timeParams.getWaitTime() != null) { FloatingParameterType waittimeType = (FloatingParameterType) timeParams.getWaitTime().getParameterValue().get(0); properties.put("waittime", waittimeType.getValue()); } CostParameters costParams = eleType.getCostParameters(); if(costParams != null) { if(costParams.getUnitCost() != null) { FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); } // bpsim 1.0 does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); } } } } // marshall the node out if(isCustomElement((String) properties.get("taskname"), preProcessingData)) { marshallNode(task, properties, (String) properties.get("taskname"), plane, generator, xOffset, yOffset); } else { marshallNode(task, properties, "Task", plane, generator, xOffset, yOffset); } } protected void marshallParallelGateway(ParallelGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { marshallNode(gateway, flowElementProperties, "ParallelGateway", plane, generator, xOffset, yOffset); } protected void marshallExclusiveGateway(ExclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { if(gateway.getDefault() != null) { SequenceFlow defsf = gateway.getDefault(); String defGatewayStr = ""; if(defsf.getName() != null && defsf.getName().length() > 0) { defGatewayStr = defsf.getName() + " : " + defsf.getId(); } else { defGatewayStr = defsf.getId(); } flowElementProperties.put("defaultgate", defGatewayStr); } marshallNode(gateway, flowElementProperties, "Exclusive_Databased_Gateway", plane, generator, xOffset, yOffset); } protected void marshallInclusiveGateway(InclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { if(gateway.getDefault() != null) { SequenceFlow defsf = gateway.getDefault(); String defGatewayStr = ""; if(defsf.getName() != null && defsf.getName().length() > 0) { defGatewayStr = defsf.getName() + " : " + defsf.getId(); } else { defGatewayStr = defsf.getId(); } flowElementProperties.put("defaultgate", defGatewayStr); } marshallNode(gateway, flowElementProperties, "InclusiveGateway", plane, generator, xOffset, yOffset); } protected void marshallEventBasedGateway(EventBasedGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { marshallNode(gateway, flowElementProperties, "EventbasedGateway", plane, generator, xOffset, yOffset); } protected void marshallComplexGateway(ComplexGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { marshallNode(gateway, flowElementProperties, "ComplexGateway", plane, generator, xOffset, yOffset); } protected void marshallNode(FlowNode node, Map<String, Object> properties, String stencil, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset) throws JsonGenerationException, IOException { if (properties == null) { properties = new LinkedHashMap<String, Object>(); } if(node.getDocumentation() != null && node.getDocumentation().size() > 0) { properties.put("documentation", node.getDocumentation().get(0).getText()); } if(node.getName() != null) { properties.put("name", unescapeXML(node.getName())); } else { properties.put("name", ""); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencil); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (SequenceFlow outgoing: node.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } // we need to also add associations as outgoing elements Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getSourceRef().getId().equals(node.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", association.getId()); generator.writeEndObject(); } } } // and boundary events for activities List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>(); findBoundaryEvents(process, boundaryEvents); for(BoundaryEvent be : boundaryEvents) { if(be.getAttachedToRef().getId().equals(node.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", be.getId()); generator.writeEndObject(); } } generator.writeEndArray(); // boundary events have a docker if(node instanceof BoundaryEvent) { // find the edge associated with this boundary event for (DiagramElement element: plane.getPlaneElement()) { if(element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == node) { List<Point> waypoints = ((BPMNEdge) element).getWaypoint(); if(waypoints != null && waypoints.size() > 0) { // one per boundary event Point p = waypoints.get(0); if(p != null) { generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", p.getX()); generator.writeObjectField("y", p.getY()); generator.writeEndObject(); generator.writeEndArray(); } } } } } BPMNShape shape = (BPMNShape) findDiagramElement(plane, node); Bounds bounds = shape.getBounds(); correctEventNodeSize(shape); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } private void correctEventNodeSize(BPMNShape shape) { BaseElement element = shape.getBpmnElement(); if (element instanceof Event) { // // do not "fix" events as they shape is circle - leave bounds as is // Bounds bounds = shape.getBounds(); // float width = bounds.getWidth(); // float height = bounds.getHeight(); // if (width != 30 || height != 30) { // bounds.setWidth(30); // bounds.setHeight(30); // float x = bounds.getX(); // float y = bounds.getY(); // x = x - ((30 - width)/2); // y = y - ((30 - height)/2); // bounds.setX(x); // bounds.setY(y); // } } else if (element instanceof Gateway) { Bounds bounds = shape.getBounds(); float width = bounds.getWidth(); float height = bounds.getHeight(); if (width != 40 || height != 40) { bounds.setWidth(40); bounds.setHeight(40); float x = bounds.getX(); float y = bounds.getY(); x = x - ((40 - width)/2); y = y - ((40 - height)/2); bounds.setX(x); bounds.setY(y); } } } protected void marshallDataObject(DataObject dataObject, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); if(dataObject.getDocumentation() != null && dataObject.getDocumentation().size() > 0) { properties.put("documentation", dataObject.getDocumentation().get(0).getText()); } if(dataObject.getName() != null && dataObject.getName().length() > 0) { properties.put("name", unescapeXML(dataObject.getName())); } else { // we need a name, use id instead properties.put("name", dataObject.getId()); } if(dataObject.getItemSubjectRef().getStructureRef() != null && dataObject.getItemSubjectRef().getStructureRef().length() > 0) { if(defaultTypesList.contains(dataObject.getItemSubjectRef().getStructureRef())) { properties.put("standardtype", dataObject.getItemSubjectRef().getStructureRef()); } else { properties.put("customtype", dataObject.getItemSubjectRef().getStructureRef()); } } Association outgoingAssociaton = findOutgoingAssociation(plane, dataObject); Association incomingAssociation = null; Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getTargetRef() == dataObject){ incomingAssociation = association; } } } if(outgoingAssociaton != null && incomingAssociation == null) { properties.put("input_output", "Input"); } if(outgoingAssociaton == null && incomingAssociation != null) { properties.put("input_output", "Output"); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "DataObject"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); List<Association> associations = findOutgoingAssociations(plane, dataObject); if(associations != null) { for(Association as : associations) { generator.writeStartObject(); generator.writeObjectField("resourceId", as.getId()); generator.writeEndObject(); } } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, dataObject)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected void marshallSubProcess(SubProcess subProcess, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); if(subProcess.getName() != null) { properties.put("name", unescapeXML(subProcess.getName())); } else { properties.put("name", ""); } if(subProcess instanceof AdHocSubProcess) { AdHocSubProcess ahsp = (AdHocSubProcess) subProcess; if(ahsp.getOrdering().equals(AdHocOrdering.PARALLEL)) { properties.put("adhocordering", "Parallel"); } else if(ahsp.getOrdering().equals(AdHocOrdering.SEQUENTIAL)) { properties.put("adhocordering", "Sequential"); } else { // default to parallel properties.put("adhocordering", "Parallel"); } if(ahsp.getCompletionCondition() != null) { properties.put("adhoccompletioncondition", ((FormalExpression) ahsp.getCompletionCondition()).getBody().replaceAll("\n", "\\\\n")); } } // data inputs if(subProcess.getIoSpecification() != null) { List<InputSet> inputSetList = subProcess.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { if(dataIn.getName() != null) { dataInBuffer.append(dataIn.getName()); if(dataIn.getItemSubjectRef() != null && dataIn.getItemSubjectRef().getStructureRef() != null && dataIn.getItemSubjectRef().getStructureRef().length() > 0) { dataInBuffer.append(":").append(dataIn.getItemSubjectRef().getStructureRef()); } dataInBuffer.append(","); } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(subProcess.getIoSpecification() != null) { List<OutputSet> outputSetList = subProcess.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { dataOutBuffer.append(dataOut.getName()); if(dataOut.getItemSubjectRef() != null && dataOut.getItemSubjectRef().getStructureRef() != null && dataOut.getItemSubjectRef().getStructureRef().length() > 0) { dataOutBuffer.append(":").append(dataOut.getItemSubjectRef().getStructureRef()); } dataOutBuffer.append(","); } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = subProcess.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = subProcess.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); //List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } // else { // // check if this is a bi-directional association // for(DataOutputAssociation dataout : outputAssociations) { // if(dataout.getTargetRef().getId().equals(lhsAssociation) && // ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { // isBiDirectional = true; // break; // } // } // } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } String replacer = associationValue.replaceAll(",", "##"); associationBuff.append("[din]" + rhsAssociation).append("=").append(replacer); associationBuff.append(","); } } // else if(isBiDirectional) { // associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); // associationBuff.append(","); // biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } } } for(DataOutputAssociation dataout : outputAssociations) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional // for(String bda : biDirectionalAssociations) { // String[] dbaparts = bda.split( ",\\s*" ); // if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { // wasBiDirectional = true; // break; // } // } if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) { rhsAssociation = dataout.getTransformation().getBody().replaceAll("=", "||"); } if(!wasBiDirectional) { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[dout]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); } } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions if(subProcess.getExtensionValues() != null && subProcess.getExtensionValues().size() > 0) { String onEntryStr = ""; String onExitStr = ""; for(ExtensionAttributeValue extattrval : subProcess.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true); @SuppressWarnings("unchecked") List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true); for(OnEntryScriptType onEntryScript : onEntryExtensions) { onEntryStr += onEntryScript.getScript(); onEntryStr += "|"; if(onEntryScript.getScriptFormat() != null) { String format = onEntryScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } properties.put("script_language", formatToWrite); } } for(OnExitScriptType onExitScript : onExitExtensions) { onExitStr += onExitScript.getScript(); onExitStr += "|"; if(onExitScript.getScriptFormat() != null) { String format = onExitScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } if(properties.get("script_language") == null) { properties.put("script_language", formatToWrite); } } } } if(onEntryStr.length() > 0) { if(onEntryStr.endsWith("|")) { onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1); } properties.put("onentryactions", onEntryStr); } if(onExitStr.length() > 0) { if(onExitStr.endsWith("|")) { onExitStr = onExitStr.substring(0, onExitStr.length() - 1); } properties.put("onexitactions", onExitStr); } } // loop characteristics boolean haveValidLoopCharacteristics = false; if(subProcess.getLoopCharacteristics() != null && subProcess.getLoopCharacteristics() instanceof MultiInstanceLoopCharacteristics) { haveValidLoopCharacteristics = true; properties.put("mitrigger", "true"); MultiInstanceLoopCharacteristics taskmi = (MultiInstanceLoopCharacteristics) subProcess.getLoopCharacteristics(); if(taskmi.getLoopDataInputRef() != null) { ItemAwareElement iedatainput = taskmi.getLoopDataInputRef(); List<DataInputAssociation> taskInputAssociations = subProcess.getDataInputAssociations(); for(DataInputAssociation dia : taskInputAssociations) { if(dia.getTargetRef().equals(iedatainput)) { properties.put("multipleinstancecollectioninput", dia.getSourceRef().get(0).getId()); break; } } } if(taskmi.getLoopDataOutputRef() != null) { ItemAwareElement iedataoutput = taskmi.getLoopDataOutputRef(); List<DataOutputAssociation> taskOutputAssociations = subProcess.getDataOutputAssociations(); for(DataOutputAssociation dout : taskOutputAssociations) { if(dout.getSourceRef().get(0).equals(iedataoutput)) { properties.put("multipleinstancecollectionoutput", dout.getTargetRef().getId()); break; } } } if(taskmi.getInputDataItem() != null) { List<DataInput> taskDataInputs = subProcess.getIoSpecification().getDataInputs(); for(DataInput din: taskDataInputs) { if (din.getItemSubjectRef() == null) { // for backward compatibility as the where only input supported properties.put("multipleinstancedatainput", taskmi.getInputDataItem().getId()); } if(din.getItemSubjectRef() != null && din.getItemSubjectRef().getId().equals(taskmi.getInputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedatainput", din.getName()); break; } } } if(taskmi.getOutputDataItem() != null) { List<DataOutput> taskDataOutputs = subProcess.getIoSpecification().getDataOutputs(); for(DataOutput dout : taskDataOutputs) { if(dout.getItemSubjectRef() == null) { properties.put("multipleinstancedataoutput", taskmi.getOutputDataItem().getId()); break; } if(dout.getItemSubjectRef()!= null && dout.getItemSubjectRef().getId().equals(taskmi.getOutputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedataoutput", dout.getName()); break; } } } if(taskmi.getCompletionCondition() != null) { if (taskmi.getCompletionCondition() instanceof FormalExpression) { properties.put("multipleinstancecompletioncondition", ((FormalExpression)taskmi.getCompletionCondition()).getBody()); } } } // properties List<Property> processProperties = subProcess.getProperties(); if(processProperties != null && processProperties.size() > 0) { String propVal = ""; for(int i=0; i<processProperties.size(); i++) { Property p = processProperties.get(i); propVal += p.getId(); // check the structureRef value if(p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) { propVal += ":" + p.getItemSubjectRef().getStructureRef(); } if(i != processProperties.size()-1) { propVal += ","; } } properties.put("vardefs", propVal); } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(subProcess.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 does not support random distribution // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } if(timeParams.getWaitTime() != null) { FloatingParameterType waittimeType = (FloatingParameterType) timeParams.getWaitTime().getParameterValue().get(0); properties.put("waittime", waittimeType.getValue()); } CostParameters costParams = eleType.getCostParameters(); if(costParams != null) { if(costParams.getUnitCost() != null) { FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); } // bpsim 1.0 does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); } } } } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); if(subProcess instanceof AdHocSubProcess) { generator.writeObjectField("id", "AdHocSubprocess"); } else { if(subProcess.isTriggeredByEvent()) { generator.writeObjectField("id", "EventSubprocess"); } else { if(haveValidLoopCharacteristics) { generator.writeObjectField("id", "MultipleInstanceSubprocess"); } else { generator.writeObjectField("id", "Subprocess"); } } } generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); Bounds bounds = ((BPMNShape) findDiagramElement(plane, subProcess)).getBounds(); for (FlowElement flowElement: subProcess.getFlowElements()) { if(coordianteManipulation) { marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } for (Artifact artifact: subProcess.getArtifacts()) { if(coordianteManipulation) { marshallArtifact(artifact, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def); } } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (BoundaryEvent boundaryEvent: subProcess.getBoundaryEventRefs()) { generator.writeStartObject(); generator.writeObjectField("resourceId", boundaryEvent.getId()); generator.writeEndObject(); } for (SequenceFlow outgoing: subProcess.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } // subprocess boundary events Process process = (Process) plane.getBpmnElement(); List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>(); findBoundaryEvents(process, boundaryEvents); for(BoundaryEvent be : boundaryEvents) { if(be.getAttachedToRef().getId().equals(subProcess.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", be.getId()); generator.writeEndObject(); } } generator.writeEndArray(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected void marshallSequenceFlow(SequenceFlow sequenceFlow, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset) throws JsonGenerationException, IOException { // dont marshal "dangling" sequence flow..better to just omit than fail if(sequenceFlow.getSourceRef() == null || sequenceFlow.getTargetRef() == null) { return; } Map<String, Object> properties = new LinkedHashMap<String, Object>(); // check null for sequence flow name if(sequenceFlow.getName() != null && !"".equals(sequenceFlow.getName())) { properties.put("name", unescapeXML(sequenceFlow.getName())); } else { properties.put("name", ""); } if(sequenceFlow.getDocumentation() != null && sequenceFlow.getDocumentation().size() > 0) { properties.put("documentation", sequenceFlow.getDocumentation().get(0).getText()); } if(sequenceFlow.isIsImmediate()) { properties.put("isimmediate", "true"); } else { properties.put("isimmediate", "false"); } Expression conditionExpression = sequenceFlow.getConditionExpression(); if (conditionExpression instanceof FormalExpression) { if(((FormalExpression) conditionExpression).getBody() != null) { properties.put("conditionexpression", ((FormalExpression) conditionExpression).getBody().replaceAll("\n", "\\\\n")); } if(((FormalExpression) conditionExpression).getLanguage() != null) { String cd = ((FormalExpression) conditionExpression).getLanguage(); String cdStr = ""; if(cd.equalsIgnoreCase("http://www.java.com/java")) { cdStr = "java"; } else if(cd.equalsIgnoreCase("http://www.jboss.org/drools/rule")) { cdStr = "drools"; } else if(cd.equalsIgnoreCase("http://www.mvel.org/2.0")) { cdStr = "mvel"; } else { // default to mvel cdStr = "mvel"; } properties.put("conditionexpressionlanguage", cdStr); } } boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; Iterator<FeatureMap.Entry> iter = sequenceFlow.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("priority")) { String priorityStr = String.valueOf(entry.getValue()); if(priorityStr != null) { try { Integer priorityInt = Integer.parseInt(priorityStr); if(priorityInt >= 1) { properties.put("priority", entry.getValue()); } else { _logger.error("Priority must be equal or greater than 1."); } } catch (NumberFormatException e) { _logger.error("Priority must be a number."); } } } if(entry.getEStructuralFeature().getName().equals("background-color")) { properties.put("bgcolor", entry.getValue()); foundBgColor = true; } if(entry.getEStructuralFeature().getName().equals("border-color")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { properties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { properties.put("fontcolor", entry.getValue()); foundFontColor = true; } if(entry.getEStructuralFeature().getName().equals("selectable")) { properties.put("isselectable", entry.getValue()); foundSelectable = true; } } if(!foundBgColor) { properties.put("bgcolor", defaultSequenceflowColor); } if(!foundBrColor) { properties.put("bordercolor", defaultSequenceflowColor); } if(!foundFontColor) { properties.put("fontcolor", defaultSequenceflowColor); } if(!foundSelectable) { properties.put("isselectable", "true"); } // simulation properties if(_simulationScenario != null) { List<ElementParameters> elementParams = _simulationScenario.getElementParameters(); for(ElementParameters eleType : elementParams) { if(eleType.getElementRef().equals(sequenceFlow.getId())) { FloatingParameterType valType = (FloatingParameterType) eleType.getControlParameters().getProbability().getParameterValue().get(0); properties.put("probability", valType.getValue()); } } } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "SequenceFlow"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", sequenceFlow.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getSourceRef())).getBounds(); Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getTargetRef())).getBounds(); generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", sourceBounds.getWidth() / 2); generator.writeObjectField("y", sourceBounds.getHeight() / 2); generator.writeEndObject(); List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, sequenceFlow)).getWaypoint(); for (int i = 1; i < waypoints.size() - 1; i++) { Point waypoint = waypoints.get(i); generator.writeStartObject(); generator.writeObjectField("x", waypoint.getX()); generator.writeObjectField("y", waypoint.getY()); generator.writeEndObject(); } generator.writeStartObject(); generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); generator.writeEndObject(); generator.writeEndArray(); } private DiagramElement findDiagramElement(BPMNPlane plane, BaseElement baseElement) { DiagramElement result = _diagramElements.get(baseElement.getId()); if (result != null) { return result; } for (DiagramElement element: plane.getPlaneElement()) { if ((element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == baseElement) || (element instanceof BPMNShape && ((BPMNShape) element).getBpmnElement() == baseElement)) { _diagramElements.put(baseElement.getId(), element); return element; } } _logger.info("Could not find BPMNDI information for " + baseElement); return null; } protected void marshallGlobalTask(GlobalTask globalTask, JsonGenerator generator) { if (globalTask instanceof GlobalBusinessRuleTask) { } else if (globalTask instanceof GlobalManualTask) { } else if (globalTask instanceof GlobalScriptTask) { } else if (globalTask instanceof GlobalUserTask) { } else { } } protected void marshallGlobalChoreographyTask(GlobalChoreographyTask callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } protected void marshallConversation(Conversation callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } protected void marshallChoreography(Choreography callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } protected void marshallProperties(Map<String, Object> properties, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeObjectFieldStart("properties"); for (Entry<String, Object> entry : properties.entrySet()) { generator.writeObjectField(entry.getKey(), String.valueOf(entry.getValue())); } generator.writeEndObject(); } protected void marshallArtifact(Artifact artifact, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", artifact.getId()); if (artifact instanceof Association) { marshallAssociation((Association)artifact, plane, generator, xOffset, yOffset, preProcessingData, def); } else if (artifact instanceof TextAnnotation) { marshallTextAnnotation((TextAnnotation) artifact, plane, generator, xOffset, yOffset, preProcessingData, def); } else if (artifact instanceof Group) { marshallGroup((Group) artifact, plane, generator, xOffset, yOffset, preProcessingData, def); } generator.writeEndObject(); } protected void marshallAssociation(Association association, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); Iterator<FeatureMap.Entry> iter = association.getAnyAttribute().iterator(); boolean foundBrColor = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("type")) { properties.put("type", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("bordercolor")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } } if(!foundBrColor) { properties.put("bordercolor", defaultSequenceflowColor); } if(association.getDocumentation() != null && association.getDocumentation().size() > 0) { properties.put("documentation", association.getDocumentation().get(0).getText()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); if(association.getAssociationDirection().equals(AssociationDirection.ONE)) { generator.writeObjectField("id", "Association_Unidirectional"); } else if(association.getAssociationDirection().equals(AssociationDirection.BOTH)) { generator.writeObjectField("id", "Association_Bidirectional"); } else { generator.writeObjectField("id", "Association_Undirected"); } generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", association.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, association.getSourceRef())).getBounds(); Bounds targetBounds = null; float tbx = 0; float tby = 0; if(findDiagramElement(plane, association.getTargetRef()) instanceof BPMNShape) { targetBounds = ((BPMNShape) findDiagramElement(plane, association.getTargetRef())).getBounds(); } else if(findDiagramElement(plane, association.getTargetRef()) instanceof BPMNEdge) { // connect it to first waypoint on edge List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association.getTargetRef())).getWaypoint(); if(waypoints != null && waypoints.size() > 0) { tbx = waypoints.get(0).getX(); tby = waypoints.get(0).getY(); } } generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", sourceBounds.getWidth() / 2); generator.writeObjectField("y", sourceBounds.getHeight() / 2); generator.writeEndObject(); List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association)).getWaypoint(); for (int i = 1; i < waypoints.size() - 1; i++) { Point waypoint = waypoints.get(i); generator.writeStartObject(); generator.writeObjectField("x", waypoint.getX()); generator.writeObjectField("y", waypoint.getY()); generator.writeEndObject(); } if(targetBounds != null) { generator.writeStartObject(); generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); generator.writeEndObject(); generator.writeEndArray(); } else { generator.writeStartObject(); generator.writeObjectField("x", tbx); generator.writeObjectField("y", tby); generator.writeEndObject(); generator.writeEndArray(); } } protected void marshallTextAnnotation(TextAnnotation textAnnotation, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException{ Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("name", textAnnotation.getText()); if(textAnnotation.getDocumentation() != null && textAnnotation.getDocumentation().size() > 0) { properties.put("documentation", textAnnotation.getDocumentation().get(0).getText()); } properties.put("artifacttype", "Annotation"); Iterator<FeatureMap.Entry> iter = textAnnotation.getAnyAttribute().iterator(); boolean foundBrColor = false; boolean foundFontColor = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("border-color")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { properties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { properties.put("fontcolor", entry.getValue()); foundFontColor = true; } } if(!foundBrColor) { properties.put("bordercolor", defaultBrColor); } if(!foundFontColor) { properties.put("fontcolor", defaultFontColor); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "TextAnnotation"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); if(findOutgoingAssociation(plane, textAnnotation) != null) { generator.writeStartObject(); generator.writeObjectField("resourceId", findOutgoingAssociation(plane, textAnnotation).getId()); generator.writeEndObject(); } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, textAnnotation)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected void marshallGroup(Group group, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException{ Map<String, Object> properties = new LinkedHashMap<String, Object>(); if(group.getCategoryValueRef() != null && group.getCategoryValueRef().getValue() != null) { properties.put("name", unescapeXML(group.getCategoryValueRef().getValue())); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Group"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); if(findOutgoingAssociation(plane, group) != null) { generator.writeStartObject(); generator.writeObjectField("resourceId", findOutgoingAssociation(plane, group).getId()); generator.writeEndObject(); } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, group)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected Association findOutgoingAssociation(BPMNPlane plane, BaseElement baseElement) { Association result = _diagramAssociations.get(baseElement.getId()); if (result != null) { return result; } if (!(plane.getBpmnElement() instanceof Process)){ throw new IllegalArgumentException("Don't know how to get associations from a non-Process Diagram"); } Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getSourceRef() == baseElement){ _diagramAssociations.put(baseElement.getId(), association); return association; } } } return null; } protected List<Association> findOutgoingAssociations(BPMNPlane plane, BaseElement baseElement) { List<Association> retList = new ArrayList<Association>(); if (!(plane.getBpmnElement() instanceof Process)){ throw new IllegalArgumentException("Don't know how to get associations from a non-Process Diagram"); } Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getSourceRef() == baseElement){ retList.add(association); } } } return retList; } protected void marshallStencil(String stencilId, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencilId); generator.writeEndObject(); } private boolean isCustomElement(String taskType, String preProcessingData) { if(taskType != null && taskType.length() > 0 && preProcessingData != null && preProcessingData.length() > 0) { String[] preProcessingDataElements = preProcessingData.split( ",\\s*" ); for(String preProcessingDataElement : preProcessingDataElements) { if(taskType.equals(preProcessingDataElement)) { return true; } } } return false; } private static String unescapeXML(String str) { if (str == null || str.length() == 0) return ""; StringBuffer buf = new StringBuffer(); int len = str.length(); for (int i = 0; i < len; ++i) { char c = str.charAt(i); if (c == '&') { int pos = str.indexOf(";", i); if (pos == -1) { // Really evil buf.append('&'); } else if (str.charAt(i + 1) == '#') { int val = Integer.parseInt(str.substring(i + 2, pos), 16); buf.append((char) val); i = pos; } else { String substr = str.substring(i, pos + 1); if (substr.equals("&amp;")) buf.append('&'); else if (substr.equals("&lt;")) buf.append('<'); else if (substr.equals("&gt;")) buf.append('>'); else if (substr.equals("&quot;")) buf.append('"'); else if (substr.equals("&apos;")) buf.append('\''); else // ???? buf.append(substr); i = pos; } } else { buf.append(c); } } return buf.toString(); } private String updateReassignmentAndNotificationInput(String inputStr, String type) { if(inputStr != null && inputStr.length() > 0) { String ret = ""; String[] parts = inputStr.split( "\\^\\s*" ); for(String nextPart : parts) { ret += nextPart + "@" + type + "^"; } if(ret.endsWith("^")) { ret = ret.substring(0, ret.length() - 1); } return ret; } else { return ""; } } private void findBoundaryEvents(FlowElementsContainer flc, List<BoundaryEvent> boundaryList) { for(FlowElement fl : flc.getFlowElements()) { if(fl instanceof BoundaryEvent) { boundaryList.add((BoundaryEvent) fl); } if(fl instanceof FlowElementsContainer) { findBoundaryEvents((FlowElementsContainer) fl, boundaryList); } } } }
jbpm-designer-backend/src/main/java/org/jbpm/designer/bpmn2/impl/Bpmn2JsonMarshaller.java
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.designer.bpmn2.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import bpsim.*; import bpsim.impl.BpsimPackageImpl; import org.jboss.drools.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.eclipse.bpmn2.*; import org.eclipse.bpmn2.Error; import org.eclipse.bpmn2.Process; import org.eclipse.bpmn2.di.BPMNDiagram; import org.eclipse.bpmn2.di.BPMNEdge; import org.eclipse.bpmn2.di.BPMNPlane; import org.eclipse.bpmn2.di.BPMNShape; import org.eclipse.dd.dc.Bounds; import org.eclipse.dd.dc.Point; import org.eclipse.dd.di.DiagramElement; import org.eclipse.emf.ecore.util.FeatureMap; import org.jboss.drools.impl.DroolsPackageImpl; import org.jbpm.designer.web.profile.IDiagramProfile; /** * @author Antoine Toulme * @author Surdilovic * * a marshaller to transform BPMN 2.0 elements into JSON format. * */ public class Bpmn2JsonMarshaller { public static final String defaultBgColor_Activities = "#fafad2"; public static final String defaultBgColor_Events = "#f5deb3"; public static final String defaultBgColor_StartEvents = "#9acd32"; public static final String defaultBgColor_EndEvents = "#ff6347"; public static final String defaultBgColor_DataObjects = "#C0C0C0"; public static final String defaultBgColor_CatchingEvents = "#f5deb3"; public static final String defaultBgColor_ThrowingEvents = "#8cabff"; public static final String defaultBgColor_Gateways = "#f0e68c"; public static final String defaultBgColor_Swimlanes = "#ffffff"; public static final String defaultBrColor = "#000000"; public static final String defaultBrColor_CatchingEvents = "#a0522d"; public static final String defaultBrColor_ThrowingEvents = "#008cec"; public static final String defaultBrColor_Gateways = "#a67f00"; public static final String defaultFontColor = "#000000"; public static final String defaultSequenceflowColor = "#000000"; private static final List<String> defaultTypesList = Arrays.asList("Object", "Boolean", "Float", "Integer", "List", "String"); private Map<String, DiagramElement> _diagramElements = new HashMap<String, DiagramElement>(); private Map<String,Association> _diagramAssociations = new HashMap<String, Association>(); private Scenario _simulationScenario = null; private static final Logger _logger = LoggerFactory.getLogger(Bpmn2JsonMarshaller.class); private IDiagramProfile profile; private boolean coordianteManipulation = true; public void setProfile(IDiagramProfile profile) { this.profile = profile; } public String marshall(Definitions def, String preProcessingData) throws IOException { DroolsPackageImpl.init(); BpsimPackageImpl.init(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonFactory f = new JsonFactory(); JsonGenerator generator = f.createJsonGenerator(baos, JsonEncoding.UTF8); if(def.getRelationships() != null && def.getRelationships().size() > 0) { // current support for single relationship Relationship relationship = def.getRelationships().get(0); for(ExtensionAttributeValue extattrval : relationship.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<BPSimDataType> bpsimExtensions = (List<BPSimDataType>) extensionElements.get(BpsimPackage.Literals.DOCUMENT_ROOT__BP_SIM_DATA, true); if(bpsimExtensions != null && bpsimExtensions.size() > 0) { BPSimDataType processAnalysis = bpsimExtensions.get(0); if(processAnalysis.getScenario() != null && processAnalysis.getScenario().size() > 0) { _simulationScenario = processAnalysis.getScenario().get(0); } } } } if(preProcessingData == null || preProcessingData.length() < 1) { preProcessingData = "ReadOnlyService"; } // this is a temp way to determine if // coordinate system changes are necessary String bpmn2Exporter = def.getExporter(); String bpmn2ExporterVersion = def.getExporterVersion(); boolean haveExporter = bpmn2Exporter != null && bpmn2ExporterVersion != null; if(_simulationScenario != null && !haveExporter ) { coordianteManipulation = false; } marshallDefinitions(def, generator, preProcessingData); generator.close(); return baos.toString("UTF-8"); } private void linkSequenceFlows(List<FlowElement> flowElements) { Map<String, FlowNode> nodes = new HashMap<String, FlowNode>(); for (FlowElement flowElement: flowElements) { if (flowElement instanceof FlowNode) { nodes.put(flowElement.getId(), (FlowNode) flowElement); if (flowElement instanceof SubProcess) { linkSequenceFlows(((SubProcess) flowElement).getFlowElements()); } } } for (FlowElement flowElement: flowElements) { if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; if (sequenceFlow.getSourceRef() == null && sequenceFlow.getTargetRef() == null) { String id = sequenceFlow.getId(); try { String[] subids = id.split("-_"); String id1 = subids[0]; String id2 = "_" + subids[1]; FlowNode source = nodes.get(id1); if (source != null) { sequenceFlow.setSourceRef(source); } FlowNode target = nodes.get(id2); if (target != null) { sequenceFlow.setTargetRef(target); } } catch (Throwable t) { // Do nothing } } } } } protected void marshallDefinitions(Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException { try{ generator.writeStartObject(); generator.writeObjectField("resourceId", def.getId()); /** * "properties":{"name":"", * "documentation":"", * "auditing":"", * "monitoring":"", * "executable":"true", * "package":"com.sample", * "vardefs":"a,b,c,d", * "lanes" : "a,b,c", * "id":"", * "version":"", * "author":"", * "language":"", * "namespaces":"", * "targetnamespace":"", * "expressionlanguage":"", * "typelanguage":"", * "creationdate":"", * "modificationdate":"" * } */ Map<String, Object> props = new LinkedHashMap<String, Object>(); props.put("namespaces", ""); //props.put("targetnamespace", def.getTargetNamespace()); props.put("targetnamespace", "http://www.omg.org/bpmn20"); props.put("typelanguage", def.getTypeLanguage()); props.put("name",unescapeXML(def.getName())); props.put("id", def.getId()); props.put("expressionlanguage", def.getExpressionLanguage()); // backwards compat for BZ 1048191 if( def.getDocumentation() != null && def.getDocumentation().size() > 0 ) { props.put("documentation", def.getDocumentation().get(0).getText()); } for (RootElement rootElement : def.getRootElements()) { if (rootElement instanceof Process) { // have to wait for process node to finish properties and stencil marshalling props.put("executable", ((Process) rootElement).isIsExecutable() + ""); props.put("id", rootElement.getId()); if( rootElement.getDocumentation() != null && rootElement.getDocumentation().size() > 0 ) { props.put("documentation", rootElement.getDocumentation().get(0).getText()); } Process pr = (Process) rootElement; if(pr.getName() != null && pr.getName().length() > 0) { props.put("processn", unescapeXML(((Process) rootElement).getName())); } List<Property> processProperties = ((Process) rootElement).getProperties(); if(processProperties != null && processProperties.size() > 0) { String propVal = ""; for(int i=0; i<processProperties.size(); i++) { Property p = processProperties.get(i); propVal += p.getId(); // check the structureRef value if(p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) { propVal += ":" + p.getItemSubjectRef().getStructureRef(); } if(i != processProperties.size()-1) { propVal += ","; } } props.put("vardefs", propVal); } // packageName and version and adHoc are jbpm-specific extension attribute Iterator<FeatureMap.Entry> iter = ((Process) rootElement).getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("packageName")) { props.put("package", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("version")) { props.put("version", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("adHoc")) { props.put("adhocprocess", entry.getValue()); } } // process imports, custom description and globals extension elements String allImports = ""; if((rootElement).getExtensionValues() != null && (rootElement).getExtensionValues().size() > 0) { String importsStr = ""; String globalsStr = ""; for(ExtensionAttributeValue extattrval : rootElement.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<ImportType> importExtensions = (List<ImportType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__IMPORT, true); @SuppressWarnings("unchecked") List<GlobalType> globalExtensions = (List<GlobalType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__GLOBAL, true); List<MetaDataType> metadataExtensions = (List<MetaDataType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__META_DATA, true); for(ImportType importType : importExtensions) { importsStr += importType.getName(); importsStr += "|default,"; } for(GlobalType globalType : globalExtensions) { globalsStr += (globalType.getIdentifier() + ":" + globalType.getType()); globalsStr += ","; } for(MetaDataType metaType : metadataExtensions) { props.put("customdescription", metaType.getMetaValue()); } } allImports += importsStr; if(globalsStr.length() > 0) { if(globalsStr.endsWith(",")) { globalsStr = globalsStr.substring(0, globalsStr.length() - 1); } props.put("globals", globalsStr); } } // definitions imports (wsdl) List<org.eclipse.bpmn2.Import> wsdlImports = def.getImports(); if(wsdlImports != null) { for(org.eclipse.bpmn2.Import imp : wsdlImports) { allImports += imp.getLocation() + "|" + imp.getNamespace() + "|wsdl,"; } } if(allImports.endsWith(",")) { allImports = allImports.substring(0, allImports.length() - 1); } props.put("imports", allImports); // simulation if(_simulationScenario != null && _simulationScenario.getScenarioParameters() != null) { props.put("currency", _simulationScenario.getScenarioParameters().getBaseCurrencyUnit() == null ? "" : _simulationScenario.getScenarioParameters().getBaseCurrencyUnit()); props.put("timeunit", _simulationScenario.getScenarioParameters().getBaseTimeUnit().getName()); } marshallProperties(props, generator); marshallStencil("BPMNDiagram", generator); linkSequenceFlows(((Process) rootElement).getFlowElements()); marshallProcess((Process) rootElement, def, generator, preProcessingData); } else if (rootElement instanceof Interface) { // TODO } else if (rootElement instanceof ItemDefinition) { // TODO } else if (rootElement instanceof Resource) { // TODO } else if (rootElement instanceof Error) { // TODO } else if (rootElement instanceof Message) { // TODO } else if (rootElement instanceof Signal) { // TODO } else if (rootElement instanceof Escalation) { // TODO } else if (rootElement instanceof Collaboration) { } else { _logger.warn("Unknown root element " + rootElement + ". This element will not be parsed."); } } generator.writeObjectFieldStart("stencilset"); generator.writeObjectField("url", this.profile.getStencilSetURL()); generator.writeObjectField("namespace", this.profile.getStencilSetNamespaceURL()); generator.writeEndObject(); generator.writeArrayFieldStart("ssextensions"); generator.writeObject(this.profile.getStencilSetExtensionURL()); generator.writeEndArray(); generator.writeEndObject(); } finally { _diagramElements.clear(); } } /** protected void marshallMessage(Message message, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); generator.writeStartObject(); generator.writeObjectField("resourceId", message.getId()); properties.put("name", message.getName()); if(message.getDocumentation() != null && message.getDocumentation().size() > 0) { properties.put("documentation", message.getDocumentation().get(0).getText()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Message"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeEndArray(); generator.writeEndObject(); } **/ protected void marshallCallableElement(CallableElement callableElement, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", callableElement.getId()); if (callableElement instanceof Choreography) { marshallChoreography((Choreography) callableElement, generator); } else if (callableElement instanceof Conversation) { marshallConversation((Conversation) callableElement, generator); } else if (callableElement instanceof GlobalChoreographyTask) { marshallGlobalChoreographyTask((GlobalChoreographyTask) callableElement, generator); } else if (callableElement instanceof GlobalTask) { marshallGlobalTask((GlobalTask) callableElement, generator); } else if (callableElement instanceof Process) { marshallProcess((Process) callableElement, def, generator, ""); } else { throw new UnsupportedOperationException("TODO"); //TODO! } generator.writeEndObject(); } protected void marshallProcess(Process process, Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException { BPMNPlane plane = null; for (BPMNDiagram d: def.getDiagrams()) { if (d != null) { BPMNPlane p = d.getPlane(); if (p != null) { if (p.getBpmnElement() == process) { plane = p; break; } } } } if (plane == null) { throw new IllegalArgumentException("Could not find BPMNDI information"); } generator.writeArrayFieldStart("childShapes"); List<String> laneFlowElementsIds = new ArrayList<String>(); for(LaneSet laneSet : process.getLaneSets()) { for(Lane lane : laneSet.getLanes()) { // we only want to marshall lanes if we have the bpmndi info for them! if(findDiagramElement(plane, lane) != null) { laneFlowElementsIds.addAll( marshallLanes(lane, plane, generator, 0, 0, preProcessingData, def) ); } } } for (FlowElement flowElement: process.getFlowElements()) { if( !laneFlowElementsIds.contains(flowElement.getId()) ) { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } for (Artifact artifact: process.getArtifacts()) { marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def); } generator.writeEndArray(); } private void setCatchEventProperties(CatchEvent event, Map<String, Object> properties) { if(event.getOutputSet() != null) { List<DataOutput> dataOutputs = event.getOutputSet().getDataOutputRefs(); StringBuffer doutbuff = new StringBuffer(); for(DataOutput dout : dataOutputs) { doutbuff.append(dout.getName()); doutbuff.append(","); } if(doutbuff.length() > 0) { doutbuff.setLength(doutbuff.length() - 1); } properties.put("dataoutput", doutbuff.toString()); List<DataOutputAssociation> outputAssociations = event.getDataOutputAssociation(); StringBuffer doutassociationbuff = new StringBuffer(); for(DataOutputAssociation doa : outputAssociations) { String doaName = ((DataOutput)doa.getSourceRef().get(0)).getName(); if(doaName != null && doaName.length() > 0) { doutassociationbuff.append("[dout]" + ((DataOutput)doa.getSourceRef().get(0)).getName()); doutassociationbuff.append("->"); doutassociationbuff.append(doa.getTargetRef().getId()); doutassociationbuff.append(","); } } if(doutassociationbuff.length() > 0) { doutassociationbuff.setLength(doutassociationbuff.length() - 1); } properties.put("dataoutputassociations", doutassociationbuff.toString()); } // event definitions List<EventDefinition> eventdefs = event.getEventDefinitions(); for(EventDefinition ed : eventdefs) { if(ed instanceof TimerEventDefinition) { TimerEventDefinition ted = (TimerEventDefinition) ed; // if(ted.getTimeDate() != null) { // properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody()); // } if(ted.getTimeDuration() != null) { properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody()); } if(ted.getTimeCycle() != null) { properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody()); if(((FormalExpression) ted.getTimeCycle()).getLanguage() != null) { properties.put("timecyclelanguage", ((FormalExpression) ted.getTimeCycle()).getLanguage()); } } } else if( ed instanceof SignalEventDefinition) { if(((SignalEventDefinition) ed).getSignalRef() != null) { properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef()); } else { properties.put("signalref", ""); } } else if( ed instanceof ErrorEventDefinition) { if(((ErrorEventDefinition) ed).getErrorRef() != null && ((ErrorEventDefinition) ed).getErrorRef().getErrorCode() != null) { properties.put("errorref", ((ErrorEventDefinition) ed).getErrorRef().getErrorCode()); } else { properties.put("errorref", ""); } } else if( ed instanceof ConditionalEventDefinition ) { FormalExpression conditionalExp = (FormalExpression) ((ConditionalEventDefinition) ed).getCondition(); if(conditionalExp.getBody() != null) { properties.put("conditionexpression", conditionalExp.getBody().replaceAll("\n", "\\\\n")); } if(conditionalExp.getLanguage() != null) { String languageVal = conditionalExp.getLanguage(); if(languageVal.equals("http://www.jboss.org/drools/rule")) { properties.put("conditionlanguage", "drools"); } else if(languageVal.equals("http://www.mvel.org/2.0")) { properties.put("conditionlanguage", "mvel"); } else { // default to drools properties.put("conditionlanguage", "drools"); } } } else if( ed instanceof EscalationEventDefinition ) { if(((EscalationEventDefinition) ed).getEscalationRef() != null) { Escalation esc = ((EscalationEventDefinition) ed).getEscalationRef(); if(esc.getEscalationCode() != null && esc.getEscalationCode().length() > 0) { properties.put("escalationcode", esc.getEscalationCode()); } else { properties.put("escalationcode", ""); } } } else if( ed instanceof MessageEventDefinition) { if(((MessageEventDefinition) ed).getMessageRef() != null) { Message msg = ((MessageEventDefinition) ed).getMessageRef(); properties.put("messageref", msg.getId()); } } else if( ed instanceof CompensateEventDefinition) { if(((CompensateEventDefinition) ed).getActivityRef() != null) { Activity act = ((CompensateEventDefinition) ed).getActivityRef(); properties.put("activityref", act.getName()); } } } } private void setThrowEventProperties(ThrowEvent event, Map<String, Object> properties) { if(event.getInputSet() != null) { List<DataInput> dataInputs = event.getInputSet().getDataInputRefs(); StringBuffer dinbuff = new StringBuffer(); for(DataInput din : dataInputs) { dinbuff.append(din.getName()); dinbuff.append(","); } if(dinbuff.length() > 0) { dinbuff.setLength(dinbuff.length() - 1); } properties.put("datainput", dinbuff.toString()); List<DataInputAssociation> inputAssociations = event.getDataInputAssociation(); StringBuffer dinassociationbuff = new StringBuffer(); for(DataInputAssociation din : inputAssociations) { if(din.getSourceRef().get(0).getId() != null && din.getSourceRef().get(0).getId().length() > 0) { dinassociationbuff.append("[din]" + din.getSourceRef().get(0).getId()); dinassociationbuff.append("->"); dinassociationbuff.append( ((DataInput)din.getTargetRef()).getName()); dinassociationbuff.append(","); } } if(dinassociationbuff.length() > 0) { dinassociationbuff.setLength(dinassociationbuff.length() - 1); } properties.put("datainputassociations", dinassociationbuff.toString()); } // event definitions List<EventDefinition> eventdefs = event.getEventDefinitions(); for(EventDefinition ed : eventdefs) { if(ed instanceof TimerEventDefinition) { TimerEventDefinition ted = (TimerEventDefinition) ed; // if(ted.getTimeDate() != null) { // properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody()); // } if(ted.getTimeDuration() != null) { properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody()); } if(ted.getTimeCycle() != null) { properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody()); if(((FormalExpression) ted.getTimeCycle()).getLanguage() != null) { properties.put("timecyclelanguage", ((FormalExpression) ted.getTimeCycle()).getLanguage()); } } } else if( ed instanceof SignalEventDefinition) { if(((SignalEventDefinition) ed).getSignalRef() != null) { properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef()); } else { properties.put("signalref", ""); } } else if( ed instanceof ErrorEventDefinition) { if(((ErrorEventDefinition) ed).getErrorRef() != null && ((ErrorEventDefinition) ed).getErrorRef().getErrorCode() != null) { properties.put("errorref", ((ErrorEventDefinition) ed).getErrorRef().getErrorCode()); } else { properties.put("errorref", ""); } } else if( ed instanceof ConditionalEventDefinition ) { FormalExpression conditionalExp = (FormalExpression) ((ConditionalEventDefinition) ed).getCondition(); if(conditionalExp.getBody() != null) { properties.put("conditionexpression", conditionalExp.getBody()); } if(conditionalExp.getLanguage() != null) { String languageVal = conditionalExp.getLanguage(); if(languageVal.equals("http://www.jboss.org/drools/rule")) { properties.put("conditionlanguage", "drools"); } else if(languageVal.equals("http://www.mvel.org/2.0")) { properties.put("conditionlanguage", "mvel"); } else { // default to drools properties.put("conditionlanguage", "drools"); } } } else if( ed instanceof EscalationEventDefinition ) { if(((EscalationEventDefinition) ed).getEscalationRef() != null) { Escalation esc = ((EscalationEventDefinition) ed).getEscalationRef(); if(esc.getEscalationCode() != null && esc.getEscalationCode().length() > 0) { properties.put("escalationcode", esc.getEscalationCode()); } else { properties.put("escalationcode", ""); } } } else if( ed instanceof MessageEventDefinition) { if(((MessageEventDefinition) ed).getMessageRef() != null) { Message msg = ((MessageEventDefinition) ed).getMessageRef(); properties.put("messageref", msg.getId()); } } else if( ed instanceof CompensateEventDefinition) { if(((CompensateEventDefinition) ed).getActivityRef() != null) { Activity act = ((CompensateEventDefinition) ed).getActivityRef(); properties.put("activityref", act.getName()); } } } } private List<String> marshallLanes(Lane lane, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { Bounds bounds = ((BPMNShape) findDiagramElement(plane, lane)).getBounds(); List<String> nodeRefIds = new ArrayList<String>(); if(bounds != null) { generator.writeStartObject(); generator.writeObjectField("resourceId", lane.getId()); Map<String, Object> laneProperties = new LinkedHashMap<String, Object>(); if(lane.getName() != null) { laneProperties.put("name", unescapeXML(lane.getName())); } else { laneProperties.put("name", ""); } Iterator<FeatureMap.Entry> iter = lane.getAnyAttribute().iterator(); boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("background-color")) { laneProperties.put("bgcolor", entry.getValue()); foundBgColor = true; } if(entry.getEStructuralFeature().getName().equals("border-color")) { laneProperties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { laneProperties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { laneProperties.put("fontcolor", entry.getValue()); foundFontColor = true; } if(entry.getEStructuralFeature().getName().equals("selectable")) { laneProperties.put("isselectable", entry.getValue()); foundSelectable = true; } } if(!foundBgColor) { laneProperties.put("bgcolor", defaultBgColor_Swimlanes); } if(!foundBrColor) { laneProperties.put("bordercolor", defaultBrColor); } if(!foundFontColor) { laneProperties.put("fontcolor", defaultFontColor); } if(!foundSelectable) { laneProperties.put("isselectable", "true"); } marshallProperties(laneProperties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Lane"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); for (FlowElement flowElement: lane.getFlowNodeRefs()) { nodeRefIds.add(flowElement.getId()); if(coordianteManipulation) { marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeEndArray(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); generator.writeEndObject(); } else { // dont marshall the lane unless it has BPMNDI info (eclipse editor does not generate it for lanes currently. for (FlowElement flowElement: lane.getFlowNodeRefs()) { nodeRefIds.add(flowElement.getId()); // we dont want an offset here! marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } return nodeRefIds; } protected void marshallFlowElement(FlowElement flowElement, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", flowElement.getId()); Map<String, Object> flowElementProperties = new LinkedHashMap<String, Object>(); Iterator<FeatureMap.Entry> iter = flowElement.getAnyAttribute().iterator(); boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("background-color")) { flowElementProperties.put("bgcolor", entry.getValue()); foundBgColor = true; } if(entry.getEStructuralFeature().getName().equals("border-color")) { flowElementProperties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { flowElementProperties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { flowElementProperties.put("fontcolor", entry.getValue()); foundFontColor = true; } if(entry.getEStructuralFeature().getName().equals("selectable")) { flowElementProperties.put("isselectable", entry.getValue()); foundSelectable = true; } } if(!foundBgColor) { if(flowElement instanceof Activity || flowElement instanceof SubProcess ) { flowElementProperties.put("bgcolor", defaultBgColor_Activities); } else if(flowElement instanceof StartEvent) { flowElementProperties.put("bgcolor", defaultBgColor_StartEvents); } else if(flowElement instanceof EndEvent) { flowElementProperties.put("bgcolor", defaultBgColor_EndEvents); } else if(flowElement instanceof DataObject) { flowElementProperties.put("bgcolor", defaultBgColor_DataObjects); } else if(flowElement instanceof CatchEvent) { flowElementProperties.put("bgcolor", defaultBgColor_CatchingEvents); } else if(flowElement instanceof ThrowEvent) { flowElementProperties.put("bgcolor", defaultBgColor_ThrowingEvents); } else if(flowElement instanceof Gateway) { flowElementProperties.put("bgcolor", defaultBgColor_Gateways); } else if(flowElement instanceof Lane) { flowElementProperties.put("bgcolor", defaultBgColor_Swimlanes); } else { flowElementProperties.put("bgcolor", defaultBgColor_Events); } } if(!foundBrColor) { if(flowElement instanceof CatchEvent && !(flowElement instanceof StartEvent)) { flowElementProperties.put("bordercolor", defaultBrColor_CatchingEvents); } else if(flowElement instanceof ThrowEvent && !(flowElement instanceof EndEvent)) { flowElementProperties.put("bordercolor", defaultBrColor_ThrowingEvents); } else if(flowElement instanceof Gateway) { flowElementProperties.put("bordercolor", defaultBrColor_Gateways); } else { flowElementProperties.put("bordercolor", defaultBrColor); } } if(!foundFontColor) { flowElementProperties.put("fontcolor", defaultFontColor); } if(!foundSelectable) { flowElementProperties.put("isselectable", "true"); } Map<String, Object> catchEventProperties = new LinkedHashMap<String, Object>(flowElementProperties); Map<String, Object> throwEventProperties = new LinkedHashMap<String, Object>(flowElementProperties); if(flowElement instanceof CatchEvent) { setCatchEventProperties((CatchEvent) flowElement, catchEventProperties); } if(flowElement instanceof ThrowEvent) { setThrowEventProperties((ThrowEvent) flowElement, throwEventProperties); } if (flowElement instanceof StartEvent) { marshallStartEvent((StartEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof EndEvent) { marshallEndEvent((EndEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties); } else if (flowElement instanceof IntermediateThrowEvent) { marshallIntermediateThrowEvent((IntermediateThrowEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties); } else if (flowElement instanceof IntermediateCatchEvent) { marshallIntermediateCatchEvent((IntermediateCatchEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof BoundaryEvent) { marshallBoundaryEvent((BoundaryEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties); } else if (flowElement instanceof Task) { marshallTask((Task) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties); } else if (flowElement instanceof SequenceFlow) { marshallSequenceFlow((SequenceFlow) flowElement, plane, generator, xOffset, yOffset); } else if (flowElement instanceof ParallelGateway) { marshallParallelGateway((ParallelGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof ExclusiveGateway) { marshallExclusiveGateway((ExclusiveGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof InclusiveGateway) { marshallInclusiveGateway((InclusiveGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof EventBasedGateway) { marshallEventBasedGateway((EventBasedGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof ComplexGateway) { marshallComplexGateway((ComplexGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof CallActivity) { marshallCallActivity((CallActivity) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else if (flowElement instanceof SubProcess) { if(flowElement instanceof AdHocSubProcess) { marshallSubProcess((AdHocSubProcess) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties); } else { marshallSubProcess((SubProcess) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties); } } else if (flowElement instanceof DataObject) { // only marshall if we can find DI info for it - BZ 800346 if(findDiagramElement(plane, (DataObject) flowElement) != null) { marshallDataObject((DataObject) flowElement, plane, generator, xOffset, yOffset, flowElementProperties); } else { _logger.info("Could not marshall Data Object " + (DataObject) flowElement + " because no DI information could be found."); } } else { throw new UnsupportedOperationException("Unknown flow element " + flowElement); } generator.writeEndObject(); } protected void marshallStartEvent(StartEvent startEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = startEvent.getEventDefinitions(); properties.put("isinterrupting", startEvent.isIsInterrupting()); if (eventDefinitions == null || eventDefinitions.size() == 0) { marshallNode(startEvent, properties, "StartNoneEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof ConditionalEventDefinition) { marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof SignalEventDefinition) { marshallNode(startEvent, properties, "StartSignalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(startEvent, properties, "StartMessageEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(startEvent, properties, "StartTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(startEvent, properties, "StartErrorEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof ConditionalEventDefinition) { marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof EscalationEventDefinition) { marshallNode(startEvent, properties, "StartEscalationEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof CompensateEventDefinition) { marshallNode(startEvent, properties, "StartCompensationEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Multiple event definitions not supported for start event"); } } protected void marshallEndEvent(EndEvent endEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = endEvent.getEventDefinitions(); if (eventDefinitions == null || eventDefinitions.size() == 0) { marshallNode(endEvent, properties, "EndNoneEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof TerminateEventDefinition) { marshallNode(endEvent, properties, "EndTerminateEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof SignalEventDefinition) { marshallNode(endEvent, properties, "EndSignalEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(endEvent, properties, "EndMessageEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(endEvent, properties, "EndErrorEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(endEvent, properties, "EndEscalationEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(endEvent, properties, "EndCompensationEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof CancelEventDefinition) { marshallNode(endEvent, properties, "EndCancelEvent", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Multiple event definitions not supported for end event"); } } protected void marshallIntermediateCatchEvent(IntermediateCatchEvent catchEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = catchEvent.getEventDefinitions(); // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(catchEvent.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); if (processingTime == null) { continue; } ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 has not support for random distribution type // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } } } } if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(catchEvent, properties, "IntermediateSignalEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(catchEvent, properties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(catchEvent, properties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ConditionalEventDefinition) { marshallNode(catchEvent, properties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof ErrorEventDefinition) { marshallNode(catchEvent, properties, "IntermediateErrorEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof EscalationEventDefinition) { marshallNode(catchEvent, properties, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof CompensateEventDefinition) { marshallNode(catchEvent, properties, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("Intermediate catch event does not have event definition."); } } protected void marshallBoundaryEvent(BoundaryEvent boundaryEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> catchEventProperties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = boundaryEvent.getEventDefinitions(); if(boundaryEvent.isCancelActivity()) { catchEventProperties.put("boundarycancelactivity", "true"); } else { catchEventProperties.put("boundarycancelactivity", "false"); } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(boundaryEvent.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); if (processingTime == null) { continue; } ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; catchEventProperties.put("mean", ndt.getMean()); catchEventProperties.put("standarddeviation", ndt.getStandardDeviation()); catchEventProperties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; catchEventProperties.put("min", udt.getMin()); catchEventProperties.put("max", udt.getMax()); catchEventProperties.put("distributiontype", "uniform"); // bpsim 1.0 has not support for random distribution type // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; catchEventProperties.put("mean", pdt.getMean()); catchEventProperties.put("distributiontype", "poisson"); } ControlParameters controlParams = eleType.getControlParameters(); if(controlParams != null) { Parameter probabilityParam = controlParams.getProbability(); if(probabilityParam != null && probabilityParam.getParameterValue() != null) { FloatingParameterType valType = (FloatingParameterType) probabilityParam.getParameterValue().get(0); catchEventProperties.put("probability", valType.getValue()); } } } } } if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateSignalEventCatching", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof ErrorEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateErrorEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof TimerEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof ConditionalEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset); } else if(eventDefinition instanceof MessageEventDefinition) { marshallNode(boundaryEvent, catchEventProperties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset); }else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for boundary event"); } } protected void marshallIntermediateThrowEvent(IntermediateThrowEvent throwEvent, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException { List<EventDefinition> eventDefinitions = throwEvent.getEventDefinitions(); // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(throwEvent.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); if (processingTime == null) { continue; } ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 has not support for random distribution type // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } } } } if (eventDefinitions.size() == 0) { marshallNode(throwEvent, properties, "IntermediateEvent", plane, generator, xOffset, yOffset); } else if (eventDefinitions.size() == 1) { EventDefinition eventDefinition = eventDefinitions.get(0); if (eventDefinition instanceof SignalEventDefinition) { marshallNode(throwEvent, properties, "IntermediateSignalEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof MessageEventDefinition) { marshallNode(throwEvent, properties, "IntermediateMessageEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof EscalationEventDefinition) { marshallNode(throwEvent, properties, "IntermediateEscalationEventThrowing", plane, generator, xOffset, yOffset); } else if (eventDefinition instanceof CompensateEventDefinition) { marshallNode(throwEvent, properties, "IntermediateCompensationEventThrowing", plane, generator, xOffset, yOffset); } else { throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition); } } else { throw new UnsupportedOperationException("None or multiple event definitions not supported for intermediate throw event"); } } protected void marshallCallActivity(CallActivity callActivity, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); Iterator<FeatureMap.Entry> iter = callActivity.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("independent")) { properties.put("independent", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("waitForCompletion")) { properties.put("waitforcompletion", entry.getValue()); } } if(callActivity.getCalledElement() != null && callActivity.getCalledElement().length() > 0) { properties.put("calledelement", callActivity.getCalledElement()); } // data inputs if(callActivity.getIoSpecification() != null) { List<InputSet> inputSetList = callActivity.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { if(dataIn.getName() != null) { dataInBuffer.append(dataIn.getName()); if(dataIn.getItemSubjectRef() != null && dataIn.getItemSubjectRef().getStructureRef() != null && dataIn.getItemSubjectRef().getStructureRef().length() > 0) { dataInBuffer.append(":").append(dataIn.getItemSubjectRef().getStructureRef()); } dataInBuffer.append(","); } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(callActivity.getIoSpecification() != null) { List<OutputSet> outputSetList = callActivity.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { dataOutBuffer.append(dataOut.getName()); if(dataOut.getItemSubjectRef() != null && dataOut.getItemSubjectRef().getStructureRef() != null && dataOut.getItemSubjectRef().getStructureRef().length() > 0) { dataOutBuffer.append(":").append(dataOut.getItemSubjectRef().getStructureRef()); } dataOutBuffer.append(","); } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = callActivity.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = callActivity.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); //List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } // else { // // check if this is a bi-directional association // for(DataOutputAssociation dataout : outputAssociations) { // if(dataout.getTargetRef().getId().equals(lhsAssociation) && // ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { // isBiDirectional = true; // break; // } // } // } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } String replacer = associationValue.replaceAll(",", "##"); associationBuff.append(rhsAssociation).append("=").append(replacer); associationBuff.append(","); } } // else if(isBiDirectional) { // associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); // associationBuff.append(","); // biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } } } for(DataOutputAssociation dataout : outputAssociations) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional // for(String bda : biDirectionalAssociations) { // String[] dbaparts = bda.split( ",\\s*" ); // if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { // wasBiDirectional = true; // break; // } // } if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) { rhsAssociation = dataout.getTransformation().getBody().replaceAll("=", "||"); } if(!wasBiDirectional) { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[dout]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); } } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions if(callActivity.getExtensionValues() != null && callActivity.getExtensionValues().size() > 0) { String onEntryStr = ""; String onExitStr = ""; for(ExtensionAttributeValue extattrval : callActivity.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true); @SuppressWarnings("unchecked") List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true); for(OnEntryScriptType onEntryScript : onEntryExtensions) { onEntryStr += onEntryScript.getScript(); onEntryStr += "|"; if(onEntryScript.getScriptFormat() != null) { String format = onEntryScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } properties.put("script_language", formatToWrite); } } for(OnExitScriptType onExitScript : onExitExtensions) { onExitStr += onExitScript.getScript(); onExitStr += "|"; if(onExitScript.getScriptFormat() != null) { String format = onExitScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } if(properties.get("script_language") == null) { properties.put("script_language", formatToWrite); } } } } if(onEntryStr.length() > 0) { if(onEntryStr.endsWith("|")) { onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1); } properties.put("onentryactions", onEntryStr); } if(onExitStr.length() > 0) { if(onExitStr.endsWith("|")) { onExitStr = onExitStr.substring(0, onExitStr.length() - 1); } properties.put("onexitactions", onExitStr); } } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(callActivity.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 does not support random distribution // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } if(timeParams.getWaitTime() != null) { FloatingParameterType waittimeType = (FloatingParameterType) timeParams.getWaitTime().getParameterValue().get(0); properties.put("waittime", waittimeType.getValue()); } CostParameters costParams = eleType.getCostParameters(); if(costParams != null) { if(costParams.getUnitCost() != null) { FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); } // bpsim 1.0 does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); } } } } marshallNode(callActivity, properties, "ReusableSubprocess", plane, generator, xOffset, yOffset); } protected void marshallTask(Task task, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); String taskType = "None"; if (task instanceof BusinessRuleTask) { taskType = "Business Rule"; Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("ruleFlowGroup")) { properties.put("ruleflowgroup", entry.getValue()); } } } else if (task instanceof ScriptTask) { ScriptTask scriptTask = (ScriptTask) task; properties.put("script", scriptTask.getScript() != null ? scriptTask.getScript().replace("\\", "\\\\").replace("\n", "\\n") : ""); String format = scriptTask.getScriptFormat(); if(format != null && format.length() > 0) { String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { // default to java formatToWrite = "java"; } properties.put("script_language", formatToWrite); } taskType = "Script"; } else if (task instanceof ServiceTask) { taskType = "Service"; ServiceTask serviceTask = (ServiceTask) task; if(serviceTask.getOperationRef() != null && serviceTask.getImplementation() != null) { properties.put("serviceimplementation", serviceTask.getImplementation()); properties.put("serviceoperation", serviceTask.getOperationRef().getName() == null ? serviceTask.getOperationRef().getImplementationRef() : serviceTask.getOperationRef().getName()); if(def != null) { List<RootElement> roots = def.getRootElements(); for(RootElement root : roots) { if(root instanceof Interface) { Interface inter = (Interface) root; List<Operation> interOperations = inter.getOperations(); for(Operation interOper : interOperations) { if(interOper.getId().equals(serviceTask.getOperationRef().getId())) { properties.put("serviceinterface", inter.getName() == null ? inter.getImplementationRef() : inter.getName()); } } } } } } } else if (task instanceof ManualTask) { taskType = "Manual"; } else if (task instanceof UserTask) { taskType = "User"; // get the user task actors List<ResourceRole> roles = task.getResources(); StringBuilder sb = new StringBuilder(); for(ResourceRole role : roles) { if(role instanceof PotentialOwner) { FormalExpression fe = (FormalExpression) ( (PotentialOwner)role).getResourceAssignmentExpression().getExpression(); if(fe.getBody() != null && fe.getBody().length() > 0) { sb.append(fe.getBody()); sb.append(","); } } } if(sb.length() > 0) { sb.setLength(sb.length() - 1); } properties.put("actors", sb.toString()); // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(task.getId())) { CostParameters costParams = eleType.getCostParameters(); FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); // bpsim does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); ResourceParameters resourceParams = eleType.getResourceParameters(); FloatingParameterType quantityVal = (FloatingParameterType) resourceParams.getQuantity().getParameterValue().get(0); properties.put("quantity", quantityVal.getValue()); FloatingParameterType workingHoursVal = (FloatingParameterType) resourceParams.getAvailability().getParameterValue().get(0); properties.put("workinghours", workingHoursVal.getValue()); } } } } else if (task instanceof SendTask) { taskType = "Send"; SendTask st = (SendTask) task; if(st.getMessageRef() != null) { properties.put("messageref", st.getMessageRef().getId()); } } else if (task instanceof ReceiveTask) { taskType = "Receive"; ReceiveTask rt = (ReceiveTask) task; if(rt.getMessageRef() != null) { properties.put("messageref", rt.getMessageRef().getId()); } } // backwards compatibility with jbds editor boolean foundTaskName = false; if(task.getIoSpecification() != null && task.getIoSpecification().getDataInputs() != null) { List<DataInput> taskDataInputs = task.getIoSpecification().getDataInputs(); for(DataInput din : taskDataInputs) { if(din.getName() != null && din.getName().equals("TaskName")) { List<DataInputAssociation> taskDataInputAssociations = task.getDataInputAssociations(); for(DataInputAssociation dia : taskDataInputAssociations) { if(dia.getTargetRef() != null && dia.getTargetRef().getId().equals(din.getId())) { properties.put("taskname", ((FormalExpression) dia.getAssignment().get(0).getFrom()).getBody()); foundTaskName = true; } } break; } } } if(!foundTaskName) { // try the drools specific attribute set on the task Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("taskName")) { String tname = (String) entry.getValue(); if(tname != null && tname.length() > 0) { properties.put("taskname", tname); } } } } // check if we are dealing with a custom task if(isCustomElement((String) properties.get("taskname"), preProcessingData)) { properties.put("tasktype", properties.get("taskname")); } else { properties.put("tasktype", taskType); } // multiple instance if(task.getLoopCharacteristics() != null) { properties.put("multipleinstance", "true"); MultiInstanceLoopCharacteristics taskmi = (MultiInstanceLoopCharacteristics) task.getLoopCharacteristics(); if(taskmi.getLoopDataInputRef() != null) { ItemAwareElement iedatainput = taskmi.getLoopDataInputRef(); List<DataInputAssociation> taskInputAssociations = task.getDataInputAssociations(); for(DataInputAssociation dia : taskInputAssociations) { if(dia.getTargetRef().equals(iedatainput)) { properties.put("multipleinstancecollectioninput", dia.getSourceRef().get(0).getId()); break; } } } if(taskmi.getLoopDataOutputRef() != null) { ItemAwareElement iedataoutput = taskmi.getLoopDataOutputRef(); List<DataOutputAssociation> taskOutputAssociations = task.getDataOutputAssociations(); for(DataOutputAssociation dout : taskOutputAssociations) { if(dout.getSourceRef().get(0).equals(iedataoutput)) { properties.put("multipleinstancecollectionoutput", dout.getTargetRef().getId()); break; } } } if(taskmi.getInputDataItem() != null && taskmi.getInputDataItem().getItemSubjectRef() != null) { List<DataInput> taskDataInputs = task.getIoSpecification().getDataInputs(); for(DataInput din: taskDataInputs) { if(din != null && din.getItemSubjectRef() != null && taskmi.getInputDataItem() != null && taskmi.getInputDataItem().getItemSubjectRef() != null ) { if(din.getItemSubjectRef().getId().equals(taskmi.getInputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedatainput", din.getName()); } } } } if(taskmi.getOutputDataItem() != null && taskmi.getOutputDataItem().getItemSubjectRef() != null) { List<DataOutput> taskDataOutputs = task.getIoSpecification().getDataOutputs(); for(DataOutput dout : taskDataOutputs) { if(dout != null && dout.getItemSubjectRef() != null && taskmi.getOutputDataItem() != null && taskmi.getOutputDataItem().getItemSubjectRef() != null) { if(dout.getItemSubjectRef().getId().equals(taskmi.getOutputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedataoutput", dout.getName()); } } } } if(taskmi.getCompletionCondition() != null) { if (taskmi.getCompletionCondition() instanceof FormalExpression) { properties.put("multipleinstancecompletioncondition", ((FormalExpression)taskmi.getCompletionCondition()).getBody()); } } } else { properties.put("multipleinstance", "false"); } // data inputs DataInput groupDataInput = null; DataInput skippableDataInput = null; DataInput commentDataInput = null; DataInput contentDataInput = null; DataInput priorityDataInput = null; DataInput localeDataInput = null; DataInput createdByDataInput = null; DataInput notCompletedReassignInput = null; DataInput notStartedReassignInput = null; DataInput notCompletedNotificationInput = null; DataInput notStartedNotificationInput = null; if(task.getIoSpecification() != null) { List<InputSet> inputSetList = task.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { // dont add "TaskName" as that is added manually if(dataIn.getName() != null && !dataIn.getName().equals("TaskName") && !dataIn.getName().equals("miinputCollection")) { dataInBuffer.append(dataIn.getName()); if(dataIn.getItemSubjectRef() != null && dataIn.getItemSubjectRef().getStructureRef() != null && dataIn.getItemSubjectRef().getStructureRef().length() > 0) { dataInBuffer.append(":").append(dataIn.getItemSubjectRef().getStructureRef()); } dataInBuffer.append(","); } if(dataIn.getName() != null && dataIn.getName().equals("GroupId")) { groupDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Skippable")) { skippableDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Comment")) { commentDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Content")) { contentDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Priority")) { priorityDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("Locale")) { localeDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("CreatedBy")) { createdByDataInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotCompletedReassign")) { notCompletedReassignInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotStartedReassign")) { notStartedReassignInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotCompletedNotify")) { notCompletedNotificationInput = dataIn; } if(dataIn.getName() != null && dataIn.getName().equals("NotStartedNotify")) { notStartedNotificationInput = dataIn; } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(task.getIoSpecification() != null) { List<OutputSet> outputSetList = task.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { if(!dataOut.getName().equals("mioutputCollection")) { dataOutBuffer.append(dataOut.getName()); if(dataOut.getItemSubjectRef() != null && dataOut.getItemSubjectRef().getStructureRef() != null && dataOut.getItemSubjectRef().getStructureRef().length() > 0) { dataOutBuffer.append(":").append(dataOut.getItemSubjectRef().getStructureRef()); } dataOutBuffer.append(","); } } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = task.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = task.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); //List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { boolean proceed = true; if(task.getLoopCharacteristics() != null) { MultiInstanceLoopCharacteristics taskMultiLoop = (MultiInstanceLoopCharacteristics) task.getLoopCharacteristics(); // dont include associations that include mi loop data inputs if(taskMultiLoop.getInputDataItem() != null && taskMultiLoop.getInputDataItem().getId() != null) { if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0 && datain.getSourceRef().get(0).getId().equals(taskMultiLoop.getInputDataItem().getId())) { proceed = false; } } // dont include associations that include loopDataInputRef as target if(taskMultiLoop.getLoopDataInputRef() != null ) { if(datain.getTargetRef().equals(taskMultiLoop.getLoopDataInputRef())) { proceed = false; } } } if(proceed) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } // else { // // check if this is a bi-directional association // for(DataOutputAssociation dataout : outputAssociations) { // if(dataout.getTargetRef().getId().equals(lhsAssociation) && // ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { // isBiDirectional = true; // break; // } // } // } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } // don't include properties that have their independent input editors: if(!(rhsAssociation.equals("GroupId") || rhsAssociation.equals("Skippable") || rhsAssociation.equals("Comment") || rhsAssociation.equals("Priority") || rhsAssociation.equals("Content") || rhsAssociation.equals("TaskName") || rhsAssociation.equals("Locale") || rhsAssociation.equals("CreatedBy") || rhsAssociation.equals("NotCompletedReassign") || rhsAssociation.equals("NotStartedReassign") || rhsAssociation.equals("NotCompletedNotify") || rhsAssociation.equals("NotStartedNotify") )) { String replacer = associationValue.replaceAll(",", "##"); associationBuff.append("[din]" + rhsAssociation).append("=").append(replacer); associationBuff.append(","); } if(rhsAssociation.equalsIgnoreCase("TaskName")) { properties.put("taskname", associationValue); } if (groupDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(groupDataInput.getId())) { properties.put("groupid", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody() == null ? "" : ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (skippableDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(skippableDataInput.getId())) { properties.put("skippable", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (commentDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(commentDataInput.getId())) { properties.put("comment", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (priorityDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(priorityDataInput.getId())) { properties.put("priority", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody() == null ? "" : ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (contentDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(contentDataInput.getId())) { properties.put("content", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (localeDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(localeDataInput.getId())) { properties.put("locale", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (createdByDataInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(createdByDataInput.getId())) { properties.put("createdby", ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody()); } if (notCompletedReassignInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notCompletedReassignInput.getId())) { properties.put("tmpreassignmentnotcompleted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-completed" )); } if (notStartedReassignInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notStartedReassignInput.getId())) { properties.put("tmpreassignmentnotstarted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-started" )); } if (notCompletedNotificationInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notCompletedNotificationInput.getId())) { properties.put("tmpnotificationnotcompleted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-completed" )); } if (notStartedNotificationInput != null && datain.getAssignment().get(0).getTo() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody() != null && ((FormalExpression) datain.getAssignment().get(0).getTo()).getBody().equals(notStartedNotificationInput.getId())) { properties.put("tmpnotificationnotstarted", updateReassignmentAndNotificationInput( ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(), "not-started" )); } } } // else if(isBiDirectional) { // associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); // associationBuff.append(","); // biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // if(contentDataInput != null) { // if(rhsAssociation.equals(contentDataInput.getName())) { // properties.put("content", lhsAssociation); // } // } } } } if(properties.get("tmpreassignmentnotcompleted") != null && ((String)properties.get("tmpreassignmentnotcompleted")).length() > 0 && properties.get("tmpreassignmentnotstarted") != null && ((String) properties.get("tmpreassignmentnotstarted")).length() > 0) { properties.put("reassignment", properties.get("tmpreassignmentnotcompleted") + "^" + properties.get("tmpreassignmentnotstarted")); } else if(properties.get("tmpreassignmentnotcompleted") != null && ((String) properties.get("tmpreassignmentnotcompleted")).length() > 0) { properties.put("reassignment", properties.get("tmpreassignmentnotcompleted")); } else if(properties.get("tmpreassignmentnotstarted") != null && ((String) properties.get("tmpreassignmentnotstarted")).length() > 0) { properties.put("reassignment", properties.get("tmpreassignmentnotstarted")); } if(properties.get("tmpnotificationnotcompleted") != null && ((String)properties.get("tmpnotificationnotcompleted")).length() > 0 && properties.get("tmpnotificationnotstarted") != null && ((String) properties.get("tmpnotificationnotstarted")).length() > 0) { properties.put("notifications", properties.get("tmpnotificationnotcompleted") + "^" + properties.get("tmpnotificationnotstarted")); } else if(properties.get("tmpnotificationnotcompleted") != null && ((String) properties.get("tmpnotificationnotcompleted")).length() > 0) { properties.put("notifications", properties.get("tmpnotificationnotcompleted")); } else if(properties.get("tmpnotificationnotstarted") != null && ((String) properties.get("tmpnotificationnotstarted")).length() > 0) { properties.put("notifications", properties.get("tmpnotificationnotstarted")); } for(DataOutputAssociation dataout : outputAssociations) { boolean proceed = true; if(task.getLoopCharacteristics() != null) { MultiInstanceLoopCharacteristics taskMultiLoop = (MultiInstanceLoopCharacteristics) task.getLoopCharacteristics(); // dont include associations that include mi loop data outputs if(taskMultiLoop.getOutputDataItem() != null && taskMultiLoop.getOutputDataItem().getId() != null) { if(dataout.getTargetRef().getId().equals(taskMultiLoop.getOutputDataItem().getId())) { proceed = false; } } // dont include associations that include loopDataOutputRef as source if(taskMultiLoop.getLoopDataOutputRef() != null) { if(dataout.getSourceRef().get(0).equals(taskMultiLoop.getLoopDataOutputRef())) { proceed = false; } } } if(proceed) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional // for(String bda : biDirectionalAssociations) { // String[] dbaparts = bda.split( ",\\s*" ); // if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { // wasBiDirectional = true; // break; // } // } if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) { rhsAssociation = dataout.getTransformation().getBody().replaceAll("=", "||"); } if(!wasBiDirectional) { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[dout]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); } } } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions if(task.getExtensionValues() != null && task.getExtensionValues().size() > 0) { String onEntryStr = ""; String onExitStr = ""; for(ExtensionAttributeValue extattrval : task.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true); @SuppressWarnings("unchecked") List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true); for(OnEntryScriptType onEntryScript : onEntryExtensions) { onEntryStr += onEntryScript.getScript(); onEntryStr += "|"; if(onEntryScript.getScriptFormat() != null) { String format = onEntryScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } properties.put("script_language", formatToWrite); } } for(OnExitScriptType onExitScript : onExitExtensions) { onExitStr += onExitScript.getScript(); onExitStr += "|"; if(onExitScript.getScriptFormat() != null) { String format = onExitScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } if(properties.get("script_language") == null) { properties.put("script_language", formatToWrite); } } } } if(onEntryStr.length() > 0) { if(onEntryStr.endsWith("|")) { onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1); } properties.put("onentryactions", onEntryStr); } if(onExitStr.length() > 0) { if(onExitStr.endsWith("|")) { onExitStr = onExitStr.substring(0, onExitStr.length() - 1); } properties.put("onexitactions", onExitStr); } } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(task.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 does not support random distribution // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } if(timeParams.getWaitTime() != null) { FloatingParameterType waittimeType = (FloatingParameterType) timeParams.getWaitTime().getParameterValue().get(0); properties.put("waittime", waittimeType.getValue()); } CostParameters costParams = eleType.getCostParameters(); if(costParams != null) { if(costParams.getUnitCost() != null) { FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); } // bpsim 1.0 does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); } } } } // marshall the node out if(isCustomElement((String) properties.get("taskname"), preProcessingData)) { marshallNode(task, properties, (String) properties.get("taskname"), plane, generator, xOffset, yOffset); } else { marshallNode(task, properties, "Task", plane, generator, xOffset, yOffset); } } protected void marshallParallelGateway(ParallelGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { marshallNode(gateway, flowElementProperties, "ParallelGateway", plane, generator, xOffset, yOffset); } protected void marshallExclusiveGateway(ExclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { if(gateway.getDefault() != null) { SequenceFlow defsf = gateway.getDefault(); String defGatewayStr = ""; if(defsf.getName() != null && defsf.getName().length() > 0) { defGatewayStr = defsf.getName() + " : " + defsf.getId(); } else { defGatewayStr = defsf.getId(); } flowElementProperties.put("defaultgate", defGatewayStr); } marshallNode(gateway, flowElementProperties, "Exclusive_Databased_Gateway", plane, generator, xOffset, yOffset); } protected void marshallInclusiveGateway(InclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { if(gateway.getDefault() != null) { SequenceFlow defsf = gateway.getDefault(); String defGatewayStr = ""; if(defsf.getName() != null && defsf.getName().length() > 0) { defGatewayStr = defsf.getName() + " : " + defsf.getId(); } else { defGatewayStr = defsf.getId(); } flowElementProperties.put("defaultgate", defGatewayStr); } marshallNode(gateway, flowElementProperties, "InclusiveGateway", plane, generator, xOffset, yOffset); } protected void marshallEventBasedGateway(EventBasedGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { marshallNode(gateway, flowElementProperties, "EventbasedGateway", plane, generator, xOffset, yOffset); } protected void marshallComplexGateway(ComplexGateway gateway, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { marshallNode(gateway, flowElementProperties, "ComplexGateway", plane, generator, xOffset, yOffset); } protected void marshallNode(FlowNode node, Map<String, Object> properties, String stencil, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset) throws JsonGenerationException, IOException { if (properties == null) { properties = new LinkedHashMap<String, Object>(); } if(node.getDocumentation() != null && node.getDocumentation().size() > 0) { properties.put("documentation", node.getDocumentation().get(0).getText()); } if(node.getName() != null) { properties.put("name", unescapeXML(node.getName())); } else { properties.put("name", ""); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencil); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (SequenceFlow outgoing: node.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } // we need to also add associations as outgoing elements Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getSourceRef().getId().equals(node.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", association.getId()); generator.writeEndObject(); } } } // and boundary events for activities List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>(); findBoundaryEvents(process, boundaryEvents); for(BoundaryEvent be : boundaryEvents) { if(be.getAttachedToRef().getId().equals(node.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", be.getId()); generator.writeEndObject(); } } generator.writeEndArray(); // boundary events have a docker if(node instanceof BoundaryEvent) { // find the edge associated with this boundary event for (DiagramElement element: plane.getPlaneElement()) { if(element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == node) { List<Point> waypoints = ((BPMNEdge) element).getWaypoint(); if(waypoints != null && waypoints.size() > 0) { // one per boundary event Point p = waypoints.get(0); if(p != null) { generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", p.getX()); generator.writeObjectField("y", p.getY()); generator.writeEndObject(); generator.writeEndArray(); } } } } } BPMNShape shape = (BPMNShape) findDiagramElement(plane, node); Bounds bounds = shape.getBounds(); correctEventNodeSize(shape); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } private void correctEventNodeSize(BPMNShape shape) { BaseElement element = shape.getBpmnElement(); if (element instanceof Event) { // // do not "fix" events as they shape is circle - leave bounds as is // Bounds bounds = shape.getBounds(); // float width = bounds.getWidth(); // float height = bounds.getHeight(); // if (width != 30 || height != 30) { // bounds.setWidth(30); // bounds.setHeight(30); // float x = bounds.getX(); // float y = bounds.getY(); // x = x - ((30 - width)/2); // y = y - ((30 - height)/2); // bounds.setX(x); // bounds.setY(y); // } } else if (element instanceof Gateway) { Bounds bounds = shape.getBounds(); float width = bounds.getWidth(); float height = bounds.getHeight(); if (width != 40 || height != 40) { bounds.setWidth(40); bounds.setHeight(40); float x = bounds.getX(); float y = bounds.getY(); x = x - ((40 - width)/2); y = y - ((40 - height)/2); bounds.setX(x); bounds.setY(y); } } } protected void marshallDataObject(DataObject dataObject, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); if(dataObject.getDocumentation() != null && dataObject.getDocumentation().size() > 0) { properties.put("documentation", dataObject.getDocumentation().get(0).getText()); } if(dataObject.getName() != null && dataObject.getName().length() > 0) { properties.put("name", unescapeXML(dataObject.getName())); } else { // we need a name, use id instead properties.put("name", dataObject.getId()); } if(dataObject.getItemSubjectRef().getStructureRef() != null && dataObject.getItemSubjectRef().getStructureRef().length() > 0) { if(defaultTypesList.contains(dataObject.getItemSubjectRef().getStructureRef())) { properties.put("standardtype", dataObject.getItemSubjectRef().getStructureRef()); } else { properties.put("customtype", dataObject.getItemSubjectRef().getStructureRef()); } } Association outgoingAssociaton = findOutgoingAssociation(plane, dataObject); Association incomingAssociation = null; Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getTargetRef() == dataObject){ incomingAssociation = association; } } } if(outgoingAssociaton != null && incomingAssociation == null) { properties.put("input_output", "Input"); } if(outgoingAssociaton == null && incomingAssociation != null) { properties.put("input_output", "Output"); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "DataObject"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); List<Association> associations = findOutgoingAssociations(plane, dataObject); if(associations != null) { for(Association as : associations) { generator.writeStartObject(); generator.writeObjectField("resourceId", as.getId()); generator.writeEndObject(); } } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, dataObject)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected void marshallSubProcess(SubProcess subProcess, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); if(subProcess.getName() != null) { properties.put("name", unescapeXML(subProcess.getName())); } else { properties.put("name", ""); } if(subProcess instanceof AdHocSubProcess) { AdHocSubProcess ahsp = (AdHocSubProcess) subProcess; if(ahsp.getOrdering().equals(AdHocOrdering.PARALLEL)) { properties.put("adhocordering", "Parallel"); } else if(ahsp.getOrdering().equals(AdHocOrdering.SEQUENTIAL)) { properties.put("adhocordering", "Sequential"); } else { // default to parallel properties.put("adhocordering", "Parallel"); } if(ahsp.getCompletionCondition() != null) { properties.put("adhoccompletioncondition", ((FormalExpression) ahsp.getCompletionCondition()).getBody().replaceAll("\n", "\\\\n")); } } // data inputs if(subProcess.getIoSpecification() != null) { List<InputSet> inputSetList = subProcess.getIoSpecification().getInputSets(); StringBuilder dataInBuffer = new StringBuilder(); for(InputSet inset : inputSetList) { List<DataInput> dataInputList = inset.getDataInputRefs(); for(DataInput dataIn : dataInputList) { if(dataIn.getName() != null) { dataInBuffer.append(dataIn.getName()); if(dataIn.getItemSubjectRef() != null && dataIn.getItemSubjectRef().getStructureRef() != null && dataIn.getItemSubjectRef().getStructureRef().length() > 0) { dataInBuffer.append(":").append(dataIn.getItemSubjectRef().getStructureRef()); } dataInBuffer.append(","); } } } if(dataInBuffer.length() > 0) { dataInBuffer.setLength(dataInBuffer.length() - 1); } properties.put("datainputset", dataInBuffer.toString()); } // data outputs if(subProcess.getIoSpecification() != null) { List<OutputSet> outputSetList = subProcess.getIoSpecification().getOutputSets(); StringBuilder dataOutBuffer = new StringBuilder(); for(OutputSet outset : outputSetList) { List<DataOutput> dataOutputList = outset.getDataOutputRefs(); for(DataOutput dataOut : dataOutputList) { dataOutBuffer.append(dataOut.getName()); if(dataOut.getItemSubjectRef() != null && dataOut.getItemSubjectRef().getStructureRef() != null && dataOut.getItemSubjectRef().getStructureRef().length() > 0) { dataOutBuffer.append(":").append(dataOut.getItemSubjectRef().getStructureRef()); } dataOutBuffer.append(","); } } if(dataOutBuffer.length() > 0) { dataOutBuffer.setLength(dataOutBuffer.length() - 1); } properties.put("dataoutputset", dataOutBuffer.toString()); } // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = subProcess.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = subProcess.getDataOutputAssociations(); List<String> uniDirectionalAssociations = new ArrayList<String>(); //List<String> biDirectionalAssociations = new ArrayList<String>(); for(DataInputAssociation datain : inputAssociations) { String lhsAssociation = ""; if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { lhsAssociation = datain.getTransformation().getBody(); } else { lhsAssociation = datain.getSourceRef().get(0).getId(); } } String rhsAssociation = ""; if(datain.getTargetRef() != null) { rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); } //boolean isBiDirectional = false; boolean isAssignment = false; if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { isAssignment = true; } // else { // // check if this is a bi-directional association // for(DataOutputAssociation dataout : outputAssociations) { // if(dataout.getTargetRef().getId().equals(lhsAssociation) && // ((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) { // isBiDirectional = true; // break; // } // } // } if(isAssignment) { // only know how to deal with formal expressions if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); if(associationValue == null) { associationValue = ""; } String replacer = associationValue.replaceAll(",", "##"); associationBuff.append("[din]" + rhsAssociation).append("=").append(replacer); associationBuff.append(","); } } // else if(isBiDirectional) { // associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation); // associationBuff.append(","); // biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); // } else { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); } } } for(DataOutputAssociation dataout : outputAssociations) { if(dataout.getSourceRef().size() > 0) { String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName(); String rhsAssociation = dataout.getTargetRef().getId(); boolean wasBiDirectional = false; // check if we already addressed this association as bidirectional // for(String bda : biDirectionalAssociations) { // String[] dbaparts = bda.split( ",\\s*" ); // if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) { // wasBiDirectional = true; // break; // } // } if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) { rhsAssociation = dataout.getTransformation().getBody().replaceAll("=", "||"); } if(!wasBiDirectional) { if(lhsAssociation != null && lhsAssociation.length() > 0) { associationBuff.append("[dout]" + lhsAssociation).append("->").append(rhsAssociation); associationBuff.append(","); } } } } String assignmentString = associationBuff.toString(); if(assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions if(subProcess.getExtensionValues() != null && subProcess.getExtensionValues().size() > 0) { String onEntryStr = ""; String onExitStr = ""; for(ExtensionAttributeValue extattrval : subProcess.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true); @SuppressWarnings("unchecked") List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true); for(OnEntryScriptType onEntryScript : onEntryExtensions) { onEntryStr += onEntryScript.getScript(); onEntryStr += "|"; if(onEntryScript.getScriptFormat() != null) { String format = onEntryScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } properties.put("script_language", formatToWrite); } } for(OnExitScriptType onExitScript : onExitExtensions) { onExitStr += onExitScript.getScript(); onExitStr += "|"; if(onExitScript.getScriptFormat() != null) { String format = onExitScript.getScriptFormat(); String formatToWrite = ""; if(format.equals("http://www.java.com/java")) { formatToWrite = "java"; } else if(format.equals("http://www.mvel.org/2.0")) { formatToWrite = "mvel"; } else { formatToWrite = "java"; } if(properties.get("script_language") == null) { properties.put("script_language", formatToWrite); } } } } if(onEntryStr.length() > 0) { if(onEntryStr.endsWith("|")) { onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1); } properties.put("onentryactions", onEntryStr); } if(onExitStr.length() > 0) { if(onExitStr.endsWith("|")) { onExitStr = onExitStr.substring(0, onExitStr.length() - 1); } properties.put("onexitactions", onExitStr); } } // loop characteristics boolean haveValidLoopCharacteristics = false; if(subProcess.getLoopCharacteristics() != null && subProcess.getLoopCharacteristics() instanceof MultiInstanceLoopCharacteristics) { haveValidLoopCharacteristics = true; properties.put("mitrigger", "true"); MultiInstanceLoopCharacteristics taskmi = (MultiInstanceLoopCharacteristics) subProcess.getLoopCharacteristics(); if(taskmi.getLoopDataInputRef() != null) { ItemAwareElement iedatainput = taskmi.getLoopDataInputRef(); List<DataInputAssociation> taskInputAssociations = subProcess.getDataInputAssociations(); for(DataInputAssociation dia : taskInputAssociations) { if(dia.getTargetRef().equals(iedatainput)) { properties.put("multipleinstancecollectioninput", dia.getSourceRef().get(0).getId()); break; } } } if(taskmi.getLoopDataOutputRef() != null) { ItemAwareElement iedataoutput = taskmi.getLoopDataOutputRef(); List<DataOutputAssociation> taskOutputAssociations = subProcess.getDataOutputAssociations(); for(DataOutputAssociation dout : taskOutputAssociations) { if(dout.getSourceRef().get(0).equals(iedataoutput)) { properties.put("multipleinstancecollectionoutput", dout.getTargetRef().getId()); break; } } } if(taskmi.getInputDataItem() != null) { List<DataInput> taskDataInputs = subProcess.getIoSpecification().getDataInputs(); for(DataInput din: taskDataInputs) { if (din.getItemSubjectRef() == null) { // for backward compatibility as the where only input supported properties.put("multipleinstancedatainput", taskmi.getInputDataItem().getId()); } if(din.getItemSubjectRef() != null && din.getItemSubjectRef().getId().equals(taskmi.getInputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedatainput", din.getName()); break; } } } if(taskmi.getOutputDataItem() != null) { List<DataOutput> taskDataOutputs = subProcess.getIoSpecification().getDataOutputs(); for(DataOutput dout : taskDataOutputs) { if(dout.getItemSubjectRef() == null) { properties.put("multipleinstancedataoutput", taskmi.getOutputDataItem().getId()); break; } if(dout.getItemSubjectRef()!= null && dout.getItemSubjectRef().getId().equals(taskmi.getOutputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedataoutput", dout.getName()); break; } } } if(taskmi.getCompletionCondition() != null) { if (taskmi.getCompletionCondition() instanceof FormalExpression) { properties.put("multipleinstancecompletioncondition", ((FormalExpression)taskmi.getCompletionCondition()).getBody()); } } } // properties List<Property> processProperties = subProcess.getProperties(); if(processProperties != null && processProperties.size() > 0) { String propVal = ""; for(int i=0; i<processProperties.size(); i++) { Property p = processProperties.get(i); propVal += p.getId(); // check the structureRef value if(p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) { propVal += ":" + p.getItemSubjectRef().getStructureRef(); } if(i != processProperties.size()-1) { propVal += ","; } } properties.put("vardefs", propVal); } // simulation properties if(_simulationScenario != null) { for(ElementParameters eleType : _simulationScenario.getElementParameters()) { if(eleType.getElementRef().equals(subProcess.getId())) { TimeParameters timeParams = eleType.getTimeParameters(); Parameter processingTime = timeParams.getProcessingTime(); ParameterValue paramValue = processingTime.getParameterValue().get(0); if(paramValue instanceof NormalDistributionType) { NormalDistributionType ndt = (NormalDistributionType) paramValue; properties.put("mean", ndt.getMean()); properties.put("standarddeviation", ndt.getStandardDeviation()); properties.put("distributiontype", "normal"); } else if(paramValue instanceof UniformDistributionType) { UniformDistributionType udt = (UniformDistributionType) paramValue; properties.put("min", udt.getMin()); properties.put("max", udt.getMax()); properties.put("distributiontype", "uniform"); // bpsim 1.0 does not support random distribution // } else if(paramValue instanceof RandomDistributionType) { // RandomDistributionType rdt = (RandomDistributionType) paramValue; // properties.put("min", rdt.getMin()); // properties.put("max", rdt.getMax()); // properties.put("distributiontype", "random"); } else if(paramValue instanceof PoissonDistributionType) { PoissonDistributionType pdt = (PoissonDistributionType) paramValue; properties.put("mean", pdt.getMean()); properties.put("distributiontype", "poisson"); } // bpsim 1.0 has no support for individual time unit // if(timeParams.getTimeUnit() != null) { // properties.put("timeunit", timeParams.getTimeUnit().getName()); // } if(timeParams.getWaitTime() != null) { FloatingParameterType waittimeType = (FloatingParameterType) timeParams.getWaitTime().getParameterValue().get(0); properties.put("waittime", waittimeType.getValue()); } CostParameters costParams = eleType.getCostParameters(); if(costParams != null) { if(costParams.getUnitCost() != null) { FloatingParameterType unitCostVal = (FloatingParameterType) costParams.getUnitCost().getParameterValue().get(0); properties.put("unitcost", unitCostVal.getValue()); } // bpsim 1.0 does not support individual currency //properties.put("currency", costParams.getUnitCost() == null ? "" : costParams.getUnitCost()); } } } } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); if(subProcess instanceof AdHocSubProcess) { generator.writeObjectField("id", "AdHocSubprocess"); } else { if(subProcess.isTriggeredByEvent()) { generator.writeObjectField("id", "EventSubprocess"); } else { if(haveValidLoopCharacteristics) { generator.writeObjectField("id", "MultipleInstanceSubprocess"); } else { generator.writeObjectField("id", "Subprocess"); } } } generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); Bounds bounds = ((BPMNShape) findDiagramElement(plane, subProcess)).getBounds(); for (FlowElement flowElement: subProcess.getFlowElements()) { if(coordianteManipulation) { marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } for (Artifact artifact: subProcess.getArtifacts()) { if(coordianteManipulation) { marshallArtifact(artifact, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def); } } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (BoundaryEvent boundaryEvent: subProcess.getBoundaryEventRefs()) { generator.writeStartObject(); generator.writeObjectField("resourceId", boundaryEvent.getId()); generator.writeEndObject(); } for (SequenceFlow outgoing: subProcess.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } // subprocess boundary events Process process = (Process) plane.getBpmnElement(); List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>(); findBoundaryEvents(process, boundaryEvents); for(BoundaryEvent be : boundaryEvents) { if(be.getAttachedToRef().getId().equals(subProcess.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", be.getId()); generator.writeEndObject(); } } generator.writeEndArray(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected void marshallSequenceFlow(SequenceFlow sequenceFlow, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset) throws JsonGenerationException, IOException { // dont marshal "dangling" sequence flow..better to just omit than fail if(sequenceFlow.getSourceRef() == null || sequenceFlow.getTargetRef() == null) { return; } Map<String, Object> properties = new LinkedHashMap<String, Object>(); // check null for sequence flow name if(sequenceFlow.getName() != null && !"".equals(sequenceFlow.getName())) { properties.put("name", unescapeXML(sequenceFlow.getName())); } else { properties.put("name", ""); } if(sequenceFlow.getDocumentation() != null && sequenceFlow.getDocumentation().size() > 0) { properties.put("documentation", sequenceFlow.getDocumentation().get(0).getText()); } if(sequenceFlow.isIsImmediate()) { properties.put("isimmediate", "true"); } else { properties.put("isimmediate", "false"); } Expression conditionExpression = sequenceFlow.getConditionExpression(); if (conditionExpression instanceof FormalExpression) { if(((FormalExpression) conditionExpression).getBody() != null) { properties.put("conditionexpression", ((FormalExpression) conditionExpression).getBody().replaceAll("\n", "\\\\n")); } if(((FormalExpression) conditionExpression).getLanguage() != null) { String cd = ((FormalExpression) conditionExpression).getLanguage(); String cdStr = ""; if(cd.equalsIgnoreCase("http://www.java.com/java")) { cdStr = "java"; } else if(cd.equalsIgnoreCase("http://www.jboss.org/drools/rule")) { cdStr = "drools"; } else if(cd.equalsIgnoreCase("http://www.mvel.org/2.0")) { cdStr = "mvel"; } else { // default to mvel cdStr = "mvel"; } properties.put("conditionexpressionlanguage", cdStr); } } boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; Iterator<FeatureMap.Entry> iter = sequenceFlow.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("priority")) { String priorityStr = String.valueOf(entry.getValue()); if(priorityStr != null) { try { Integer priorityInt = Integer.parseInt(priorityStr); if(priorityInt >= 1) { properties.put("priority", entry.getValue()); } else { _logger.error("Priority must be equal or greater than 1."); } } catch (NumberFormatException e) { _logger.error("Priority must be a number."); } } } if(entry.getEStructuralFeature().getName().equals("background-color")) { properties.put("bgcolor", entry.getValue()); foundBgColor = true; } if(entry.getEStructuralFeature().getName().equals("border-color")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { properties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { properties.put("fontcolor", entry.getValue()); foundFontColor = true; } if(entry.getEStructuralFeature().getName().equals("selectable")) { properties.put("isselectable", entry.getValue()); foundSelectable = true; } } if(!foundBgColor) { properties.put("bgcolor", defaultSequenceflowColor); } if(!foundBrColor) { properties.put("bordercolor", defaultSequenceflowColor); } if(!foundFontColor) { properties.put("fontcolor", defaultSequenceflowColor); } if(!foundSelectable) { properties.put("isselectable", "true"); } // simulation properties if(_simulationScenario != null) { List<ElementParameters> elementParams = _simulationScenario.getElementParameters(); for(ElementParameters eleType : elementParams) { if(eleType.getElementRef().equals(sequenceFlow.getId())) { FloatingParameterType valType = (FloatingParameterType) eleType.getControlParameters().getProbability().getParameterValue().get(0); properties.put("probability", valType.getValue()); } } } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "SequenceFlow"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", sequenceFlow.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getSourceRef())).getBounds(); Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getTargetRef())).getBounds(); generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", sourceBounds.getWidth() / 2); generator.writeObjectField("y", sourceBounds.getHeight() / 2); generator.writeEndObject(); List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, sequenceFlow)).getWaypoint(); for (int i = 1; i < waypoints.size() - 1; i++) { Point waypoint = waypoints.get(i); generator.writeStartObject(); generator.writeObjectField("x", waypoint.getX()); generator.writeObjectField("y", waypoint.getY()); generator.writeEndObject(); } generator.writeStartObject(); generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); generator.writeEndObject(); generator.writeEndArray(); } private DiagramElement findDiagramElement(BPMNPlane plane, BaseElement baseElement) { DiagramElement result = _diagramElements.get(baseElement.getId()); if (result != null) { return result; } for (DiagramElement element: plane.getPlaneElement()) { if ((element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == baseElement) || (element instanceof BPMNShape && ((BPMNShape) element).getBpmnElement() == baseElement)) { _diagramElements.put(baseElement.getId(), element); return element; } } _logger.info("Could not find BPMNDI information for " + baseElement); return null; } protected void marshallGlobalTask(GlobalTask globalTask, JsonGenerator generator) { if (globalTask instanceof GlobalBusinessRuleTask) { } else if (globalTask instanceof GlobalManualTask) { } else if (globalTask instanceof GlobalScriptTask) { } else if (globalTask instanceof GlobalUserTask) { } else { } } protected void marshallGlobalChoreographyTask(GlobalChoreographyTask callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } protected void marshallConversation(Conversation callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } protected void marshallChoreography(Choreography callableElement, JsonGenerator generator) { throw new UnsupportedOperationException("TODO"); //TODO! } protected void marshallProperties(Map<String, Object> properties, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeObjectFieldStart("properties"); for (Entry<String, Object> entry : properties.entrySet()) { generator.writeObjectField(entry.getKey(), String.valueOf(entry.getValue())); } generator.writeEndObject(); } protected void marshallArtifact(Artifact artifact, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws IOException { generator.writeStartObject(); generator.writeObjectField("resourceId", artifact.getId()); if (artifact instanceof Association) { marshallAssociation((Association)artifact, plane, generator, xOffset, yOffset, preProcessingData, def); } else if (artifact instanceof TextAnnotation) { marshallTextAnnotation((TextAnnotation) artifact, plane, generator, xOffset, yOffset, preProcessingData, def); } else if (artifact instanceof Group) { marshallGroup((Group) artifact, plane, generator, xOffset, yOffset, preProcessingData, def); } generator.writeEndObject(); } protected void marshallAssociation(Association association, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); Iterator<FeatureMap.Entry> iter = association.getAnyAttribute().iterator(); boolean foundBrColor = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("type")) { properties.put("type", entry.getValue()); } if(entry.getEStructuralFeature().getName().equals("bordercolor")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } } if(!foundBrColor) { properties.put("bordercolor", defaultSequenceflowColor); } if(association.getDocumentation() != null && association.getDocumentation().size() > 0) { properties.put("documentation", association.getDocumentation().get(0).getText()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); if(association.getAssociationDirection().equals(AssociationDirection.ONE)) { generator.writeObjectField("id", "Association_Unidirectional"); } else if(association.getAssociationDirection().equals(AssociationDirection.BOTH)) { generator.writeObjectField("id", "Association_Bidirectional"); } else { generator.writeObjectField("id", "Association_Undirected"); } generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", association.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, association.getSourceRef())).getBounds(); Bounds targetBounds = null; float tbx = 0; float tby = 0; if(findDiagramElement(plane, association.getTargetRef()) instanceof BPMNShape) { targetBounds = ((BPMNShape) findDiagramElement(plane, association.getTargetRef())).getBounds(); } else if(findDiagramElement(plane, association.getTargetRef()) instanceof BPMNEdge) { // connect it to first waypoint on edge List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association.getTargetRef())).getWaypoint(); if(waypoints != null && waypoints.size() > 0) { tbx = waypoints.get(0).getX(); tby = waypoints.get(0).getY(); } } generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", sourceBounds.getWidth() / 2); generator.writeObjectField("y", sourceBounds.getHeight() / 2); generator.writeEndObject(); List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association)).getWaypoint(); for (int i = 1; i < waypoints.size() - 1; i++) { Point waypoint = waypoints.get(i); generator.writeStartObject(); generator.writeObjectField("x", waypoint.getX()); generator.writeObjectField("y", waypoint.getY()); generator.writeEndObject(); } if(targetBounds != null) { generator.writeStartObject(); generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); generator.writeEndObject(); generator.writeEndArray(); } else { generator.writeStartObject(); generator.writeObjectField("x", tbx); generator.writeObjectField("y", tby); generator.writeEndObject(); generator.writeEndArray(); } } protected void marshallTextAnnotation(TextAnnotation textAnnotation, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException{ Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("name", textAnnotation.getText()); if(textAnnotation.getDocumentation() != null && textAnnotation.getDocumentation().size() > 0) { properties.put("documentation", textAnnotation.getDocumentation().get(0).getText()); } properties.put("artifacttype", "Annotation"); Iterator<FeatureMap.Entry> iter = textAnnotation.getAnyAttribute().iterator(); boolean foundBrColor = false; boolean foundFontColor = false; while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("border-color")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("fontsize")) { properties.put("fontsize", entry.getValue()); foundBrColor = true; } if(entry.getEStructuralFeature().getName().equals("color")) { properties.put("fontcolor", entry.getValue()); foundFontColor = true; } } if(!foundBrColor) { properties.put("bordercolor", defaultBrColor); } if(!foundFontColor) { properties.put("fontcolor", defaultFontColor); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "TextAnnotation"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); if(findOutgoingAssociation(plane, textAnnotation) != null) { generator.writeStartObject(); generator.writeObjectField("resourceId", findOutgoingAssociation(plane, textAnnotation).getId()); generator.writeEndObject(); } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, textAnnotation)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected void marshallGroup(Group group, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException{ Map<String, Object> properties = new LinkedHashMap<String, Object>(); if(group.getCategoryValueRef() != null && group.getCategoryValueRef().getValue() != null) { properties.put("name", unescapeXML(group.getCategoryValueRef().getValue())); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Group"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); if(findOutgoingAssociation(plane, group) != null) { generator.writeStartObject(); generator.writeObjectField("resourceId", findOutgoingAssociation(plane, group).getId()); generator.writeEndObject(); } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, group)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); } protected Association findOutgoingAssociation(BPMNPlane plane, BaseElement baseElement) { Association result = _diagramAssociations.get(baseElement.getId()); if (result != null) { return result; } if (!(plane.getBpmnElement() instanceof Process)){ throw new IllegalArgumentException("Don't know how to get associations from a non-Process Diagram"); } Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getSourceRef() == baseElement){ _diagramAssociations.put(baseElement.getId(), association); return association; } } } return null; } protected List<Association> findOutgoingAssociations(BPMNPlane plane, BaseElement baseElement) { List<Association> retList = new ArrayList<Association>(); if (!(plane.getBpmnElement() instanceof Process)){ throw new IllegalArgumentException("Don't know how to get associations from a non-Process Diagram"); } Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association){ Association association = (Association) artifact; if (association.getSourceRef() == baseElement){ retList.add(association); } } } return retList; } protected void marshallStencil(String stencilId, JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencilId); generator.writeEndObject(); } private boolean isCustomElement(String taskType, String preProcessingData) { if(taskType != null && taskType.length() > 0 && preProcessingData != null && preProcessingData.length() > 0) { String[] preProcessingDataElements = preProcessingData.split( ",\\s*" ); for(String preProcessingDataElement : preProcessingDataElements) { if(taskType.equals(preProcessingDataElement)) { return true; } } } return false; } private static String unescapeXML(String str) { if (str == null || str.length() == 0) return ""; StringBuffer buf = new StringBuffer(); int len = str.length(); for (int i = 0; i < len; ++i) { char c = str.charAt(i); if (c == '&') { int pos = str.indexOf(";", i); if (pos == -1) { // Really evil buf.append('&'); } else if (str.charAt(i + 1) == '#') { int val = Integer.parseInt(str.substring(i + 2, pos), 16); buf.append((char) val); i = pos; } else { String substr = str.substring(i, pos + 1); if (substr.equals("&amp;")) buf.append('&'); else if (substr.equals("&lt;")) buf.append('<'); else if (substr.equals("&gt;")) buf.append('>'); else if (substr.equals("&quot;")) buf.append('"'); else if (substr.equals("&apos;")) buf.append('\''); else // ???? buf.append(substr); i = pos; } } else { buf.append(c); } } return buf.toString(); } private String updateReassignmentAndNotificationInput(String inputStr, String type) { if(inputStr != null && inputStr.length() > 0) { String ret = ""; String[] parts = inputStr.split( "\\^\\s*" ); for(String nextPart : parts) { ret += nextPart + "@" + type + "^"; } if(ret.endsWith("^")) { ret = ret.substring(0, ret.length() - 1); } return ret; } else { return ""; } } private void findBoundaryEvents(FlowElementsContainer flc, List<BoundaryEvent> boundaryList) { for(FlowElement fl : flc.getFlowElements()) { if(fl instanceof BoundaryEvent) { boundaryList.add((BoundaryEvent) fl); } if(fl instanceof FlowElementsContainer) { findBoundaryEvents((FlowElementsContainer) fl, boundaryList); } } } }
BZ 1200758 - Impossible to save process with 'end event' with Data Input configured
jbpm-designer-backend/src/main/java/org/jbpm/designer/bpmn2/impl/Bpmn2JsonMarshaller.java
BZ 1200758 - Impossible to save process with 'end event' with Data Input configured
<ide><path>bpm-designer-backend/src/main/java/org/jbpm/designer/bpmn2/impl/Bpmn2JsonMarshaller.java <ide> } <ide> properties.put("datainput", dinbuff.toString()); <ide> <del> List<DataInputAssociation> inputAssociations = event.getDataInputAssociation(); <del> StringBuffer dinassociationbuff = new StringBuffer(); <del> for(DataInputAssociation din : inputAssociations) { <del> if(din.getSourceRef().get(0).getId() != null && din.getSourceRef().get(0).getId().length() > 0) { <del> dinassociationbuff.append("[din]" + din.getSourceRef().get(0).getId()); <del> dinassociationbuff.append("->"); <del> dinassociationbuff.append( ((DataInput)din.getTargetRef()).getName()); <del> dinassociationbuff.append(","); <del> } <del> } <del> if(dinassociationbuff.length() > 0) { <del> dinassociationbuff.setLength(dinassociationbuff.length() - 1); <del> } <del> properties.put("datainputassociations", dinassociationbuff.toString()); <del> } <add> StringBuilder associationBuff = new StringBuilder(); <add> List<String> uniDirectionalAssociations = new ArrayList<String>(); <add> for(DataInputAssociation datain : event.getDataInputAssociation()) { <add> String lhsAssociation = ""; <add> if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) { <add> if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) { <add> lhsAssociation = datain.getTransformation().getBody(); <add> } else { <add> lhsAssociation = datain.getSourceRef().get(0).getId(); <add> } <add> } <add> <add> String rhsAssociation = ""; <add> if(datain.getTargetRef() != null) { <add> rhsAssociation = ((DataInput) datain.getTargetRef()).getName(); <add> } <add> <add> //boolean isBiDirectional = false; <add> boolean isAssignment = false; <add> <add> if(datain.getAssignment() != null && datain.getAssignment().size() > 0) { <add> isAssignment = true; <add> } <add> <add> if(isAssignment) { <add> // only know how to deal with formal expressions <add> if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) { <add> String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody(); <add> if(associationValue == null) { <add> associationValue = ""; <add> } <add> String replacer = associationValue.replaceAll(",", "##"); <add> associationBuff.append("[din]" + rhsAssociation).append("=").append(replacer); <add> associationBuff.append(","); <add> } <add> } <add> else { <add> if(lhsAssociation != null && lhsAssociation.length() > 0) { <add> associationBuff.append("[din]" + lhsAssociation).append("->").append(rhsAssociation); <add> associationBuff.append(","); <add> uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation); <add> } <add> } <add> } <add> <add> String assignmentString = associationBuff.toString(); <add> if(assignmentString.endsWith(",")) { <add> assignmentString = assignmentString.substring(0, assignmentString.length() - 1); <add> } <add> properties.put("datainputassociations", assignmentString); <add> } <add> <ide> // event definitions <ide> List<EventDefinition> eventdefs = event.getEventDefinitions(); <ide> for(EventDefinition ed : eventdefs) {
JavaScript
mpl-2.0
06bb277ff9b141e48ce719b4d0f91fb87161e447
0
mozilla/motown
#!/usr/local/bin/node /* 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/. */ // Module dependencies. const express = require('express'), logger = require('winston'), passport = require('passport'), util = require('util'), application = require('./controllers/application'), redis = require('../../lib/redis')(), socket = require('./socket'), connect = require('connect'), RedisStore = require('connect-redis')(connect), BrowserID = require('passport-browserid').Strategy, User = require('../models/user'), config = require('../../lib/configuration'); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.find(id, function(err, user){ if (user){ done(null, user); } }); }); passport.use(new BrowserID({ audience: config.get('public_url') }, function(email, done) { User.findByEmail(email, function(err, user){ if (user){ return done(null, user); } else{ user = new User({'email': email}); user.save(function(err, user){ if (err){ logger.error("Error saving user after login (" + email + ")"); } else{ return done(null, user); } }); } }); } )); var http = express.createServer(); var sessionStore = new RedisStore({ maxAge: (1).day }); // Express Configuration http.configure(function(){ http.set('views', __dirname + '/views'); http.set('view engine', 'ejs'); http.use(express.logger()); http.use(express.static(__dirname + '/public')); http.use(express.cookieParser()); http.use(express.bodyParser()); http.use(express.methodOverride()); //TODO: Load secret from config/env var http.use(express.session({ secret: 'As a kid I ran down the stairs at full speed because I imagined Indians with bows and arrows would hit me if I walked.', key: 'express.sid', store: sessionStore })); // Initialize Passport! http.use(passport.initialize()); // Support persistent sessions: http.use(passport.session()); http.use(http.router); }); http.configure('development', function(){ http.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); http.configure('production', function(){ http.use(express.errorHandler()); }); // HTTP Routes routes = { site: require('./controllers/site'), social: require('./controllers/social'), profile: require('./controllers/profile'), feeds: require('./controllers/feeds') }; http.get('/', routes.site.index); http.get('/login', routes.site.login); http.get('/logout', routes.site.logout); http.post('/auth/browserid', passport.authenticate('browserid', { failureRedirect: '/login' }), routes.site.authenticate); http.get('/social/worker.js', routes.social.worker); http.get('/social/sidebar', routes.social.sidebar); http.get('/social/manifest.json', routes.social.manifest); http.get('/profile', application.authenticate, routes.profile.index.get); http.put('/profile', application.authenticate, routes.profile.index.put); http.post('/profile/nick', application.authenticate, routes.profile.nick.post); http.get('/feeds', application.authenticate, routes.feeds.index.get); process.on('uncaughtException', function(err) { logger.error(err); }); http.listen(config.get('bind_to').port); socket.listen(http, sessionStore); if (http.address() == null){ logger.error("Error listening to " + JSON.stringify(config.get('bind_to'))); process.exit(1); } logger.info(("MoTown HTTP server listening on port %d in %s mode", http.address().port, http.settings.env));
app/http/server.js
#!/usr/local/bin/node /* 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/. */ // Module dependencies. const express = require('express'), logger = require('winston'), passport = require('passport'), util = require('util'), application = require('./controllers/application'), redis = require('../../lib/redis')(), socket = require('./socket'), connect = require('connect'), RedisStore = require('connect-redis')(connect), BrowserID = require('passport-browserid').Strategy, User = require('../models/user'), config = require('../../lib/configuration'); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.find(id, function(err, user){ if (user){ done(null, user); } }); }); passport.use(new BrowserID({ audience: config.get('public_url') }, function(email, done) { User.findByEmail(email, function(err, user){ if (user){ return done(null, user); } else{ user = new User({'email': email}); user.save(function(err, user){ if (err){ logger.error("Error saving user after login (" + email + ")"); } else{ return done(null, user); } }); } }); } )); var http = express.createServer(); var sessionStore = new RedisStore({ maxAge: (1).day }); // Express Configuration http.configure(function(){ http.set('views', __dirname + '/views'); http.set('view engine', 'ejs'); http.use(express.logger()); http.use(express.static(__dirname + '/public')); http.use(express.cookieParser()); http.use(express.bodyParser()); http.use(express.methodOverride()); //TODO: Load secret from config/env var http.use(express.session({ secret: 'As a kid I ran down the stairs at full speed because I imagined Indians with bows and arrows would hit me if I walked.', key: 'express.sid', store: sessionStore })); // Initialize Passport! http.use(passport.initialize()); // Support persistent sessions: http.use(passport.session()); http.use(http.router); }); http.configure('development', function(){ http.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); http.configure('production', function(){ http.use(express.errorHandler()); }); // HTTP Routes routes = { site: require('./controllers/site'), social: require('./controllers/social'), profile: require('./controllers/profile') }; http.get('/', routes.site.index); http.get('/login', routes.site.login); http.get('/logout', routes.site.logout); http.post('/auth/browserid', passport.authenticate('browserid', { failureRedirect: '/login' }), routes.site.authenticate); http.get('/social/worker.js', routes.social.worker); http.get('/social/sidebar', routes.social.sidebar); http.get('/social/manifest.json', routes.social.manifest); http.get('/profile', application.authenticate, routes.profile.index.get); http.put('/profile', application.authenticate, routes.profile.index.put); http.post('/profile/nick', application.authenticate, routes.profile.nick.post); process.on('uncaughtException', function(err) { logger.error(err); }); http.listen(config.get('bind_to').port); socket.listen(http, sessionStore); if (http.address() == null){ logger.error("Error listening to " + JSON.stringify(config.get('bind_to'))); process.exit(1); } logger.info(("MoTown HTTP server listening on port %d in %s mode", http.address().port, http.settings.env));
Adding some installation instructions.
app/http/server.js
Adding some installation instructions.
<ide><path>pp/http/server.js <ide> routes = { <ide> site: require('./controllers/site'), <ide> social: require('./controllers/social'), <del> profile: require('./controllers/profile') <add> profile: require('./controllers/profile'), <add> feeds: require('./controllers/feeds') <ide> }; <ide> <ide> <ide> http.put('/profile', application.authenticate, routes.profile.index.put); <ide> http.post('/profile/nick', application.authenticate, routes.profile.nick.post); <ide> <add>http.get('/feeds', application.authenticate, routes.feeds.index.get); <add> <ide> <ide> process.on('uncaughtException', function(err) { <ide> logger.error(err);
Java
mit
0a0856cdcc2f80e53c05314e2953582996ad5b2b
0
pwall567/javautil
/* * @(#) SyncQueue.java * * javautil Java Utility Library * Copyright (c) 2013, 2014, 2015 Peter Wall * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pwall.util; import java.util.ArrayList; import java.util.List; /** * Class to represent a synchronized first-in first-out queue. Objects may be added to the end * or inserted at the beginning of the queue, and reads will cause the thread to wait until data * is available. An optional maximum capacity may be specified; in that case the thread trying * to add to the queue will block until space is available. * * @author Peter Wall */ public class SyncQueue<T> { public static final int defaultInitialCapacity = 10; public static final int defaultMaxLength = 0; // indicates no limit private List<T> queue; private int maxLength; /** * Construct a {@code SyncQueue} with the specified initial capacity and maximum size. * * @param initialCapacity the initial capacity of the queue * @param maxLength the maximum length of the queue */ public SyncQueue(int initialCapacity, int maxLength) { queue = new ArrayList<>(initialCapacity); this.maxLength = maxLength; } /** * Construct a {@code SyncQueue} with the specified initial capacity. * * @param initialCapacity the initial capacity of the queue */ public SyncQueue(int initialCapacity) { this(initialCapacity, defaultMaxLength); } /** * Construct a {@code SyncQueue} with the default initial capacity. */ public SyncQueue() { this(defaultInitialCapacity); } /** * Add an object to the end of the queue and wake up all threads currently waiting for this * queue. * * @param object the object to be added * @return {@code true} if the operation was successful */ public synchronized boolean add(T object) { if (!checkCapacity()) return false; queue.add(object); notifyAll(); return true; } /** * Add an object to the end of the queue and wake up all threads currently waiting for this * queue. If there is already an object in the queue identical to the one supplied, don't * add the new one. * * @param object the object to be added * @return {@code true} if the operation was successful */ public synchronized boolean addUnique(T object) { if (queue.contains(object)) return true; if (!checkCapacity()) return false; queue.add(object); notifyAll(); return true; } /** * Insert an object at the beginning of the queue and wake up all threads currently waiting * for this queue. * * @param object the object to be added * @return {@code true} if the operation was successful */ public synchronized boolean insert(T object) { if (!checkCapacity()) return false; queue.add(0, object); notifyAll(); return true; } /** * Insert an object at the beginning of the queue and wake up all threads currently waiting * for this queue. If there is already an object in the queue identical to the one * supplied, delete it first and insert the new one at the start. * * @param object the object to be added * @return {@code true} if the operation was successful */ public synchronized boolean insertUnique(T object) { queue.remove(object); if (!checkCapacity()) return false; queue.add(0, object); notifyAll(); return true; } /** * Wait for the queue to have capacity to take another entry. * * @return {@code true} if the queue has capacity; {@code false} if the thread was * interrupted while waiting for capacity */ private boolean checkCapacity() { if (maxLength > 0) { while (queue.size() >= maxLength) { try { wait(); } catch (InterruptedException e) { return false; } } } return true; } /** * Remove the specified object from the queue. * * @param object the object to be removed * @return {@code true} if the object was removed */ public synchronized boolean remove(T object) { if (!queue.remove(object)) return false; notifyAll(); return true; } /** * Get the next object from the queue, blocking if none is available. The method will * return {@code null} if the thread is interrupted. * * @return the next object, or {@code null} */ public synchronized T get() { while (queue.size() == 0) { try { wait(); } catch (InterruptedException e) { return null; } } T result = queue.remove(0); notifyAll(); return result; } /** * Determine the current length of the queue. * * @return the number of objects currently in the queue */ public synchronized int getSize() { return queue.size(); } /** * Get the maximum queue length. * * @return the maximum queue length */ public synchronized int getMaxLength() { return maxLength; } /** * Get the maximum queue length. * * @param maxLength the maximum queue length */ public synchronized void setMaxLength(int maxLength) { this.maxLength = maxLength; } }
src/main/java/net/pwall/util/SyncQueue.java
/* * @(#) SyncQueue.java * * javautil Java Utility Library * Copyright (c) 2013, 2014 Peter Wall * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pwall.util; import java.util.ArrayList; import java.util.List; /** * Class to represent a synchronized first-in first-out queue. Objects may be added to the end * of the queue, and reads will cause the thread to wait until data is available. * * @author Peter Wall */ public class SyncQueue<T> { public static final int defaultInitialCapacity = 10; public static final int defaultMaxLength = 0; private List<T> queue; private int maxLength; /** * Construct a {@code SyncQueue} with the specified initial capacity. * * @param initialCapacity the initial capacity of the queue * @param maxLength the maximum length of the queue */ public SyncQueue(int initialCapacity, int maxLength) { queue = new ArrayList<>(initialCapacity); this.maxLength = maxLength; } /** * Construct a {@code SyncQueue} with the specified initial capacity. * * @param initialCapacity the initial capacity of the queue */ public SyncQueue(int initialCapacity) { this(initialCapacity, defaultMaxLength); } /** * Construct a {@code SyncQueue} with an initial capacity of 10. */ public SyncQueue() { this(defaultInitialCapacity); } /** * Add an object to the end of the queue and wake up all threads currently waiting for this * queue. * * @param object the object to be added * @return {@code true} if the object was added */ public synchronized boolean add(T object) { if (!checkCapacity()) return false; queue.add(object); notifyAll(); return true; } /** * Add an object to the end of the queue and wake up all threads currently waiting for this * queue. If there is already an object in the queue identical to the one supplied, delete * it first. * * @param object the object to be added * @return {@code true} if the object was added */ public synchronized boolean addUnique(T object) { queue.remove(object); if (!checkCapacity()) return false; queue.add(object); notifyAll(); return true; } /** * Insert an object at the beginning of the queue and wake up all threads currently waiting * for this queue. * * @param object the object to be added * @return {@code true} if the object was added */ public synchronized boolean insert(T object) { if (!checkCapacity()) return false; queue.add(0, object); notifyAll(); return true; } /** * Insert an object at the beginning of the queue and wake up all threads currently waiting * for this queue. If there is already an object in the queue identical to the one * supplied, delete it first. * * @param object the object to be added * @return {@code true} if the object was added */ public synchronized boolean insertUnique(T object) { queue.remove(object); if (!checkCapacity()) return false; queue.add(0, object); notifyAll(); return true; } /** * Check that the queue has the capacity to take another entry. * * @return {@code true} if the queue has capacity; {@code false} if the task was * interrupted while waiting for capacity */ private boolean checkCapacity() { if (maxLength > 0) { while (queue.size() >= maxLength) { try { wait(); } catch (InterruptedException e) { return false; } } } return true; } /** * Get the next object from the queue, blocking if none is available. The method will * return {@code null} is the thread is interrupted. * * @return the next object, or {@code null} */ public synchronized T get() { while (queue.size() == 0) { try { wait(); } catch (InterruptedException e) { return null; } } return queue.remove(0); } /** * Determine the current length of the queue. * * @return the number of objects currently in the queue */ public synchronized int getSize() { return queue.size(); } /** * Get the maximum queue length. * * @return the maximum queue length */ public synchronized int getMaxLength() { return maxLength; } /** * Get the maximum queue length. * * @param maxLength the maximum queue length */ public synchronized void setMaxLength(int maxLength) { this.maxLength = maxLength; } }
More enhancements to SyncQueue
src/main/java/net/pwall/util/SyncQueue.java
More enhancements to SyncQueue
<ide><path>rc/main/java/net/pwall/util/SyncQueue.java <ide> * @(#) SyncQueue.java <ide> * <ide> * javautil Java Utility Library <del> * Copyright (c) 2013, 2014 Peter Wall <add> * Copyright (c) 2013, 2014, 2015 Peter Wall <ide> * <ide> * Permission is hereby granted, free of charge, to any person obtaining a copy <ide> * of this software and associated documentation files (the "Software"), to deal <ide> <ide> /** <ide> * Class to represent a synchronized first-in first-out queue. Objects may be added to the end <del> * of the queue, and reads will cause the thread to wait until data is available. <add> * or inserted at the beginning of the queue, and reads will cause the thread to wait until data <add> * is available. An optional maximum capacity may be specified; in that case the thread trying <add> * to add to the queue will block until space is available. <ide> * <ide> * @author Peter Wall <ide> */ <ide> public class SyncQueue<T> { <ide> <ide> public static final int defaultInitialCapacity = 10; <del> public static final int defaultMaxLength = 0; <add> public static final int defaultMaxLength = 0; // indicates no limit <ide> <ide> private List<T> queue; <ide> private int maxLength; <ide> <ide> /** <del> * Construct a {@code SyncQueue} with the specified initial capacity. <add> * Construct a {@code SyncQueue} with the specified initial capacity and maximum size. <ide> * <ide> * @param initialCapacity the initial capacity of the queue <ide> * @param maxLength the maximum length of the queue <ide> } <ide> <ide> /** <del> * Construct a {@code SyncQueue} with an initial capacity of 10. <add> * Construct a {@code SyncQueue} with the default initial capacity. <ide> */ <ide> public SyncQueue() { <ide> this(defaultInitialCapacity); <ide> * queue. <ide> * <ide> * @param object the object to be added <del> * @return {@code true} if the object was added <add> * @return {@code true} if the operation was successful <ide> */ <ide> public synchronized boolean add(T object) { <ide> if (!checkCapacity()) <ide> <ide> /** <ide> * Add an object to the end of the queue and wake up all threads currently waiting for this <del> * queue. If there is already an object in the queue identical to the one supplied, delete <del> * it first. <del> * <del> * @param object the object to be added <del> * @return {@code true} if the object was added <add> * queue. If there is already an object in the queue identical to the one supplied, don't <add> * add the new one. <add> * <add> * @param object the object to be added <add> * @return {@code true} if the operation was successful <ide> */ <ide> public synchronized boolean addUnique(T object) { <del> queue.remove(object); <add> if (queue.contains(object)) <add> return true; <ide> if (!checkCapacity()) <ide> return false; <ide> queue.add(object); <ide> * for this queue. <ide> * <ide> * @param object the object to be added <del> * @return {@code true} if the object was added <add> * @return {@code true} if the operation was successful <ide> */ <ide> public synchronized boolean insert(T object) { <ide> if (!checkCapacity()) <ide> /** <ide> * Insert an object at the beginning of the queue and wake up all threads currently waiting <ide> * for this queue. If there is already an object in the queue identical to the one <del> * supplied, delete it first. <del> * <del> * @param object the object to be added <del> * @return {@code true} if the object was added <add> * supplied, delete it first and insert the new one at the start. <add> * <add> * @param object the object to be added <add> * @return {@code true} if the operation was successful <ide> */ <ide> public synchronized boolean insertUnique(T object) { <ide> queue.remove(object); <ide> } <ide> <ide> /** <del> * Check that the queue has the capacity to take another entry. <del> * <del> * @return {@code true} if the queue has capacity; {@code false} if the task was <add> * Wait for the queue to have capacity to take another entry. <add> * <add> * @return {@code true} if the queue has capacity; {@code false} if the thread was <ide> * interrupted while waiting for capacity <ide> */ <ide> private boolean checkCapacity() { <ide> } <ide> <ide> /** <add> * Remove the specified object from the queue. <add> * <add> * @param object the object to be removed <add> * @return {@code true} if the object was removed <add> */ <add> public synchronized boolean remove(T object) { <add> if (!queue.remove(object)) <add> return false; <add> notifyAll(); <add> return true; <add> } <add> <add> /** <ide> * Get the next object from the queue, blocking if none is available. The method will <del> * return {@code null} is the thread is interrupted. <add> * return {@code null} if the thread is interrupted. <ide> * <ide> * @return the next object, or {@code null} <ide> */ <ide> return null; <ide> } <ide> } <del> return queue.remove(0); <add> T result = queue.remove(0); <add> notifyAll(); <add> return result; <ide> } <ide> <ide> /**
Java
apache-2.0
e8e2e4b0515062f400445bde009001ba5c40173d
0
hsaputra/cdap,anthcp/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,caskdata/cdap,mpouttuclarke/cdap,caskdata/cdap,mpouttuclarke/cdap,hsaputra/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,hsaputra/cdap,anthcp/cdap,chtyim/cdap,anthcp/cdap,chtyim/cdap,caskdata/cdap,caskdata/cdap,hsaputra/cdap,mpouttuclarke/cdap
/* * Copyright © 2014 Cask Data, 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 co.cask.cdap.internal.app.runtime.batch; import co.cask.cdap.app.metrics.MapReduceMetrics; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.metrics.MetricsCollector; import co.cask.cdap.metrics.collect.MapReduceCounterCollectionService; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.TaskCounter; import org.apache.hadoop.mapreduce.TaskReport; import org.apache.hadoop.mapreduce.TaskType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Map; /** * Gathers statistics from a running mapreduce job through its counters and writes the data to the metrics system. */ public class MapReduceMetricsWriter { private static final Logger LOG = LoggerFactory.getLogger(MapReduceMetricsWriter.class); private static final String METRIC_INPUT_RECORDS = "process.entries.in"; private static final String METRIC_OUTPUT_RECORDS = "process.entries.out"; private static final String METRIC_BYTES = "process.bytes"; private static final String METRIC_COMPLETION = "process.completion"; private static final String METRIC_USED_CONTAINERS = "resources.used.containers"; private static final String METRIC_USED_MEMORY = "resources.used.memory"; private final Job jobConf; private final BasicMapReduceContext context; private final MetricsCollector mapperMetrics; private final MetricsCollector reducerMetrics; private final LoadingCache<String, MetricsCollector> mapTaskMetricsCollectors; private final LoadingCache<String, MetricsCollector> reduceTaskMetricsCollectors; public MapReduceMetricsWriter(Job jobConf, BasicMapReduceContext context) { this.jobConf = jobConf; this.context = context; this.mapperMetrics = context.getProgramMetrics().childCollector(Constants.Metrics.Tag.MR_TASK_TYPE, MapReduceMetrics.TaskType.Mapper.getId()); this.reducerMetrics = context.getProgramMetrics().childCollector(Constants.Metrics.Tag.MR_TASK_TYPE, MapReduceMetrics.TaskType.Reducer.getId()); this.mapTaskMetricsCollectors = CacheBuilder.newBuilder() .build(new CacheLoader<String, MetricsCollector>() { @Override public MetricsCollector load(String taskId) { return mapperMetrics.childCollector(Constants.Metrics.Tag.INSTANCE_ID, taskId); } }); this.reduceTaskMetricsCollectors = CacheBuilder.newBuilder() .build(new CacheLoader<String, MetricsCollector>() { @Override public MetricsCollector load(String taskId) { return reducerMetrics.childCollector(Constants.Metrics.Tag.INSTANCE_ID, taskId); } }); } public void reportStats() throws IOException, InterruptedException { Counters jobCounters = jobConf.getCounters(); reportMapredStats(jobCounters); reportSystemStats(jobCounters); } // job level stats from counters built in to mapreduce private void reportMapredStats(Counters jobCounters) throws IOException, InterruptedException { JobStatus jobStatus = jobConf.getStatus(); // map stats float mapProgress = jobStatus.getMapProgress(); int runningMappers = 0; int runningReducers = 0; for (TaskReport tr : jobConf.getTaskReports(TaskType.MAP)) { reportMapTaskMetrics(tr); runningMappers += tr.getRunningTaskAttemptIds().size(); } for (TaskReport tr : jobConf.getTaskReports(TaskType.REDUCE)) { reportReduceTaskMetrics(tr); runningReducers += tr.getRunningTaskAttemptIds().size(); } int memoryPerMapper = jobConf.getConfiguration().getInt(Job.MAP_MEMORY_MB, Job.DEFAULT_MAP_MEMORY_MB); int memoryPerReducer = jobConf.getConfiguration().getInt(Job.REDUCE_MEMORY_MB, Job.DEFAULT_REDUCE_MEMORY_MB); long mapInputRecords = getTaskCounter(jobCounters, TaskCounter.MAP_INPUT_RECORDS); long mapOutputRecords = getTaskCounter(jobCounters, TaskCounter.MAP_OUTPUT_RECORDS); long mapOutputBytes = getTaskCounter(jobCounters, TaskCounter.MAP_OUTPUT_BYTES); mapperMetrics.gauge(METRIC_COMPLETION, (long) (mapProgress * 100)); mapperMetrics.gauge(METRIC_INPUT_RECORDS, mapInputRecords); mapperMetrics.gauge(METRIC_OUTPUT_RECORDS, mapOutputRecords); mapperMetrics.gauge(METRIC_BYTES, mapOutputBytes); mapperMetrics.gauge(METRIC_USED_CONTAINERS, runningMappers); mapperMetrics.gauge(METRIC_USED_MEMORY, runningMappers * memoryPerMapper); LOG.trace("Reporting mapper stats: (completion, ins, outs, bytes, containers, memory) = ({}, {}, {}, {}, {}, {})", (int) (mapProgress * 100), mapInputRecords, mapOutputRecords, mapOutputBytes, runningMappers, runningMappers * memoryPerMapper); // reduce stats float reduceProgress = jobStatus.getReduceProgress(); long reduceInputRecords = getTaskCounter(jobCounters, TaskCounter.REDUCE_INPUT_RECORDS); long reduceOutputRecords = getTaskCounter(jobCounters, TaskCounter.REDUCE_OUTPUT_RECORDS); reducerMetrics.gauge(METRIC_COMPLETION, (long) (reduceProgress * 100)); reducerMetrics.gauge(METRIC_INPUT_RECORDS, reduceInputRecords); reducerMetrics.gauge(METRIC_OUTPUT_RECORDS, reduceOutputRecords); reducerMetrics.gauge(METRIC_USED_CONTAINERS, runningReducers); reducerMetrics.gauge(METRIC_USED_MEMORY, runningReducers * memoryPerReducer); LOG.trace("Reporting reducer stats: (completion, ins, outs, containers, memory) = ({}, {}, {}, {}, {})", (int) (reduceProgress * 100), reduceInputRecords, reduceOutputRecords, runningReducers, runningReducers * memoryPerReducer); } private void reportMapTaskMetrics(TaskReport taskReport) { Counters counters = taskReport.getTaskCounters(); MetricsCollector metricsCollector = mapTaskMetricsCollectors.getUnchecked(taskReport.getTaskId()); metricsCollector.gauge(METRIC_INPUT_RECORDS, getTaskCounter(counters, TaskCounter.MAP_INPUT_RECORDS)); metricsCollector.gauge(METRIC_OUTPUT_RECORDS, getTaskCounter(counters, TaskCounter.MAP_OUTPUT_RECORDS)); metricsCollector.gauge(METRIC_BYTES, getTaskCounter(counters, TaskCounter.MAP_OUTPUT_BYTES)); metricsCollector.gauge(METRIC_COMPLETION, (long) (taskReport.getProgress() * 100)); } private void reportReduceTaskMetrics(TaskReport taskReport) { Counters counters = taskReport.getTaskCounters(); MetricsCollector metricsCollector = reduceTaskMetricsCollectors.getUnchecked(taskReport.getTaskId()); metricsCollector.gauge(METRIC_INPUT_RECORDS, getTaskCounter(counters, TaskCounter.REDUCE_INPUT_RECORDS)); metricsCollector.gauge(METRIC_OUTPUT_RECORDS, getTaskCounter(counters, TaskCounter.REDUCE_OUTPUT_RECORDS)); metricsCollector.gauge(METRIC_COMPLETION, (long) (taskReport.getProgress() * 100)); } // report system stats coming from user metrics or dataset operations private void reportSystemStats(Counters jobCounters) { for (String group : jobCounters.getGroupNames()) { if (group.startsWith("cdap.")) { Map<String, String> tags = MapReduceCounterCollectionService.parseTags(group); // todo: use some caching? MetricsCollector collector = context.getProgramMetrics().childCollector(tags); // Note: all mapreduce metrics are reported as gauges due to how mapreduce counters work; // we may later emit metrics right from the tasks into the metrics system to overcome this limitation for (Counter counter : jobCounters.getGroup(group)) { collector.gauge(counter.getName(), counter.getValue()); } } } } private long getTaskCounter(Counters jobCounters, TaskCounter taskCounter) { return jobCounters.findCounter(TaskCounter.class.getName(), taskCounter.name()).getValue(); } }
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/batch/MapReduceMetricsWriter.java
/* * Copyright © 2014 Cask Data, 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 co.cask.cdap.internal.app.runtime.batch; import co.cask.cdap.app.metrics.MapReduceMetrics; import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.metrics.MetricsCollector; import co.cask.cdap.metrics.collect.MapReduceCounterCollectionService; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.TaskCounter; import org.apache.hadoop.mapreduce.TaskReport; import org.apache.hadoop.mapreduce.TaskType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Map; /** * Gathers statistics from a running mapreduce job through its counters and writes the data to the metrics system. */ public class MapReduceMetricsWriter { private static final Logger LOG = LoggerFactory.getLogger(MapReduceMetricsWriter.class); private static final String METRIC_INPUT_RECORDS = "process.entries.in"; private static final String METRIC_OUTPUT_RECORDS = "process.entries.out"; private static final String METRIC_BYTES = "process.bytes"; private static final String METRIC_COMPLETION = "process.completion"; private static final String METRIC_USED_CONTAINERS = "resources.used.containers"; private static final String METRIC_USED_MEMORY = "resources.used.memory"; private final Job jobConf; private final BasicMapReduceContext context; private final MetricsCollector mapperMetrics; private final MetricsCollector reducerMetrics; public MapReduceMetricsWriter(Job jobConf, BasicMapReduceContext context) { this.jobConf = jobConf; this.context = context; this.mapperMetrics = context.getProgramMetrics().childCollector(Constants.Metrics.Tag.MR_TASK_TYPE, MapReduceMetrics.TaskType.Mapper.getId()); this.reducerMetrics = context.getProgramMetrics().childCollector(Constants.Metrics.Tag.MR_TASK_TYPE, MapReduceMetrics.TaskType.Reducer.getId()); } public void reportStats() throws IOException, InterruptedException { Counters jobCounters = jobConf.getCounters(); reportMapredStats(jobCounters); reportSystemStats(jobCounters); } // job level stats from counters built in to mapreduce private void reportMapredStats(Counters jobCounters) throws IOException, InterruptedException { JobStatus jobStatus = jobConf.getStatus(); // map stats float mapProgress = jobStatus.getMapProgress(); int runningMappers = 0; int runningReducers = 0; for (TaskReport tr : jobConf.getTaskReports(TaskType.MAP)) { runningMappers += tr.getRunningTaskAttemptIds().size(); } for (TaskReport tr : jobConf.getTaskReports(TaskType.REDUCE)) { runningReducers += tr.getRunningTaskAttemptIds().size(); } int memoryPerMapper = jobConf.getConfiguration().getInt(Job.MAP_MEMORY_MB, Job.DEFAULT_MAP_MEMORY_MB); int memoryPerReducer = jobConf.getConfiguration().getInt(Job.REDUCE_MEMORY_MB, Job.DEFAULT_REDUCE_MEMORY_MB); long mapInputRecords = getTaskCounter(jobCounters, TaskCounter.MAP_INPUT_RECORDS); long mapOutputRecords = getTaskCounter(jobCounters, TaskCounter.MAP_OUTPUT_RECORDS); long mapOutputBytes = getTaskCounter(jobCounters, TaskCounter.MAP_OUTPUT_BYTES); mapperMetrics.gauge(METRIC_COMPLETION, (long) (mapProgress * 100)); mapperMetrics.gauge(METRIC_INPUT_RECORDS, mapInputRecords); mapperMetrics.gauge(METRIC_OUTPUT_RECORDS, mapOutputRecords); mapperMetrics.gauge(METRIC_BYTES, mapOutputBytes); mapperMetrics.gauge(METRIC_USED_CONTAINERS, runningMappers); mapperMetrics.gauge(METRIC_USED_MEMORY, runningMappers * memoryPerMapper); LOG.trace("Reporting mapper stats: (completion, ins, outs, bytes, containers, memory) = ({}, {}, {}, {}, {}, {})", (int) (mapProgress * 100), mapInputRecords, mapOutputRecords, mapOutputBytes, runningMappers, runningMappers * memoryPerMapper); // reduce stats float reduceProgress = jobStatus.getReduceProgress(); long reduceInputRecords = getTaskCounter(jobCounters, TaskCounter.REDUCE_INPUT_RECORDS); long reduceOutputRecords = getTaskCounter(jobCounters, TaskCounter.REDUCE_OUTPUT_RECORDS); reducerMetrics.gauge(METRIC_COMPLETION, (long) (reduceProgress * 100)); reducerMetrics.gauge(METRIC_INPUT_RECORDS, reduceInputRecords); reducerMetrics.gauge(METRIC_OUTPUT_RECORDS, reduceOutputRecords); reducerMetrics.gauge(METRIC_USED_CONTAINERS, runningReducers); reducerMetrics.gauge(METRIC_USED_MEMORY, runningReducers * memoryPerReducer); LOG.trace("Reporting reducer stats: (completion, ins, outs, containers, memory) = ({}, {}, {}, {}, {})", (int) (reduceProgress * 100), reduceInputRecords, reduceOutputRecords, runningReducers, runningReducers * memoryPerReducer); } // report system stats coming from user metrics or dataset operations private void reportSystemStats(Counters jobCounters) throws IOException, InterruptedException { for (String group : jobCounters.getGroupNames()) { if (group.startsWith("cdap.")) { Map<String, String> tags = MapReduceCounterCollectionService.parseTags(group); // todo: use some caching? MetricsCollector collector = context.getProgramMetrics().childCollector(tags); // Note: all mapreduce metrics are reported as gauges due to how mapreduce counters work; // we may later emit metrics right from the tasks into the metrics system to overcome this limitation for (Counter counter : jobCounters.getGroup(group)) { collector.gauge(counter.getName(), counter.getValue()); } } } } private long getTaskCounter(Counters jobCounters, TaskCounter taskCounter) throws IOException, InterruptedException { return jobCounters.findCounter(TaskCounter.class.getName(), taskCounter.name()).getValue(); } }
Emit MR metrics to metricsCollector on task granularity.
cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/batch/MapReduceMetricsWriter.java
Emit MR metrics to metricsCollector on task granularity.
<ide><path>dap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/batch/MapReduceMetricsWriter.java <ide> import co.cask.cdap.common.conf.Constants; <ide> import co.cask.cdap.common.metrics.MetricsCollector; <ide> import co.cask.cdap.metrics.collect.MapReduceCounterCollectionService; <add>import com.google.common.cache.CacheBuilder; <add>import com.google.common.cache.CacheLoader; <add>import com.google.common.cache.LoadingCache; <ide> import org.apache.hadoop.mapreduce.Counter; <ide> import org.apache.hadoop.mapreduce.Counters; <ide> import org.apache.hadoop.mapreduce.Job; <ide> private final BasicMapReduceContext context; <ide> private final MetricsCollector mapperMetrics; <ide> private final MetricsCollector reducerMetrics; <add> private final LoadingCache<String, MetricsCollector> mapTaskMetricsCollectors; <add> private final LoadingCache<String, MetricsCollector> reduceTaskMetricsCollectors; <ide> <ide> public MapReduceMetricsWriter(Job jobConf, BasicMapReduceContext context) { <ide> this.jobConf = jobConf; <ide> MapReduceMetrics.TaskType.Mapper.getId()); <ide> this.reducerMetrics = context.getProgramMetrics().childCollector(Constants.Metrics.Tag.MR_TASK_TYPE, <ide> MapReduceMetrics.TaskType.Reducer.getId()); <add> this.mapTaskMetricsCollectors = CacheBuilder.newBuilder() <add> .build(new CacheLoader<String, MetricsCollector>() { <add> @Override <add> public MetricsCollector load(String taskId) { <add> return mapperMetrics.childCollector(Constants.Metrics.Tag.INSTANCE_ID, taskId); <add> } <add> }); <add> this.reduceTaskMetricsCollectors = CacheBuilder.newBuilder() <add> .build(new CacheLoader<String, MetricsCollector>() { <add> @Override <add> public MetricsCollector load(String taskId) { <add> return reducerMetrics.childCollector(Constants.Metrics.Tag.INSTANCE_ID, taskId); <add> } <add> }); <ide> } <ide> <ide> public void reportStats() throws IOException, InterruptedException { <ide> int runningMappers = 0; <ide> int runningReducers = 0; <ide> for (TaskReport tr : jobConf.getTaskReports(TaskType.MAP)) { <add> reportMapTaskMetrics(tr); <ide> runningMappers += tr.getRunningTaskAttemptIds().size(); <ide> } <ide> for (TaskReport tr : jobConf.getTaskReports(TaskType.REDUCE)) { <add> reportReduceTaskMetrics(tr); <ide> runningReducers += tr.getRunningTaskAttemptIds().size(); <ide> } <ide> int memoryPerMapper = jobConf.getConfiguration().getInt(Job.MAP_MEMORY_MB, Job.DEFAULT_MAP_MEMORY_MB); <ide> runningReducers * memoryPerReducer); <ide> } <ide> <add> private void reportMapTaskMetrics(TaskReport taskReport) { <add> Counters counters = taskReport.getTaskCounters(); <add> MetricsCollector metricsCollector = mapTaskMetricsCollectors.getUnchecked(taskReport.getTaskId()); <add> metricsCollector.gauge(METRIC_INPUT_RECORDS, getTaskCounter(counters, TaskCounter.MAP_INPUT_RECORDS)); <add> metricsCollector.gauge(METRIC_OUTPUT_RECORDS, getTaskCounter(counters, TaskCounter.MAP_OUTPUT_RECORDS)); <add> metricsCollector.gauge(METRIC_BYTES, getTaskCounter(counters, TaskCounter.MAP_OUTPUT_BYTES)); <add> metricsCollector.gauge(METRIC_COMPLETION, (long) (taskReport.getProgress() * 100)); <add> } <add> <add> private void reportReduceTaskMetrics(TaskReport taskReport) { <add> Counters counters = taskReport.getTaskCounters(); <add> MetricsCollector metricsCollector = reduceTaskMetricsCollectors.getUnchecked(taskReport.getTaskId()); <add> metricsCollector.gauge(METRIC_INPUT_RECORDS, getTaskCounter(counters, TaskCounter.REDUCE_INPUT_RECORDS)); <add> metricsCollector.gauge(METRIC_OUTPUT_RECORDS, getTaskCounter(counters, TaskCounter.REDUCE_OUTPUT_RECORDS)); <add> metricsCollector.gauge(METRIC_COMPLETION, (long) (taskReport.getProgress() * 100)); <add> } <add> <ide> // report system stats coming from user metrics or dataset operations <del> private void reportSystemStats(Counters jobCounters) throws IOException, InterruptedException { <add> private void reportSystemStats(Counters jobCounters) { <ide> for (String group : jobCounters.getGroupNames()) { <ide> if (group.startsWith("cdap.")) { <ide> <ide> } <ide> } <ide> <del> private long getTaskCounter(Counters jobCounters, TaskCounter taskCounter) throws IOException, InterruptedException { <add> private long getTaskCounter(Counters jobCounters, TaskCounter taskCounter) { <ide> return jobCounters.findCounter(TaskCounter.class.getName(), taskCounter.name()).getValue(); <ide> } <ide>
Java
lgpl-2.1
0815703bff3793194bede18c057f04f6f18b3ba1
0
alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.ui.login; import org.opencms.i18n.CmsMessages; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.ui.CmsVaadinUtils; import org.opencms.workplace.CmsWorkplace; import java.util.List; import java.util.Locale; import java.util.Map; import com.google.common.collect.Maps; import com.vaadin.annotations.DesignRoot; import com.vaadin.server.ExternalResource; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Image; import com.vaadin.ui.Label; import com.vaadin.ui.OptionGroup; import com.vaadin.ui.VerticalLayout; import elemental.events.KeyboardEvent.KeyCode; /** * Login form.<p> */ @DesignRoot public class CmsLoginForm extends VerticalLayout { /** Version id. */ private static final long serialVersionUID = 1L; /** The label showing the copyright information. */ private Label m_copyright; /** The security field, which allows the user to choose between a private or public PC. */ private OptionGroup m_securityField; /** Widget for entering the user name. */ private CmsLoginUserField m_userField; /** Widget for entering the password. */ private CmsLoginPasswordField m_passwordField; /** Widget for OU selection. */ private CmsLoginOuSelector m_ouSelect; /** Login button. */ private Button m_loginButton; /** OpenCms logo. */ private Image m_logo; /** The login controller. */ private CmsLoginController m_controller; /** * Creates a new instance.<p> * * @param controller the login controller * @param locale the locale to use */ @SuppressWarnings("serial") public CmsLoginForm(CmsLoginController controller, Locale locale) { m_controller = controller; final CmsMessages messages = org.opencms.workplace.Messages.get().getBundle(locale); Map<String, String> macros = Maps.newHashMap(); macros.put("showSecure", "" + controller.isShowSecure()); String pctype = controller.getPcType(); CmsVaadinUtils.readAndLocalizeDesign(this, messages, macros); m_securityField.addItem("public"); m_securityField.addItem("private"); m_securityField.setValue(pctype); m_copyright.setContentMode(ContentMode.HTML); m_copyright.setValue(CmsLoginHelper.getCopyrightHtml(locale)); m_securityField.setItemCaption( "private", messages.key(org.opencms.workplace.Messages.GUI_LOGIN_PCTYPE_PRIVATE_0)); m_securityField.setItemCaption( "public", messages.key(org.opencms.workplace.Messages.GUI_LOGIN_PCTYPE_PUBLIC_0)); setWidth("700px"); m_logo.setSource(new ExternalResource(CmsWorkplace.getResourceUri("commons/login_logo.png"))); setComponentAlignment(m_logo, Alignment.MIDDLE_CENTER); m_loginButton.setClickShortcut(KeyCode.ENTER); m_loginButton.addClickListener(new ClickListener() { @SuppressWarnings("synthetic-access") public void buttonClick(ClickEvent event) { m_controller.onClickLogin(); } }); addAttachListener(new AttachListener() { @SuppressWarnings("synthetic-access") public void attach(AttachEvent event) { m_userField.focus(); } }); } /** * Gets the OU.<p> * * @return the OU */ public String getOrgUnit() { return m_ouSelect.getValue(); } /** * Gets the password.<p> * * @return the password */ public String getPassword() { return m_passwordField.getValue(); } /** * Gets the PC type.<p> * * @return the PC type */ public String getPcType() { return "" + m_securityField.getValue(); } /** * Gets the user.<p> * * @return the user */ public String getUser() { return m_userField.getValue(); } /** * Selects a specific org unit.<p> * * @param preselectedOu the OU to select */ public void selectOrgUnit(String preselectedOu) { m_ouSelect.setValue(preselectedOu); } /** * Sets the org units available for selection.<p> * * @param ous the ous */ public void setSelectableOrgUnits(List<CmsOrganizationalUnit> ous) { m_ouSelect.initOrgUnits(ous); } }
src/org/opencms/ui/login/CmsLoginForm.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.ui.login; import org.opencms.i18n.CmsMessages; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.ui.CmsVaadinUtils; import org.opencms.workplace.CmsWorkplace; import java.util.List; import java.util.Locale; import java.util.Map; import com.google.common.collect.Maps; import com.vaadin.annotations.DesignRoot; import com.vaadin.server.ExternalResource; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Image; import com.vaadin.ui.Label; import com.vaadin.ui.OptionGroup; import com.vaadin.ui.VerticalLayout; import elemental.events.KeyboardEvent.KeyCode; /** * Login form.<p> */ @DesignRoot public class CmsLoginForm extends VerticalLayout { /** Version id. */ private static final long serialVersionUID = 1L; /** The label showing the copyright information. */ private Label m_copyright; /** The security field, which allows the user to choose between a private or public PC. */ private OptionGroup m_securityField; /** Widget for entering the user name. */ private CmsLoginUserField m_userField; /** Widget for entering the password. */ private CmsLoginPasswordField m_passwordField; /** Widget for OU selection. */ private CmsLoginOuSelector m_ouSelect; /** Login button. */ private Button m_loginButton; /** OpenCms logo. */ private Image m_logo; /** The login controller. */ private CmsLoginController m_controller; /** * Creates a new instance.<p> * * @param controller the login controller * @param locale the locale to use */ @SuppressWarnings("serial") public CmsLoginForm(CmsLoginController controller, Locale locale) { m_controller = controller; final CmsMessages messages = org.opencms.workplace.Messages.get().getBundle(locale); Map<String, String> macros = Maps.newHashMap(); macros.put("showSecure", "" + controller.isShowSecure()); String pctype = controller.getPcType(); CmsVaadinUtils.readAndLocalizeDesign(this, messages, macros); m_securityField.addItem("public"); m_securityField.addItem("private"); m_securityField.setValue(pctype); m_copyright.setContentMode(ContentMode.HTML); m_copyright.setValue(CmsLoginHelper.getCopyrightHtml(locale)); m_securityField.setItemCaption( "private", messages.key(org.opencms.workplace.Messages.GUI_LOGIN_PCTYPE_PRIVATE_0)); m_securityField.setItemCaption( "public", messages.key(org.opencms.workplace.Messages.GUI_LOGIN_PCTYPE_PUBLIC_0)); setWidth("700px"); m_logo.setSource(new ExternalResource(CmsWorkplace.getResourceUri("commons/login_logo.png"))); setComponentAlignment(m_logo, Alignment.MIDDLE_CENTER); m_loginButton.setClickShortcut(KeyCode.ENTER); m_loginButton.addClickListener(new ClickListener() { @SuppressWarnings("synthetic-access") public void buttonClick(ClickEvent event) { m_controller.onClickLogin(); } }); } /** * Gets the OU.<p> * * @return the OU */ public String getOrgUnit() { return m_ouSelect.getValue(); } /** * Gets the password.<p> * * @return the password */ public String getPassword() { return m_passwordField.getValue(); } /** * Gets the PC type.<p> * * @return the PC type */ public String getPcType() { return "" + m_securityField.getValue(); } /** * Gets the user.<p> * * @return the user */ public String getUser() { return m_userField.getValue(); } /** * Selects a specific org unit.<p> * * @param preselectedOu the OU to select */ public void selectOrgUnit(String preselectedOu) { m_ouSelect.setValue(preselectedOu); } /** * Sets the org units available for selection.<p> * * @param ous the ous */ public void setSelectableOrgUnits(List<CmsOrganizationalUnit> ous) { m_ouSelect.initOrgUnits(ous); } }
Made login form focus on the user name field after page load.
src/org/opencms/ui/login/CmsLoginForm.java
Made login form focus on the user name field after page load.
<ide><path>rc/org/opencms/ui/login/CmsLoginForm.java <ide> } <ide> <ide> }); <add> addAttachListener(new AttachListener() { <add> <add> @SuppressWarnings("synthetic-access") <add> public void attach(AttachEvent event) { <add> <add> m_userField.focus(); <add> } <add> }); <ide> <ide> } <ide>
Java
isc
bef716f99c0fc2502030859fa5e1718b32043be9
0
j256/ormlite-core
package com.j256.ormlite.db; import java.sql.Driver; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.j256.ormlite.field.DataPersister; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.FieldConverter; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.DatabaseTableConfig; /** * Definition of the per-database functionality needed to isolate the differences between the various databases. * * @author graywatson */ public interface DatabaseType { /** * Return true if the database URL corresponds to this database type. Usually the URI is in the form jdbc:ddd:... * where ddd is the driver url part. */ public boolean isDatabaseUrlThisType(String url, String dbTypePart); /** * Load the driver class associated with this database so it can wire itself into JDBC. * * @throws SQLException * If the driver class is not available in the classpath. */ public void loadDriver() throws SQLException; /** * Set the driver instance on the database type. */ public void setDriver(Driver driver); /** * Takes a {@link FieldType} and appends the SQL necessary to create the field to the string builder. The field may * also generate additional arguments which go at the end of the insert statement or additional statements to be * executed before or afterwards depending on the configurations. The database can also add to the list of queries * that will be performed afterward to test portions of the config. */ public void appendColumnArg(String tableName, StringBuilder sb, FieldType fieldType, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException; /** * Appends information about primary key field(s) to the additional-args or other lists. */ public void addPrimaryKeySql(FieldType[] fieldTypes, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException; /** * Appends information about unique field(s) to the additional-args or other lists. */ public void addUniqueComboSql(FieldType[] fieldTypes, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException; /** * Takes a {@link FieldType} and adds the necessary statements to the before and after lists necessary so that the * dropping of the table will succeed and will clear other associated sequences or other database artifacts */ public void dropColumnArg(FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter); /** * Add a entity-name word to the string builder wrapped in the proper characters to escape it. This avoids problems * with table, column, and sequence-names being reserved words. */ public void appendEscapedEntityName(StringBuilder sb, String word); /** * Add the word to the string builder wrapped in the proper characters to escape it. This avoids problems with data * values being reserved words. */ public void appendEscapedWord(StringBuilder sb, String word); /** * Return the name of an ID sequence based on the tabelName and the fieldType of the id. */ public String generateIdSequenceName(String tableName, FieldType idFieldType); /** * Return the prefix to put at the front of a SQL line to mark it as a comment. */ public String getCommentLinePrefix(); /** * Return true if the database needs a sequence when you use generated IDs. Some databases (H2, MySQL) create them * auto-magically. This also means that the database needs to query for a sequence value <i>before</i> the object is * inserted. For old[er] versions of Postgres, for example, the JDBC call-back stuff to get the just-inserted id * value does not work so we have to get the next sequence value by hand, assign it into the object, and then insert * the object -- yes two SQL statements. */ public boolean isIdSequenceNeeded(); /** * Return the DataPersister to associate with the DataType. This allows the database instance to convert a field as * necessary before it goes to the database. */ public DataPersister getDataPersister(DataPersister defaultPersister, FieldType fieldType); /** * Return the FieldConverter to associate with the DataType. This allows the database instance to convert a field as * necessary before it goes to the database. */ public FieldConverter getFieldConverter(DataPersister dataType, FieldType fieldType); /** * Return true if the database supports the width parameter on VARCHAR fields. */ public boolean isVarcharFieldWidthSupported(); /** * Return true if the database supports the LIMIT SQL command. Otherwise we have to use the * {@link PreparedStatement#setMaxRows} instead. See prepareSqlStatement in MappedPreparedQuery. */ public boolean isLimitSqlSupported(); /** * Return true if the LIMIT should be called after SELECT otherwise at the end of the WHERE (the default). */ public boolean isLimitAfterSelect(); /** * Append to the string builder the necessary SQL to limit the results to a certain number. With some database * types, the offset is an argument to the LIMIT so the offset value (which could be null or not) is passed in. The * database type can choose to ignore it. */ public void appendLimitValue(StringBuilder sb, long limit, Long offset); /** * Return true if the database supports the OFFSET SQL command in some form. */ public boolean isOffsetSqlSupported(); /** * Return true if the database supports the offset as a comma argument from the limit. This also means that the * limit _must_ be specified if the offset is specified */ public boolean isOffsetLimitArgument(); /** * Append to the string builder the necessary SQL to start the results at a certain row number. */ public void appendOffsetValue(StringBuilder sb, long offset); /** * Append the SQL necessary to get the next-value from a sequence. This is only necessary if * {@link #isIdSequenceNeeded} is true. */ public void appendSelectNextValFromSequence(StringBuilder sb, String sequenceName); /** * Append the SQL necessary to properly finish a CREATE TABLE line. */ public void appendCreateTableSuffix(StringBuilder sb); /** * Returns true if a 'CREATE TABLE' statement should return 0. False if &gt; 0. */ public boolean isCreateTableReturnsZero(); /** * Returns true if CREATE and DROP TABLE statements can return &lt; 0 and still have worked. Gross! */ public boolean isCreateTableReturnsNegative(); /** * Returns true if table and field names should be made uppercase. * * <p> * Turns out that Derby and Hsqldb are doing something wrong (IMO) with entity names. If you create a table with the * name "footable" (with the quotes) then it will be created as lowercase footable, case sensitive. However, if you * then issue the query 'select * from footable' (without quotes) it won't find the table because it gets promoted * to be FOOTABLE and is searched in a case sensitive manner. So for these databases, entity names have to be forced * to be uppercase so external queries will also work. * </p> */ public boolean isEntityNamesMustBeUpCase(); /** * Returns the uppercase version of an entity name. This is here in case someone wants to override the behavior of * the default method because of localization issues. */ public String upCaseEntityName(String entityName); /** * Returns the uppercase version of a string for generating and matching fields and methods. This is here in case * someone wants to override the behavior of the default locale because of localization issues around * capitalization. * * @param string * String to up case. * @param forceEnglish * Set to true to use the English locale otherwise false to use the default local one. */ public String upCaseString(String string, boolean forceEnglish); /** * Returns the lowercase version of a string for generating and fields and methods. This is here in case someone * wants to override the behavior of the default locale because of localization issues around capitalization. * * @param string * String to down case. * @param forceEnglish * Set to true to use the English locale otherwise false to use the default local one. */ public String downCaseString(String string, boolean forceEnglish); /** * Returns true if nested savePoints are supported, otherwise false. */ public boolean isNestedSavePointsSupported(); /** * Return an statement that doesn't do anything but which can be used to ping the database by sending it over a * database connection. */ public String getPingStatement(); /** * Returns true if batch operations should be done inside of a transaction. Default is false in which case * auto-commit disabling will be done. */ public boolean isBatchUseTransaction(); /** * Returns true if the table truncate operation is supported. */ public boolean isTruncateSupported(); /** * Returns true if the table creation IF NOT EXISTS syntax is supported. */ public boolean isCreateIfNotExistsSupported(); /** * Does the database support the "CREATE INDEX IF NOT EXISTS" SQL construct. By default this just calls * {@link #isCreateIfNotExistsSupported()}. */ public boolean isCreateIndexIfNotExistsSupported(); /** * Returns true if we have to select the value of the sequence before we insert a new data row. */ public boolean isSelectSequenceBeforeInsert(); /** * Does the database support the {@link DatabaseField#allowGeneratedIdInsert()} setting which allows people to * insert values into generated-id columns. */ public boolean isAllowGeneratedIdInsertSupported(); /** * Return the name of the database for logging purposes. */ public String getDatabaseName(); /** * Extract and return a custom database configuration for this class. * * @return null if no custom configuration extractor for this database type. */ public <T> DatabaseTableConfig<T> extractDatabaseTableConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException; /** * Append the SQL necessary to properly finish a "INSERT INTO xxx" line when there are no arguments. */ public void appendInsertNoColumns(StringBuilder sb); }
src/main/java/com/j256/ormlite/db/DatabaseType.java
package com.j256.ormlite.db; import java.sql.Driver; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import com.j256.ormlite.field.DataPersister; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.FieldConverter; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.DatabaseTableConfig; /** * Definition of the per-database functionality needed to isolate the differences between the various databases. * * @author graywatson */ public interface DatabaseType { /** * Return true if the database URL corresponds to this database type. Usually the URI is in the form jdbc:ddd:... * where ddd is the driver url part. */ public boolean isDatabaseUrlThisType(String url, String dbTypePart); /** * Load the driver class associated with this database so it can wire itself into JDBC. * * @throws SQLException * If the driver class is not available in the classpath. */ public void loadDriver() throws SQLException; /** * Set the driver instance on the database type. */ public void setDriver(Driver driver); /** * Takes a {@link FieldType} and appends the SQL necessary to create the field to the string builder. The field may * also generate additional arguments which go at the end of the insert statement or additional statements to be * executed before or afterwards depending on the configurations. The database can also add to the list of queries * that will be performed afterward to test portions of the config. */ public void appendColumnArg(String tableName, StringBuilder sb, FieldType fieldType, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException; /** * Appends information about primary key field(s) to the additional-args or other lists. */ public void addPrimaryKeySql(FieldType[] fieldTypes, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException; /** * Appends information about unique field(s) to the additional-args or other lists. */ public void addUniqueComboSql(FieldType[] fieldTypes, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException; /** * Takes a {@link FieldType} and adds the necessary statements to the before and after lists necessary so that the * dropping of the table will succeed and will clear other associated sequences or other database artifacts */ public void dropColumnArg(FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter); /** * Add a entity-name word to the string builder wrapped in the proper characters to escape it. This avoids problems * with table, column, and sequence-names being reserved words. */ public void appendEscapedEntityName(StringBuilder sb, String word); /** * Add the word to the string builder wrapped in the proper characters to escape it. This avoids problems with data * values being reserved words. */ public void appendEscapedWord(StringBuilder sb, String word); /** * Return the name of an ID sequence based on the tabelName and the fieldType of the id. */ public String generateIdSequenceName(String tableName, FieldType idFieldType); /** * Return the prefix to put at the front of a SQL line to mark it as a comment. */ public String getCommentLinePrefix(); /** * Return true if the database needs a sequence when you use generated IDs. Some databases (H2, MySQL) create them * auto-magically. This also means that the database needs to query for a sequence value <i>before</i> the object is * inserted. For old[er] versions of Postgres, for example, the JDBC call-back stuff to get the just-inserted id * value does not work so we have to get the next sequence value by hand, assign it into the object, and then insert * the object -- yes two SQL statements. */ public boolean isIdSequenceNeeded(); /** * Return the DataPersister to associate with the DataType. This allows the database instance to convert a field as * necessary before it goes to the database. */ public DataPersister getDataPersister(DataPersister defaultPersister, FieldType fieldType); /** * Return the FieldConverter to associate with the DataType. This allows the database instance to convert a field as * necessary before it goes to the database. */ public FieldConverter getFieldConverter(DataPersister dataType, FieldType fieldType); /** * Return true if the database supports the width parameter on VARCHAR fields. */ public boolean isVarcharFieldWidthSupported(); /** * Return true if the database supports the LIMIT SQL command. Otherwise we have to use the * {@link PreparedStatement#setMaxRows} instead. See prepareSqlStatement in MappedPreparedQuery. */ public boolean isLimitSqlSupported(); /** * Return true if the LIMIT should be called after SELECT otherwise at the end of the WHERE (the default). */ public boolean isLimitAfterSelect(); /** * Append to the string builder the necessary SQL to limit the results to a certain number. With some database * types, the offset is an argument to the LIMIT so the offset value (which could be null or not) is passed in. The * database type can choose to ignore it. */ public void appendLimitValue(StringBuilder sb, long limit, Long offset); /** * Return true if the database supports the OFFSET SQL command in some form. */ public boolean isOffsetSqlSupported(); /** * Return true if the database supports the offset as a comma argument from the limit. This also means that the * limit _must_ be specified if the offset is specified */ public boolean isOffsetLimitArgument(); /** * Append to the string builder the necessary SQL to start the results at a certain row number. */ public void appendOffsetValue(StringBuilder sb, long offset); /** * Append the SQL necessary to get the next-value from a sequence. This is only necessary if * {@link #isIdSequenceNeeded} is true. */ public void appendSelectNextValFromSequence(StringBuilder sb, String sequenceName); /** * Append the SQL necessary to properly finish a CREATE TABLE line. */ public void appendCreateTableSuffix(StringBuilder sb); /** * Returns true if a 'CREATE TABLE' statement should return 0. False if &gt; 0. */ public boolean isCreateTableReturnsZero(); /** * Returns true if CREATE and DROP TABLE statements can return &lt; 0 and still have worked. Gross! */ public boolean isCreateTableReturnsNegative(); /** * Returns true if table and field names should be made uppercase. * * <p> * Turns out that Derby and Hsqldb are doing something wrong (IMO) with entity names. If you create a table with the * name "footable" (with the quotes) then it will be created as lowercase footable, case sensitive. However, if you * then issue the query 'select * from footable' (without quotes) it won't find the table because it gets promoted * to be FOOTABLE and is searched in a case sensitive manner. So for these databases, entity names have to be forced * to be uppercase so external queries will also work. * </p> */ public boolean isEntityNamesMustBeUpCase(); /** * Returns the uppercase version of an entity name. This is here in case someone wants to override the behavior of * the default method because of localization issues. */ public String upCaseEntityName(String entityName); /** * Returns the uppercase version of a string for generating and matching fields and methods. This is here in case * someone wants to override the behavior of the default locale because of localization issues around * capitalization. * * @param string * String to capitalize. * @param forceEnglish * Set to true to use the English locale otherwise false to use the default local one. */ public String upCaseString(String string, boolean forceEnglish); /** * Returns the lowercase version of a string for generating and fields and methods. This is here in case someone * wants to override the behavior of the default locale because of localization issues around capitalization. * * @param string * String to capitalize. * @param forceEnglish * Set to true to use the English locale otherwise false to use the default local one. */ public String downCaseString(String string, boolean forceEnglish); /** * Returns true if nested savePoints are supported, otherwise false. */ public boolean isNestedSavePointsSupported(); /** * Return an statement that doesn't do anything but which can be used to ping the database by sending it over a * database connection. */ public String getPingStatement(); /** * Returns true if batch operations should be done inside of a transaction. Default is false in which case * auto-commit disabling will be done. */ public boolean isBatchUseTransaction(); /** * Returns true if the table truncate operation is supported. */ public boolean isTruncateSupported(); /** * Returns true if the table creation IF NOT EXISTS syntax is supported. */ public boolean isCreateIfNotExistsSupported(); /** * Does the database support the "CREATE INDEX IF NOT EXISTS" SQL construct. By default this just calls * {@link #isCreateIfNotExistsSupported()}. */ public boolean isCreateIndexIfNotExistsSupported(); /** * Returns true if we have to select the value of the sequence before we insert a new data row. */ public boolean isSelectSequenceBeforeInsert(); /** * Does the database support the {@link DatabaseField#allowGeneratedIdInsert()} setting which allows people to * insert values into generated-id columns. */ public boolean isAllowGeneratedIdInsertSupported(); /** * Return the name of the database for logging purposes. */ public String getDatabaseName(); /** * Extract and return a custom database configuration for this class. * * @return null if no custom configuration extractor for this database type. */ public <T> DatabaseTableConfig<T> extractDatabaseTableConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException; /** * Append the SQL necessary to properly finish a "INSERT INTO xxx" line when there are no arguments. */ public void appendInsertNoColumns(StringBuilder sb); }
comments
src/main/java/com/j256/ormlite/db/DatabaseType.java
comments
<ide><path>rc/main/java/com/j256/ormlite/db/DatabaseType.java <ide> * capitalization. <ide> * <ide> * @param string <del> * String to capitalize. <add> * String to up case. <ide> * @param forceEnglish <ide> * Set to true to use the English locale otherwise false to use the default local one. <ide> */ <ide> * wants to override the behavior of the default locale because of localization issues around capitalization. <ide> * <ide> * @param string <del> * String to capitalize. <add> * String to down case. <ide> * @param forceEnglish <ide> * Set to true to use the English locale otherwise false to use the default local one. <ide> */
Java
mit
bbc950ede6f868dcf77718059d526b74afd09bde
0
andrewdavidmackenzie/viskell,wandernauta/viskell,viskell/viskell
package nl.utwente.group10.ui.components.anchors; import nl.utwente.group10.haskell.expr.Expr; import nl.utwente.group10.haskell.expr.Ident; import nl.utwente.group10.ui.components.blocks.Block; import nl.utwente.group10.ui.components.lines.Connection; import nl.utwente.group10.ui.handlers.AnchorHandler; /** * ConnectionAnchor that specifically functions as an input. */ public class InputAnchor extends ConnectionAnchor { /** The expression to return when there is no connection. */ private Expr connectionlessExpr; /** * @param block * The Block this anchor is connected to. */ public InputAnchor(Block block) { super(block); new AnchorHandler(super.getBlock().getPane().getConnectionCreationManager(), this); connectionlessExpr = new Ident("undefined"); } /** * @return The expression carried by the connection connected to this * anchor. */ @Override public final Expr getExpr() { if (isPrimaryConnected()) { return getPrimaryOppositeAnchor().get().getBlock().getExpr(); } else { return connectionlessExpr; } } @Override public void disconnectConnection(Connection connection) { connectionlessExpr = new Ident("undefined"); super.disconnectConnection(connection); } @Override public boolean canAddConnection() { // InputAnchors only support 1 connection; return !hasConnection(); } @Override public String toString() { return "InputAnchor for " + getBlock(); } }
Code/src/main/java/nl/utwente/group10/ui/components/anchors/InputAnchor.java
package nl.utwente.group10.ui.components.anchors; import nl.utwente.group10.haskell.expr.Expr; import nl.utwente.group10.haskell.expr.Ident; import nl.utwente.group10.ui.components.blocks.Block; import nl.utwente.group10.ui.handlers.AnchorHandler; /** * ConnectionAnchor that specifically functions as an input. */ public class InputAnchor extends ConnectionAnchor { /** The expression to return when there is no connection. */ private Expr connectionlessExpr; /** * @param block * The Block this anchor is connected to. */ public InputAnchor(Block block) { super(block); new AnchorHandler(super.getBlock().getPane().getConnectionCreationManager(), this); connectionlessExpr = new Ident("undefined"); } /** * @return The expression carried by the connection connected to this * anchor. */ @Override public final Expr getExpr() { if (isPrimaryConnected()) { return getPrimaryOppositeAnchor().get().getBlock().getExpr(); } else { return connectionlessExpr; } } @Override public boolean canAddConnection() { // InputAnchors only support 1 connection; return !hasConnection(); } @Override public String toString() { return "InputAnchor for " + getBlock(); } }
Fixed connectionlessExpr freshness
Code/src/main/java/nl/utwente/group10/ui/components/anchors/InputAnchor.java
Fixed connectionlessExpr freshness
<ide><path>ode/src/main/java/nl/utwente/group10/ui/components/anchors/InputAnchor.java <ide> import nl.utwente.group10.haskell.expr.Expr; <ide> import nl.utwente.group10.haskell.expr.Ident; <ide> import nl.utwente.group10.ui.components.blocks.Block; <add>import nl.utwente.group10.ui.components.lines.Connection; <ide> import nl.utwente.group10.ui.handlers.AnchorHandler; <ide> <ide> /** <ide> return connectionlessExpr; <ide> } <ide> } <add> <add> @Override <add> public void disconnectConnection(Connection connection) { <add> connectionlessExpr = new Ident("undefined"); <add> super.disconnectConnection(connection); <add> } <ide> <ide> @Override <ide> public boolean canAddConnection() {
Java
mit
3b3d3416057a7f7aeaa2fbd1f8c9068afcec026d
0
gurkenlabs/litiengine,gurkenlabs/litiengine
package de.gurkenlabs.litiengine.graphics; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.environment.IEnvironment; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.util.ImageProcessing; import de.gurkenlabs.litiengine.util.MathUtilities; import de.gurkenlabs.litiengine.util.geom.GeometricUtilities; public abstract class ColorLayer implements IRenderable { private final IEnvironment environment; private final Image[][] tiles; private int alpha; private Color color; protected ColorLayer(IEnvironment env, final Color color, final int alpha) { this.environment = env; this.color = color; this.alpha = alpha; this.tiles = new Image[env.getMap().getWidth()][env.getMap().getHeight()]; this.updateSection(this.environment.getMap().getBounds()); } @Override public void render(Graphics2D g) { final Rectangle2D viewport = Game.getCamera().getViewPort(); final IMap map = this.getEnvironment().getMap(); // draw the tile on the layer image for (int x = 0; x < map.getWidth(); x++) { for (int y = 0; y < map.getHeight(); y++) { Rectangle2D tileBounds = map.getTileShape(x, y).getBounds2D(); if (!viewport.intersects(tileBounds)) { continue; } final double offsetX = -(viewport.getX()); final double offsetY = -(viewport.getY()); ImageRenderer.render(g, tiles[x][y], offsetX + tileBounds.getX(), offsetY + tileBounds.getY()); } } } public int getAlpha() { return this.alpha; } public Color getColor() { return this.color; } public Color getColorWithAlpha() { return new Color(this.getColor().getRed(), this.getColor().getGreen(), this.getColor().getBlue(), this.getAlpha()); } public void setAlpha(int ambientAlpha) { this.alpha = MathUtilities.clamp(ambientAlpha, 0, 255); this.updateSection(this.environment.getMap().getBounds()); } public void setColor(final Color color) { this.color = color; this.updateSection(this.environment.getMap().getBounds()); } public void updateSection(Rectangle2D section) { if (this.getColor() == null) { return; } final IMap map = this.getEnvironment().getMap(); final Rectangle2D tileSection = MapUtilities.getTileBoundingBox(map, section); if (tileSection == null) { return; } final BufferedImage img = ImageProcessing.getCompatibleImage((int) tileSection.getWidth(), (int) tileSection.getHeight()); final Graphics2D g = img.createGraphics(); this.renderSection(g, tileSection); g.dispose(); this.setTiles(img, tileSection); } private void setTiles(BufferedImage img, Rectangle2D section) { final IMap map = this.getEnvironment().getMap(); final Point startTile = MapUtilities.getTile(map, new Point2D.Double(section.getX(), section.getY())); final Point endTile = MapUtilities.getTile(map, new Point2D.Double(section.getMaxX(), section.getMaxY())); final int startX = MathUtilities.clamp(startTile.x, 0, Math.min(startTile.x + (endTile.x - startTile.x), tiles.length) - 1); final int startY = MathUtilities.clamp(startTile.y, 0, Math.min(startTile.y + (endTile.y - startTile.y), tiles[0].length) - 1); final int endX = MathUtilities.clamp(endTile.x, 0, Math.min(startTile.x + (endTile.x - startTile.x), tiles.length) - 1); final int endY = MathUtilities.clamp(endTile.y, 0, Math.min(startTile.y + (endTile.y - startTile.y), tiles[0].length) - 1); final Shape startTileShape = map.getTileShape(startX, startY); for (int x = startX; x <= endX; x++) { for (int y = startY; y <= endY; y++) { Shape tile = map.getTileShape(x, y); Shape translatedTile = GeometricUtilities.translateShape(tile, new Point2D.Double(0, 0)); int subX = MathUtilities.clamp((int) (tile.getBounds().getX() - startTileShape.getBounds().getX()), 0, img.getWidth() - map.getTileWidth()); int subY = MathUtilities.clamp((int) (tile.getBounds().getY() - startTileShape.getBounds().getY()), 0, img.getHeight() - map.getTileHeight()); final BufferedImage smallImage = img.getSubimage(subX, subY, map.getTileWidth(), map.getTileHeight()); final BufferedImage clippedImage = ImageProcessing.getCompatibleImage(smallImage.getWidth(), smallImage.getHeight()); Graphics2D g = clippedImage.createGraphics(); g.clip(translatedTile); g.drawImage(smallImage, 0, 0, null); g.dispose(); this.tiles[x][y] = clippedImage; } } } protected abstract void renderSection(Graphics2D g, Rectangle2D section); protected IEnvironment getEnvironment() { return this.environment; } }
src/de/gurkenlabs/litiengine/graphics/ColorLayer.java
package de.gurkenlabs.litiengine.graphics; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.environment.IEnvironment; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.util.ImageProcessing; import de.gurkenlabs.litiengine.util.MathUtilities; import de.gurkenlabs.litiengine.util.geom.GeometricUtilities; public abstract class ColorLayer implements IRenderable { private final IEnvironment environment; private final Image[][] tiles; private int alpha; private Color color; protected ColorLayer(IEnvironment env, final Color color, final int alpha) { this.environment = env; this.color = color; this.alpha = alpha; this.tiles = new Image[env.getMap().getWidth()][env.getMap().getHeight()]; this.updateSection(this.environment.getMap().getBounds()); } @Override public void render(Graphics2D g) { final Rectangle2D viewport = Game.getCamera().getViewPort(); final IMap map = this.getEnvironment().getMap(); // draw the tile on the layer image for (int x = 0; x < map.getWidth(); x++) { for (int y = 0; y < map.getHeight(); y++) { Rectangle2D tileBounds = map.getTileShape(x, y).getBounds2D(); if (!viewport.intersects(tileBounds)) { continue; } final double offsetX = -(viewport.getX()); final double offsetY = -(viewport.getY()); ImageRenderer.render(g, tiles[x][y], offsetX + tileBounds.getX(), offsetY + tileBounds.getY()); } } } public int getAlpha() { return this.alpha; } public Color getColor() { return this.color; } public Color getColorWithAlpha() { return new Color(this.getColor().getRed(), this.getColor().getGreen(), this.getColor().getBlue(), this.getAlpha()); } public void setAlpha(int ambientAlpha) { this.alpha = MathUtilities.clamp(ambientAlpha, 0, 255); this.updateSection(this.environment.getMap().getBounds()); } public void setColor(final Color color) { this.color = color; this.updateSection(this.environment.getMap().getBounds()); } public void updateSection(Rectangle2D section) { if (this.getColor() == null) { return; } final IMap map = this.getEnvironment().getMap(); final Rectangle2D tileSection = MapUtilities.getTileBoundingBox(map, section); if (tileSection == null) { return; } final BufferedImage img = ImageProcessing.getCompatibleImage((int) tileSection.getWidth(), (int) tileSection.getHeight()); final Graphics2D g = img.createGraphics(); this.renderSection(g, tileSection); g.dispose(); this.setTiles(img, tileSection); } private void setTiles(BufferedImage img, Rectangle2D section) { final IMap map = this.getEnvironment().getMap(); final Point startTile = MapUtilities.getTile(map, new Point2D.Double(section.getX(), section.getY())); final Point endTile = MapUtilities.getTile(map, new Point2D.Double(section.getMaxX(), section.getMaxY())); final int startX = MathUtilities.clamp(startTile.x, 0, Math.min(startTile.x + (endTile.x - startTile.x), tiles.length) - 1); final int startY = MathUtilities.clamp(startTile.y, 0, Math.min(startTile.y + (endTile.y - startTile.y), tiles[0].length) - 1); final int endX = MathUtilities.clamp(endTile.x, 0, Math.min(startTile.x + (endTile.x - startTile.x), tiles.length) - 1); final int endY = MathUtilities.clamp(endTile.y, 0, Math.min(startTile.y + (endTile.y - startTile.y), tiles[0].length) - 1); final Shape startTileShape = map.getTileShape(startX, startY); for (int x = startX; x <= endX; x++) { for (int y = startY; y <= endY; y++) { Shape tile = map.getTileShape(x, y); Shape translatedTile = GeometricUtilities.translateShape(tile, new Point2D.Double(0, 0)); int subX = MathUtilities.clamp((int) (tile.getBounds().getX() - startTileShape.getBounds().getX()), 0, img.getWidth() - map.getTileWidth()); int subY = MathUtilities.clamp((int) (tile.getBounds().getY() - startTileShape.getBounds().getY()), 0, img.getHeight() - map.getTileHeight()); final BufferedImage smallImage = img.getSubimage(subX, subY, map.getTileWidth(), map.getTileHeight()); final BufferedImage clippedImage = ImageProcessing.getCompatibleImage(smallImage.getWidth(), smallImage.getHeight()); Graphics2D g = clippedImage.createGraphics(); g.clip(translatedTile); g.drawImage(smallImage, 0, 0, null); g.clip(translatedTile); g.dispose(); this.tiles[x][y] = clippedImage; } } } protected abstract void renderSection(Graphics2D g, Rectangle2D section); protected IEnvironment getEnvironment() { return this.environment; } }
Remove redundant line of code.
src/de/gurkenlabs/litiengine/graphics/ColorLayer.java
Remove redundant line of code.
<ide><path>rc/de/gurkenlabs/litiengine/graphics/ColorLayer.java <ide> Graphics2D g = clippedImage.createGraphics(); <ide> g.clip(translatedTile); <ide> g.drawImage(smallImage, 0, 0, null); <del> g.clip(translatedTile); <ide> g.dispose(); <ide> this.tiles[x][y] = clippedImage; <ide> }
Java
apache-2.0
537adb0f822a15ba598fcd303f09b3fd30dcccca
0
HubSpot/Blazar,HubSpot/Blazar,HubSpot/Blazar,HubSpot/Blazar
package com.hubspot.blazar.data.dao; import com.hubspot.blazar.base.GitInfo; import com.hubspot.blazar.base.ModuleDependency; import com.hubspot.blazar.base.graph.Edge; import com.hubspot.rosetta.jdbi.BindWithRosetta; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlBatch; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.unstable.BindIn; import java.util.Set; @UseStringTemplate3StatementLocator public interface DependenciesDao { @SqlQuery("SELECT module_provides.moduleId AS source, module_depends.moduleId AS target " + "FROM module_provides " + "INNER JOIN module_depends ON (module_provides.name = module_depends.name) " + "INNER JOIN modules provides ON (module_provides.moduleId = provides.id) " + "INNER JOIN modules depends ON (module_depends.moduleId = depends.id) " + "WHERE provides.branchId = :id AND depends.branchId = :id") Set<Edge> getEdges(@BindWithRosetta GitInfo gitInfo); @SqlQuery("SELECT module_provides.moduleId AS source, module_depends.moduleId AS target " + "FROM module_provides " + "INNER JOIN module_depends ON (module_provides.name = module_depends.name) " + "INNER JOIN modules ON (module_depends.moduleId = modules.id) " + "INNER JOIN branches ON (modules.branchId = branches.id) " + "WHERE module_provides.moduleId IN (<moduleIds>) " + "AND modules.active = 1 " + "AND branches.active = 1") Set<Edge> getEdges(@BindIn("moduleIds") Set<Integer> moduleIds); @SqlBatch("INSERT INTO module_provides (moduleId, name) VALUES (:moduleId, :name)") void insertProvides(@BindWithRosetta Set<ModuleDependency> dependencies); @SqlBatch("INSERT INTO module_depends (moduleId, name) VALUES (:moduleId, :name)") void insertDepends(@BindWithRosetta Set<ModuleDependency> dependencies); @SqlUpdate("DELETE FROM module_provides WHERE moduleId = :moduleId") void deleteProvides(@Bind("moduleId") int moduleId); @SqlUpdate("DELETE FROM module_depends WHERE moduleId = :moduleId") void deleteDepends(@Bind("moduleId") int moduleId); }
BlazarData/src/main/java/com/hubspot/blazar/data/dao/DependenciesDao.java
package com.hubspot.blazar.data.dao; import com.hubspot.blazar.base.GitInfo; import com.hubspot.blazar.base.ModuleDependency; import com.hubspot.blazar.base.graph.Edge; import com.hubspot.rosetta.jdbi.BindWithRosetta; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlBatch; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.unstable.BindIn; import java.util.Set; @UseStringTemplate3StatementLocator public interface DependenciesDao { @SqlQuery("SELECT module_provides.moduleId AS source, module_depends.moduleId AS target " + "FROM module_provides " + "INNER JOIN module_depends ON (module_provides.name = module_depends.name) " + "INNER JOIN modules provides ON (module_provides.moduleId = provides.id) " + "INNER JOIN modules depends ON (module_provides.moduleId = depends.id) " + "WHERE provides.branchId = :id AND depends.branchId = :id") Set<Edge> getEdges(@BindWithRosetta GitInfo gitInfo); @SqlQuery("SELECT module_provides.moduleId AS source, module_depends.moduleId AS target " + "FROM module_provides " + "INNER JOIN module_depends ON (module_provides.name = module_depends.name) " + "INNER JOIN modules ON (module_depends.moduleId = modules.id) " + "INNER JOIN branches ON (modules.branchId = branches.id) " + "WHERE module_provides.moduleId IN (<moduleIds>) " + "AND modules.active = 1 " + "AND branches.active = 1") Set<Edge> getEdges(@BindIn("moduleIds") Set<Integer> moduleIds); @SqlBatch("INSERT INTO module_provides (moduleId, name) VALUES (:moduleId, :name)") void insertProvides(@BindWithRosetta Set<ModuleDependency> dependencies); @SqlBatch("INSERT INTO module_depends (moduleId, name) VALUES (:moduleId, :name)") void insertDepends(@BindWithRosetta Set<ModuleDependency> dependencies); @SqlUpdate("DELETE FROM module_provides WHERE moduleId = :moduleId") void deleteProvides(@Bind("moduleId") int moduleId); @SqlUpdate("DELETE FROM module_depends WHERE moduleId = :moduleId") void deleteDepends(@Bind("moduleId") int moduleId); }
Fix test
BlazarData/src/main/java/com/hubspot/blazar/data/dao/DependenciesDao.java
Fix test
<ide><path>lazarData/src/main/java/com/hubspot/blazar/data/dao/DependenciesDao.java <ide> "FROM module_provides " + <ide> "INNER JOIN module_depends ON (module_provides.name = module_depends.name) " + <ide> "INNER JOIN modules provides ON (module_provides.moduleId = provides.id) " + <del> "INNER JOIN modules depends ON (module_provides.moduleId = depends.id) " + <add> "INNER JOIN modules depends ON (module_depends.moduleId = depends.id) " + <ide> "WHERE provides.branchId = :id AND depends.branchId = :id") <ide> Set<Edge> getEdges(@BindWithRosetta GitInfo gitInfo); <ide>
Java
bsd-3-clause
e74715a31c36903c5d0deca22d8c277f013a6b89
0
edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon
/* * $Id: LockssDocumentBuilderFactoryImpl.java,v 1.5 2008-02-15 09:16:44 tlipkis Exp $ */ /* Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.util; import java.util.*; import java.lang.reflect.*; import javax.xml.parsers.*; import org.xml.sax.*; import org.lockss.util.*; /** Wrapper for an existing DocumentBuilderFactory, delegates all calls to * it except that the ErrorHandler of created DocumentBuilders is set to * one that logs to the LOCKSS logger. XXX Java version-dependent: if the * DocumentBuilderFactory API changes, this must be updated to forward all * methods. Needs to know what underlying factory to use, which makes it * also dependent on xercesImpl - XXX Xerces */ public class LockssDocumentBuilderFactoryImpl extends DocumentBuilderFactory { static Logger log = Logger.getLogger("DocumentBuilderFactory"); public static String ERROR_LOGGER_NAME = "SAX"; DocumentBuilderFactory fact; public LockssDocumentBuilderFactoryImpl() { // fact = new org.apache.crimson.jaxp.DocumentBuilderFactoryImpl(); fact = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl(); log.debug3("Created fact: " + fact); } /** Forward to real factory, set error handler */ public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { DocumentBuilder db = fact.newDocumentBuilder(); log.debug3("Created builder: " + db); db.setErrorHandler(new MyErrorHandler()); return db; } public void setAttribute(String name, Object value) { fact.setAttribute(name, value); } public Object getAttribute(String name) { return fact.getAttribute(name); } public void setNamespaceAware(boolean awareness) { fact.setNamespaceAware(awareness); } public void setValidating(boolean validating) { fact.setValidating(validating); } public void setIgnoringElementContentWhitespace(boolean whitespace) { fact.setIgnoringElementContentWhitespace(whitespace); } public void setExpandEntityReferences(boolean expandEntityRef) { fact.setExpandEntityReferences(expandEntityRef); } public void setIgnoringComments(boolean ignoreComments) { fact.setIgnoringComments(ignoreComments); } public void setCoalescing(boolean coalescing) { fact.setCoalescing(coalescing); } public boolean isNamespaceAware() { return fact.isNamespaceAware(); } public boolean isValidating() { return fact.isValidating(); } public boolean isIgnoringElementContentWhitespace() { return fact.isIgnoringElementContentWhitespace(); } public boolean isExpandEntityReferences() { return fact.isExpandEntityReferences(); } public boolean isIgnoringComments() { return fact.isIgnoringComments(); } public boolean isCoalescing() { return fact.isCoalescing(); } // Abstract methods added to DocumentBuilderFactory interface in 1.5. // They must be implemented and proxied, but direct calls won't compile // in 1.4, so invoke them using reflection. Java 1.5 remove this? static Class[] argsGetFeature = {String.class}; public boolean getFeature(String name) throws ParserConfigurationException { // return fact.getFeature(name); try { Object res = invoke("getFeatureccc", argsGetFeature, new Object[] {name}); return ((Boolean)res).booleanValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof ParserConfigurationException) { throw (ParserConfigurationException)e.getCause(); } if (e.getCause() instanceof RuntimeException) { throw (RuntimeException)e.getCause(); } throw new RuntimeException(e); } } static Class[] argsSetFeature = {String.class, Boolean.TYPE}; public void setFeature(String name, boolean value) throws ParserConfigurationException { // fact.setFeature(name, value); try { invoke("setFeature", argsSetFeature, new Object[] {name, Boolean.valueOf(value)}); } catch (InvocationTargetException e) { if (e.getCause() instanceof ParserConfigurationException) { throw (ParserConfigurationException)e.getCause(); } if (e.getCause() instanceof RuntimeException) { throw (RuntimeException)e.getCause(); } throw new RuntimeException(e); } } Object invoke(String method, Class[] argtypes, Object[] args) throws InvocationTargetException { try { Method m = fact.getClass().getMethod(method, argtypes); return m.invoke(fact, args); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } // This error handler uses a Logger to log error messages static class MyErrorHandler implements ErrorHandler { private Logger log = Logger.getLogger(ERROR_LOGGER_NAME); // This method is called in the event of a recoverable error public void error(SAXParseException e) { log(Logger.LEVEL_WARNING, e); } // This method is called in the event of a non-recoverable error public void fatalError(SAXParseException e) { log(Logger.LEVEL_ERROR, e); } // This method is called in the event of a warning public void warning(SAXParseException e) { log(Logger.LEVEL_WARNING, e); } // Log the error private void log(int level, SAXParseException e) { int line = e.getLineNumber(); int col = e.getColumnNumber(); String publicId = e.getPublicId(); String systemId = e.getSystemId(); StringBuffer sb = new StringBuffer(); sb.append(e.getMessage()); if (line > 0 || col > 0) { sb.append(": line="); sb.append(line); sb.append(", col="); sb.append(col); } if (publicId != null || systemId != null) { sb.append(": publicId="); sb.append(publicId); sb.append(", systemId="); sb.append(systemId); } // Log the message log.log(level, sb.toString()); } } }
src/org/lockss/util/LockssDocumentBuilderFactoryImpl.java
/* * $Id: LockssDocumentBuilderFactoryImpl.java,v 1.4 2005-10-11 05:48:30 tlipkis Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.util; import java.util.*; import java.lang.reflect.*; import javax.xml.parsers.*; import org.xml.sax.*; import org.lockss.util.*; /** Wrapper for an existing DocumentBuilderFactory, delegates all calls to * it except that the ErrorHandler of created DocumentBuilders is set to * one that logs to the LOCKSS logger. XXX Java version-dependent: if the * DocumentBuilderFactory API changes, this must be updated to forward all * methods. Needs to know what underlying factory to use, which makes it * also dependent on xercesImpl - XXX Xerces */ public class LockssDocumentBuilderFactoryImpl extends DocumentBuilderFactory { static Logger log = Logger.getLogger("DocumentBuilderFactory"); public static String ERROR_LOGGER_NAME = "SAX"; DocumentBuilderFactory fact; public LockssDocumentBuilderFactoryImpl() { // fact = new org.apache.crimson.jaxp.DocumentBuilderFactoryImpl(); fact = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl(); log.debug2("Created fact: " + fact); } /** Forward to real factory, set error handler */ public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { DocumentBuilder db = fact.newDocumentBuilder(); log.debug2("Created builder: " + db); db.setErrorHandler(new MyErrorHandler()); return db; } public void setAttribute(String name, Object value) { fact.setAttribute(name, value); } public Object getAttribute(String name) { return fact.getAttribute(name); } public void setNamespaceAware(boolean awareness) { fact.setNamespaceAware(awareness); } public void setValidating(boolean validating) { fact.setValidating(validating); } public void setIgnoringElementContentWhitespace(boolean whitespace) { fact.setIgnoringElementContentWhitespace(whitespace); } public void setExpandEntityReferences(boolean expandEntityRef) { fact.setExpandEntityReferences(expandEntityRef); } public void setIgnoringComments(boolean ignoreComments) { fact.setIgnoringComments(ignoreComments); } public void setCoalescing(boolean coalescing) { fact.setCoalescing(coalescing); } public boolean isNamespaceAware() { return fact.isNamespaceAware(); } public boolean isValidating() { return fact.isValidating(); } public boolean isIgnoringElementContentWhitespace() { return fact.isIgnoringElementContentWhitespace(); } public boolean isExpandEntityReferences() { return fact.isExpandEntityReferences(); } public boolean isIgnoringComments() { return fact.isIgnoringComments(); } public boolean isCoalescing() { return fact.isCoalescing(); } // Abstract methods added to DocumentBuilderFactory interface in 1.5. // They must be implemented and proxied, but direct calls won't compile // in 1.4, so invoke them using reflection. Java 1.5 remove this? static Class[] argsGetFeature = {String.class}; public boolean getFeature(String name) throws ParserConfigurationException { // return fact.getFeature(name); try { Object res = invoke("getFeatureccc", argsGetFeature, new Object[] {name}); return ((Boolean)res).booleanValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof ParserConfigurationException) { throw (ParserConfigurationException)e.getCause(); } if (e.getCause() instanceof RuntimeException) { throw (RuntimeException)e.getCause(); } throw new RuntimeException(e); } } static Class[] argsSetFeature = {String.class, Boolean.TYPE}; public void setFeature(String name, boolean value) throws ParserConfigurationException { // fact.setFeature(name, value); try { invoke("setFeature", argsSetFeature, new Object[] {name, Boolean.valueOf(value)}); } catch (InvocationTargetException e) { if (e.getCause() instanceof ParserConfigurationException) { throw (ParserConfigurationException)e.getCause(); } if (e.getCause() instanceof RuntimeException) { throw (RuntimeException)e.getCause(); } throw new RuntimeException(e); } } Object invoke(String method, Class[] argtypes, Object[] args) throws InvocationTargetException { try { Method m = fact.getClass().getMethod(method, argtypes); return m.invoke(fact, args); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } // This error handler uses a Logger to log error messages static class MyErrorHandler implements ErrorHandler { private Logger log = Logger.getLogger(ERROR_LOGGER_NAME); // This method is called in the event of a recoverable error public void error(SAXParseException e) { log(Logger.LEVEL_WARNING, e); } // This method is called in the event of a non-recoverable error public void fatalError(SAXParseException e) { log(Logger.LEVEL_ERROR, e); } // This method is called in the event of a warning public void warning(SAXParseException e) { log(Logger.LEVEL_WARNING, e); } // Log the error private void log(int level, SAXParseException e) { int line = e.getLineNumber(); int col = e.getColumnNumber(); String publicId = e.getPublicId(); String systemId = e.getSystemId(); StringBuffer sb = new StringBuffer(); sb.append(e.getMessage()); if (line > 0 || col > 0) { sb.append(": line="); sb.append(line); sb.append(", col="); sb.append(col); } if (publicId != null || systemId != null) { sb.append(": publicId="); sb.append(publicId); sb.append(", systemId="); sb.append(systemId); } // Log the message log.log(level, sb.toString()); } } }
Log level. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@6942 4f837ed2-42f5-46e7-a7a5-fa17313484d4
src/org/lockss/util/LockssDocumentBuilderFactoryImpl.java
Log level.
<ide><path>rc/org/lockss/util/LockssDocumentBuilderFactoryImpl.java <ide> /* <del> * $Id: LockssDocumentBuilderFactoryImpl.java,v 1.4 2005-10-11 05:48:30 tlipkis Exp $ <add> * $Id: LockssDocumentBuilderFactoryImpl.java,v 1.5 2008-02-15 09:16:44 tlipkis Exp $ <ide> */ <ide> <ide> /* <ide> <del>Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, <add>Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University, <ide> all rights reserved. <ide> <ide> Permission is hereby granted, free of charge, to any person obtaining a copy <ide> public LockssDocumentBuilderFactoryImpl() { <ide> // fact = new org.apache.crimson.jaxp.DocumentBuilderFactoryImpl(); <ide> fact = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl(); <del> log.debug2("Created fact: " + fact); <add> log.debug3("Created fact: " + fact); <ide> } <ide> <ide> /** Forward to real factory, set error handler */ <ide> public DocumentBuilder newDocumentBuilder() <ide> throws ParserConfigurationException { <ide> DocumentBuilder db = fact.newDocumentBuilder(); <del> log.debug2("Created builder: " + db); <add> log.debug3("Created builder: " + db); <ide> db.setErrorHandler(new MyErrorHandler()); <ide> return db; <ide> }
Java
apache-2.0
afa7b6e7c36e6ebc92c2fa277dd54c52ba77145a
0
apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis
/* * 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.isis.viewer.wicket.viewer.integration; import java.lang.reflect.Constructor; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.apache.wicket.Application; import org.apache.wicket.IPageFactory; import org.apache.wicket.MetaDataKey; import org.apache.wicket.Page; import org.apache.wicket.RestartResponseException; import org.apache.wicket.Session; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.core.request.handler.ListenerInvocationNotAllowedException; import org.apache.wicket.core.request.handler.PageProvider; import org.apache.wicket.core.request.handler.RenderPageRequestHandler; import org.apache.wicket.core.request.handler.RenderPageRequestHandler.RedirectPolicy; import org.apache.wicket.protocol.http.PageExpiredException; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.component.IRequestablePage; import org.apache.wicket.request.cycle.IRequestCycleListener; import org.apache.wicket.request.cycle.PageRequestHandlerTracker; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.isis.applib.services.exceprecog.ExceptionRecognizer; import org.apache.isis.applib.services.exceprecog.ExceptionRecognizerForType; import org.apache.isis.applib.services.exceprecog.ExceptionRecognizerService; import org.apache.isis.applib.services.exceprecog.Recognition; import org.apache.isis.commons.collections.Can; import org.apache.isis.commons.internal.base._Strings; import org.apache.isis.commons.internal.exceptions._Exceptions; import org.apache.isis.core.interaction.integration.IsisRequestCycle; import org.apache.isis.core.interaction.session.InteractionFactory; import org.apache.isis.core.interaction.session.InteractionSession; import org.apache.isis.core.interaction.session.MessageBroker; import org.apache.isis.core.metamodel.spec.feature.ObjectMember; import org.apache.isis.core.metamodel.specloader.validator.MetaModelInvalidException; import org.apache.isis.core.runtime.context.IsisAppCommonContext; import org.apache.isis.viewer.wicket.model.common.CommonContextUtils; import org.apache.isis.viewer.wicket.model.models.PageType; import org.apache.isis.viewer.wicket.ui.errors.ExceptionModel; import org.apache.isis.viewer.wicket.ui.pages.PageClassRegistry; import org.apache.isis.viewer.wicket.ui.pages.error.ErrorPage; import org.apache.isis.viewer.wicket.ui.pages.login.WicketSignInPage; import org.apache.isis.viewer.wicket.ui.pages.mmverror.MmvErrorPage; import org.apache.isis.viewer.wicket.ui.panels.PromptFormAbstract; import lombok.val; import lombok.extern.log4j.Log4j2; /** * Isis-specific implementation of the Wicket's {@link RequestCycle}, * automatically opening a {@link InteractionSession} at the beginning of the request * and committing the transaction and closing the session at the end. * * @since 2.0 */ @Log4j2 public class WebRequestCycleForIsis implements IRequestCycleListener { // introduced (ISIS-1922) to handle render 'session refreshed' messages after session was expired private static enum SessionLifecyclePhase { DONT_CARE, EXPIRED, ACTIVE_AFTER_EXPIRED; static boolean isExpired(final RequestCycle requestCycle) { return Session.exists() && SessionLifecyclePhase.EXPIRED == requestCycle.getMetaData(SESSION_LIFECYCLE_PHASE_KEY); } static boolean isActiveAfterExpired() { return Session.exists() && SessionLifecyclePhase.ACTIVE_AFTER_EXPIRED == Session.get().getMetaData(SESSION_LIFECYCLE_PHASE_KEY); } static void transferExpiredFlagToSession() { Session.get().setMetaData(SESSION_LIFECYCLE_PHASE_KEY, SessionLifecyclePhase.ACTIVE_AFTER_EXPIRED); Session.get().setAttribute("session-expiry-message-timeframe", LocalDateTime.now().plusNanos(1000_000_000L)); } static void clearExpiredFlag() { Session.get().setMetaData(SESSION_LIFECYCLE_PHASE_KEY, SessionLifecyclePhase.DONT_CARE); } static boolean isExpiryMessageTimeframeExpired() { val sessionExpiryMessageTimeframe = (LocalDateTime) Session.get().getAttribute("session-expiry-message-timeframe"); return sessionExpiryMessageTimeframe==null || LocalDateTime.now().isAfter(sessionExpiryMessageTimeframe); } } public static final MetaDataKey<IsisRequestCycle> REQ_CYCLE_HANDLE_KEY = new MetaDataKey<IsisRequestCycle>() {private static final long serialVersionUID = 1L; }; private static final MetaDataKey<SessionLifecyclePhase> SESSION_LIFECYCLE_PHASE_KEY = new MetaDataKey<SessionLifecyclePhase>() { private static final long serialVersionUID = 1L; }; private PageClassRegistry pageClassRegistry; private IsisAppCommonContext commonContext; @Override public synchronized void onBeginRequest(RequestCycle requestCycle) { log.debug("onBeginRequest in"); if (!Session.exists()) { // Track if session was created from an expired one to notify user of the refresh. // If there is no remember me cookie, user will be redirected to sign in and no need to notify. if (userHasSessionWithRememberMe(requestCycle)) { requestCycle.setMetaData(SESSION_LIFECYCLE_PHASE_KEY, SessionLifecyclePhase.EXPIRED); log.debug("flagging the RequestCycle as expired (rememberMe feature is active for the current user)"); } log.debug("onBeginRequest out - session was not opened (because no Session)"); return; } val commonContext = getCommonContext(); val authentication = AuthenticatedWebSessionForIsis.get().getAuthentication(); if (authentication == null) { log.debug("onBeginRequest out - session was not opened (because no authentication)"); return; } val isisRequestCycle = IsisRequestCycle.next( commonContext.lookupServiceElseFail(InteractionFactory.class)); requestCycle.setMetaData(REQ_CYCLE_HANDLE_KEY, isisRequestCycle); isisRequestCycle.onBeginRequest(authentication); log.debug("onBeginRequest out - session was opened"); } @Override public void onRequestHandlerResolved(final RequestCycle requestCycle, final IRequestHandler handler) { log.debug("onRequestHandlerResolved in (handler: {}, hasSession: {})", ()->handler.getClass().getName(), ()->Session.exists() ? Session.get().hashCode() : "false"); // this nested class is hidden; it seems it is always used to create a new session after one has expired if("org.apache.wicket.request.flow.ResetResponseException$ResponseResettingDecorator" .equals(handler.getClass().getName()) && SessionLifecyclePhase.isExpired(requestCycle)) { log.debug("Transferring the 'expired' flag into the current session."); SessionLifecyclePhase.transferExpiredFlagToSession(); } else if(handler instanceof RenderPageRequestHandler) { val validationResult = getCommonContext().getSpecificationLoader().getValidationResult(); if(validationResult.hasFailures()) { RenderPageRequestHandler requestHandler = (RenderPageRequestHandler) handler; final IRequestablePage nextPage = requestHandler.getPage(); if(nextPage instanceof ErrorPage || nextPage instanceof MmvErrorPage) { // do nothing return; } throw new MetaModelInvalidException(validationResult.getAsLineNumberedString()); } if(SessionLifecyclePhase.isActiveAfterExpired()) { // we receive multiple requests after a session had expired and was reactivated; // impossible to tell which one is the last that should then render the message; // so we just render them on all requests, until the 1 second time frame since session creation // has gone by, could result in the message displayed too often, // but thats better than no message displayed at all if(SessionLifecyclePhase.isExpiryMessageTimeframeExpired()) { log.debug("clear the session's active-after-expired flag (expiry-message timeframe has expired"); SessionLifecyclePhase.clearExpiredFlag(); } else { getMessageBroker().ifPresent(broker -> { log.debug("render 'expired' message"); broker.addMessage(translate("You have been redirected to the home page " + "as your session expired (no recent activity).")); }); } } } log.debug("onRequestHandlerResolved out"); } /** * Is called prior to {@link #onEndRequest(RequestCycle)}, and offers the opportunity to * throw an exception. */ @Override public void onRequestHandlerExecuted(RequestCycle requestCycle, IRequestHandler handler) { log.debug("onRequestHandlerExecuted: handler: {}", handler.getClass().getName()); try { val isisRequestCycle = requestCycle.getMetaData(REQ_CYCLE_HANDLE_KEY); if(isisRequestCycle!=null) { isisRequestCycle.onRequestHandlerExecuted(); } } catch(Exception ex) { if(handler instanceof RenderPageRequestHandler) { RenderPageRequestHandler requestHandler = (RenderPageRequestHandler) handler; if(requestHandler.getPage() instanceof ErrorPage) { // do nothing return; } } log.debug("onRequestHandlerExecuted: isisRequestCycle.onRequestHandlerExecuted threw {}", ex.getClass().getName()); // shouldn't return null given that we're in a session ... throw new RestartResponseException(errorPageProviderFor(ex), RedirectPolicy.ALWAYS_REDIRECT); } } /** * It is not possible to throw exceptions here, hence use of {@link #onRequestHandlerExecuted(RequestCycle, IRequestHandler)}. */ @Override public synchronized void onEndRequest(RequestCycle requestCycle) { log.debug("onEndRequest"); val isisRequestCycle = requestCycle.getMetaData(REQ_CYCLE_HANDLE_KEY); requestCycle.setMetaData(REQ_CYCLE_HANDLE_KEY, null); if(isisRequestCycle!=null) { isisRequestCycle.onEndRequest(); } } @Override public void onDetach(RequestCycle requestCycle) { // detach the current @RequestScope, if any IRequestCycleListener.super.onDetach(requestCycle); } @Override public IRequestHandler onException(RequestCycle cycle, Exception ex) { log.debug("onException {}", ex.getClass().getSimpleName()); val validationResult = getCommonContext().getSpecificationLoader().getValidationResult(); if(validationResult.hasFailures()) { val mmvErrorPage = new MmvErrorPage(validationResult.getMessages("[%d] %s")); return new RenderPageRequestHandler(new PageProvider(mmvErrorPage), RedirectPolicy.ALWAYS_REDIRECT); } try { // adapted from http://markmail.org/message/un7phzjbtmrrperc if(ex instanceof ListenerInvocationNotAllowedException) { final ListenerInvocationNotAllowedException linaex = (ListenerInvocationNotAllowedException) ex; if(linaex.getComponent() != null && PromptFormAbstract.ID_CANCEL_BUTTON.equals(linaex.getComponent().getId())) { // no message. // this seems to occur when press ESC twice in rapid succession on a modal dialog. } else { addMessage(null); } return respondGracefully(cycle); } // handle recognized exceptions gracefully also val exceptionRecognizerService = getExceptionRecognizerService(); val recognizedIfAny = exceptionRecognizerService.recognize(ex); if(recognizedIfAny.isPresent()) { return respondGracefully(cycle); } final List<Throwable> causalChain = _Exceptions.getCausalChain(ex); final Optional<Throwable> hiddenIfAny = causalChain.stream() .filter(ObjectMember.HiddenException::isInstanceOf).findFirst(); if(hiddenIfAny.isPresent()) { addMessage("hidden"); return respondGracefully(cycle); } final Optional<Throwable> disabledIfAny = causalChain.stream() .filter(ObjectMember.DisabledException::isInstanceOf).findFirst(); if(disabledIfAny.isPresent()) { addTranslatedMessage(disabledIfAny.get().getMessage()); return respondGracefully(cycle); } } catch(Exception ignoreFailedAttemptToGracefullyHandle) { // if any of this graceful responding fails, then fall back to original handling } PageProvider errorPageProvider = errorPageProviderFor(ex); // avoid infinite redirect loops RedirectPolicy redirectPolicy = ex instanceof PageExpiredException ? RedirectPolicy.NEVER_REDIRECT : RedirectPolicy.ALWAYS_REDIRECT; return errorPageProvider != null ? new RenderPageRequestHandler(errorPageProvider, redirectPolicy) : null; } private IRequestHandler respondGracefully(final RequestCycle cycle) { final IRequestablePage page = PageRequestHandlerTracker.getFirstHandler(cycle).getPage(); final PageProvider pageProvider = new PageProvider(page); return new RenderPageRequestHandler(pageProvider); } private void addMessage(final String message) { final String translatedMessage = translate(message); addTranslatedMessage(translatedMessage); } private void addTranslatedMessage(final String translatedSuffixIfAny) { getMessageBroker().ifPresent(broker->{ final String translatedPrefix = translate("Action no longer available"); final String message = translatedSuffixIfAny != null ? String.format("%s (%s)", translatedPrefix, translatedSuffixIfAny) : translatedPrefix; broker.addMessage(message); }); } private String translate(final String text) { if(text == null) { return null; } return getCommonContext().getTranslationService() .translate(WebRequestCycleForIsis.class.getName(), text); } protected PageProvider errorPageProviderFor(Exception ex) { IRequestablePage errorPage = errorPageFor(ex); return errorPage != null ? new PageProvider(errorPage) : null; } // special case handling for PageExpiredException, otherwise infinite loop private static final ExceptionRecognizerForType pageExpiredExceptionRecognizer = new ExceptionRecognizerForType( PageExpiredException.class, __->"Requested page is no longer available."); protected IRequestablePage errorPageFor(Exception ex) { val commmonContext = getCommonContext(); if(commmonContext==null) { log.warn("Unable to obtain the IsisAppCommonContext (no session?)"); return null; } val validationResult = commmonContext.getSpecificationLoader().getValidationResult(); if(validationResult.hasFailures()) { return new MmvErrorPage(validationResult.getMessages("[%d] %s")); } val exceptionRecognizerService = getCommonContext().getServiceRegistry() .lookupServiceElseFail(ExceptionRecognizerService.class); final Optional<Recognition> recognition = exceptionRecognizerService .recognizeFromSelected( Can.<ExceptionRecognizer>ofSingleton(pageExpiredExceptionRecognizer) .addAll(exceptionRecognizerService.getExceptionRecognizers()), ex); val exceptionModel = ExceptionModel.create(commmonContext, recognition, ex); return isSignedIn() ? new ErrorPage(exceptionModel) : newSignInPage(exceptionModel); } /** * Tries to instantiate the configured {@link PageType#SIGN_IN signin page} with the given exception model * * @param exceptionModel A model bringing the information about the occurred problem * @return An instance of the configured signin page */ private IRequestablePage newSignInPage(final ExceptionModel exceptionModel) { Class<? extends Page> signInPageClass = null; if (pageClassRegistry != null) { signInPageClass = pageClassRegistry.getPageClass(PageType.SIGN_IN); } if (signInPageClass == null) { signInPageClass = WicketSignInPage.class; } final PageParameters parameters = new PageParameters(); Page signInPage; try { Constructor<? extends Page> constructor = signInPageClass.getConstructor(PageParameters.class, ExceptionModel.class); signInPage = constructor.newInstance(parameters, exceptionModel); } catch (Exception ex) { try { IPageFactory pageFactory = Application.get().getPageFactory(); signInPage = pageFactory.newPage(signInPageClass, parameters); } catch (Exception x) { throw new WicketRuntimeException("Cannot instantiate the configured sign in page", x); } } return signInPage; } /** * TODO: this is very hacky... * * <p> * Matters should improve once ISIS-299 gets implemented... */ protected boolean isSignedIn() { if(!isInInteraction()) { return false; } return getWicketAuthenticatedWebSession().isSignedIn(); } private boolean userHasSessionWithRememberMe(RequestCycle requestCycle) { val containerRequest = requestCycle.getRequest().getContainerRequest(); if (containerRequest instanceof HttpServletRequest) { val cookies = Can.ofArray(((HttpServletRequest) containerRequest).getCookies()); val cookieKey = _Strings.nullToEmpty( getCommonContext().getConfiguration().getViewer().getWicket().getRememberMe().getCookieKey()); for (val cookie : cookies) { if (cookieKey.equals(cookie.getName())) { return true; } } } return false; } public void setPageClassRegistry(PageClassRegistry pageClassRegistry) { this.pageClassRegistry = pageClassRegistry; } // -- DEPENDENCIES public IsisAppCommonContext getCommonContext() { return commonContext = CommonContextUtils.computeIfAbsent(commonContext); } private ExceptionRecognizerService getExceptionRecognizerService() { return getCommonContext().getServiceRegistry().lookupServiceElseFail(ExceptionRecognizerService.class); } private boolean isInInteraction() { return commonContext.getInteractionTracker().isInInteractionSession(); } private Optional<MessageBroker> getMessageBroker() { return commonContext.getInteractionTracker().currentMessageBroker(); } private AuthenticatedWebSession getWicketAuthenticatedWebSession() { return AuthenticatedWebSession.get(); } }
viewers/wicket/viewer/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/WebRequestCycleForIsis.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.isis.viewer.wicket.viewer.integration; import java.lang.reflect.Constructor; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.apache.wicket.Application; import org.apache.wicket.IPageFactory; import org.apache.wicket.MetaDataKey; import org.apache.wicket.Page; import org.apache.wicket.RestartResponseException; import org.apache.wicket.Session; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.authroles.authentication.AuthenticatedWebSession; import org.apache.wicket.core.request.handler.ListenerInvocationNotAllowedException; import org.apache.wicket.core.request.handler.PageProvider; import org.apache.wicket.core.request.handler.RenderPageRequestHandler; import org.apache.wicket.core.request.handler.RenderPageRequestHandler.RedirectPolicy; import org.apache.wicket.protocol.http.PageExpiredException; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.component.IRequestablePage; import org.apache.wicket.request.cycle.IRequestCycleListener; import org.apache.wicket.request.cycle.PageRequestHandlerTracker; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.isis.applib.services.exceprecog.ExceptionRecognizer; import org.apache.isis.applib.services.exceprecog.ExceptionRecognizerForType; import org.apache.isis.applib.services.exceprecog.ExceptionRecognizerService; import org.apache.isis.applib.services.exceprecog.Recognition; import org.apache.isis.commons.collections.Can; import org.apache.isis.commons.internal.base._Strings; import org.apache.isis.commons.internal.exceptions._Exceptions; import org.apache.isis.core.interaction.integration.IsisRequestCycle; import org.apache.isis.core.interaction.session.InteractionFactory; import org.apache.isis.core.interaction.session.InteractionSession; import org.apache.isis.core.interaction.session.MessageBroker; import org.apache.isis.core.metamodel.spec.feature.ObjectMember; import org.apache.isis.core.metamodel.specloader.validator.MetaModelInvalidException; import org.apache.isis.core.runtime.context.IsisAppCommonContext; import org.apache.isis.viewer.wicket.model.common.CommonContextUtils; import org.apache.isis.viewer.wicket.model.models.PageType; import org.apache.isis.viewer.wicket.ui.errors.ExceptionModel; import org.apache.isis.viewer.wicket.ui.pages.PageClassRegistry; import org.apache.isis.viewer.wicket.ui.pages.error.ErrorPage; import org.apache.isis.viewer.wicket.ui.pages.login.WicketSignInPage; import org.apache.isis.viewer.wicket.ui.pages.mmverror.MmvErrorPage; import org.apache.isis.viewer.wicket.ui.panels.PromptFormAbstract; import lombok.val; import lombok.extern.log4j.Log4j2; /** * Isis-specific implementation of the Wicket's {@link RequestCycle}, * automatically opening a {@link InteractionSession} at the beginning of the request * and committing the transaction and closing the session at the end. * * @since 2.0 */ @Log4j2 public class WebRequestCycleForIsis implements IRequestCycleListener { // introduced (ISIS-1922) to handle render 'session refreshed' messages after session was expired private static enum SessionLifecyclePhase { DONT_CARE, EXPIRED, ACTIVE_AFTER_EXPIRED; static boolean isExpired(final RequestCycle requestCycle) { return Session.exists() && SessionLifecyclePhase.EXPIRED == requestCycle.getMetaData(SESSION_LIFECYCLE_PHASE_KEY); } static boolean isActiveAfterExpired() { return Session.exists() && SessionLifecyclePhase.ACTIVE_AFTER_EXPIRED == Session.get().getMetaData(SESSION_LIFECYCLE_PHASE_KEY); } static void transferExpiredFlagToSession() { Session.get().setMetaData(SESSION_LIFECYCLE_PHASE_KEY, SessionLifecyclePhase.ACTIVE_AFTER_EXPIRED); Session.get().setAttribute("session-expiry-message-timeframe", LocalDateTime.now().plusNanos(1000_000_000L)); } static void clearExpiredFlag() { Session.get().setMetaData(SESSION_LIFECYCLE_PHASE_KEY, SessionLifecyclePhase.DONT_CARE); } static boolean isExpiryMessageTimeframeExpired() { val sessionExpiryMessageTimeframe = (LocalDateTime) Session.get().getAttribute("session-expiry-message-timeframe"); return sessionExpiryMessageTimeframe==null || LocalDateTime.now().isAfter(sessionExpiryMessageTimeframe); } } public static final MetaDataKey<IsisRequestCycle> REQ_CYCLE_HANDLE_KEY = new MetaDataKey<IsisRequestCycle>() {private static final long serialVersionUID = 1L; }; private static final MetaDataKey<SessionLifecyclePhase> SESSION_LIFECYCLE_PHASE_KEY = new MetaDataKey<SessionLifecyclePhase>() { private static final long serialVersionUID = 1L; }; private PageClassRegistry pageClassRegistry; private IsisAppCommonContext commonContext; @Override public synchronized void onBeginRequest(RequestCycle requestCycle) { log.debug("onBeginRequest in"); if (!Session.exists()) { // Track if session was created from an expired one to notify user of the refresh. // If there is no remember me cookie, user will be redirected to sign in and no need to notify. if (userHasSessionWithRememberMe(requestCycle)) { requestCycle.setMetaData(SESSION_LIFECYCLE_PHASE_KEY, SessionLifecyclePhase.EXPIRED); log.debug("flagging the RequestCycle as expired (rememberMe feature is active for the current user)"); } log.debug("onBeginRequest out - session was not opened (because no Session)"); return; } val commonContext = getCommonContext(); val authentication = AuthenticatedWebSessionForIsis.get().getAuthentication(); if (authentication == null) { log.debug("onBeginRequest out - session was not opened (because no authentication)"); return; } val isisRequestCycle = IsisRequestCycle.next( commonContext.lookupServiceElseFail(InteractionFactory.class)); requestCycle.setMetaData(REQ_CYCLE_HANDLE_KEY, isisRequestCycle); isisRequestCycle.onBeginRequest(authentication); log.debug("onBeginRequest out - session was opened"); } @Override public void onRequestHandlerResolved(final RequestCycle requestCycle, final IRequestHandler handler) { log.debug("onRequestHandlerResolved in (handler: {}, hasSession: {})", ()->handler.getClass().getName(), ()->Session.exists() ? Session.get().hashCode() : "false"); // this nested class is hidden; it seems it is always used to create a new session after one has expired if("org.apache.wicket.request.flow.ResetResponseException$ResponseResettingDecorator" .equals(handler.getClass().getName()) && SessionLifecyclePhase.isExpired(requestCycle)) { log.debug("Transferring the 'expired' flag into the current session."); SessionLifecyclePhase.transferExpiredFlagToSession(); } else if(handler instanceof RenderPageRequestHandler) { val validationResult = getCommonContext().getSpecificationLoader().getValidationResult(); if(validationResult.hasFailures()) { RenderPageRequestHandler requestHandler = (RenderPageRequestHandler) handler; final IRequestablePage nextPage = requestHandler.getPage(); if(nextPage instanceof ErrorPage || nextPage instanceof MmvErrorPage) { // do nothing return; } throw new MetaModelInvalidException(validationResult.getAsLineNumberedString()); } if(SessionLifecyclePhase.isActiveAfterExpired()) { // we receive multiple requests after a session had expired and was reactivated; // impossible to tell which one is the last that should then render the message; // so we just render them on all requests, until the 1 second time frame since session creation // has gone by, could result in the message displayed too often, // but thats better than no message displayed at all if(SessionLifecyclePhase.isExpiryMessageTimeframeExpired()) { log.debug("clear the session's active-after-expired flag (expiry-message timeframe has expired"); SessionLifecyclePhase.clearExpiredFlag(); } else { getMessageBroker().ifPresent(broker -> { log.debug("render 'expired' message"); broker.addMessage(translate("Expired session was refreshed.")); }); } } } log.debug("onRequestHandlerResolved out"); } /** * Is called prior to {@link #onEndRequest(RequestCycle)}, and offers the opportunity to * throw an exception. */ @Override public void onRequestHandlerExecuted(RequestCycle requestCycle, IRequestHandler handler) { log.debug("onRequestHandlerExecuted: handler: {}", handler.getClass().getName()); try { val isisRequestCycle = requestCycle.getMetaData(REQ_CYCLE_HANDLE_KEY); if(isisRequestCycle!=null) { isisRequestCycle.onRequestHandlerExecuted(); } } catch(Exception ex) { if(handler instanceof RenderPageRequestHandler) { RenderPageRequestHandler requestHandler = (RenderPageRequestHandler) handler; if(requestHandler.getPage() instanceof ErrorPage) { // do nothing return; } } log.debug("onRequestHandlerExecuted: isisRequestCycle.onRequestHandlerExecuted threw {}", ex.getClass().getName()); // shouldn't return null given that we're in a session ... throw new RestartResponseException(errorPageProviderFor(ex), RedirectPolicy.ALWAYS_REDIRECT); } } /** * It is not possible to throw exceptions here, hence use of {@link #onRequestHandlerExecuted(RequestCycle, IRequestHandler)}. */ @Override public synchronized void onEndRequest(RequestCycle requestCycle) { log.debug("onEndRequest"); val isisRequestCycle = requestCycle.getMetaData(REQ_CYCLE_HANDLE_KEY); requestCycle.setMetaData(REQ_CYCLE_HANDLE_KEY, null); if(isisRequestCycle!=null) { isisRequestCycle.onEndRequest(); } } @Override public void onDetach(RequestCycle requestCycle) { // detach the current @RequestScope, if any IRequestCycleListener.super.onDetach(requestCycle); } @Override public IRequestHandler onException(RequestCycle cycle, Exception ex) { log.debug("onException {}", ex.getClass().getSimpleName()); val validationResult = getCommonContext().getSpecificationLoader().getValidationResult(); if(validationResult.hasFailures()) { val mmvErrorPage = new MmvErrorPage(validationResult.getMessages("[%d] %s")); return new RenderPageRequestHandler(new PageProvider(mmvErrorPage), RedirectPolicy.ALWAYS_REDIRECT); } try { // adapted from http://markmail.org/message/un7phzjbtmrrperc if(ex instanceof ListenerInvocationNotAllowedException) { final ListenerInvocationNotAllowedException linaex = (ListenerInvocationNotAllowedException) ex; if(linaex.getComponent() != null && PromptFormAbstract.ID_CANCEL_BUTTON.equals(linaex.getComponent().getId())) { // no message. // this seems to occur when press ESC twice in rapid succession on a modal dialog. } else { addMessage(null); } return respondGracefully(cycle); } // handle recognized exceptions gracefully also val exceptionRecognizerService = getExceptionRecognizerService(); val recognizedIfAny = exceptionRecognizerService.recognize(ex); if(recognizedIfAny.isPresent()) { return respondGracefully(cycle); } final List<Throwable> causalChain = _Exceptions.getCausalChain(ex); final Optional<Throwable> hiddenIfAny = causalChain.stream() .filter(ObjectMember.HiddenException::isInstanceOf).findFirst(); if(hiddenIfAny.isPresent()) { addMessage("hidden"); return respondGracefully(cycle); } final Optional<Throwable> disabledIfAny = causalChain.stream() .filter(ObjectMember.DisabledException::isInstanceOf).findFirst(); if(disabledIfAny.isPresent()) { addTranslatedMessage(disabledIfAny.get().getMessage()); return respondGracefully(cycle); } } catch(Exception ignoreFailedAttemptToGracefullyHandle) { // if any of this graceful responding fails, then fall back to original handling } PageProvider errorPageProvider = errorPageProviderFor(ex); // avoid infinite redirect loops RedirectPolicy redirectPolicy = ex instanceof PageExpiredException ? RedirectPolicy.NEVER_REDIRECT : RedirectPolicy.ALWAYS_REDIRECT; return errorPageProvider != null ? new RenderPageRequestHandler(errorPageProvider, redirectPolicy) : null; } private IRequestHandler respondGracefully(final RequestCycle cycle) { final IRequestablePage page = PageRequestHandlerTracker.getFirstHandler(cycle).getPage(); final PageProvider pageProvider = new PageProvider(page); return new RenderPageRequestHandler(pageProvider); } private void addMessage(final String message) { final String translatedMessage = translate(message); addTranslatedMessage(translatedMessage); } private void addTranslatedMessage(final String translatedSuffixIfAny) { getMessageBroker().ifPresent(broker->{ final String translatedPrefix = translate("Action no longer available"); final String message = translatedSuffixIfAny != null ? String.format("%s (%s)", translatedPrefix, translatedSuffixIfAny) : translatedPrefix; broker.addMessage(message); }); } private String translate(final String text) { if(text == null) { return null; } return getCommonContext().getTranslationService() .translate(WebRequestCycleForIsis.class.getName(), text); } protected PageProvider errorPageProviderFor(Exception ex) { IRequestablePage errorPage = errorPageFor(ex); return errorPage != null ? new PageProvider(errorPage) : null; } // special case handling for PageExpiredException, otherwise infinite loop private static final ExceptionRecognizerForType pageExpiredExceptionRecognizer = new ExceptionRecognizerForType( PageExpiredException.class, __->"Requested page is no longer available."); protected IRequestablePage errorPageFor(Exception ex) { val commmonContext = getCommonContext(); if(commmonContext==null) { log.warn("Unable to obtain the IsisAppCommonContext (no session?)"); return null; } val validationResult = commmonContext.getSpecificationLoader().getValidationResult(); if(validationResult.hasFailures()) { return new MmvErrorPage(validationResult.getMessages("[%d] %s")); } val exceptionRecognizerService = getCommonContext().getServiceRegistry() .lookupServiceElseFail(ExceptionRecognizerService.class); final Optional<Recognition> recognition = exceptionRecognizerService .recognizeFromSelected( Can.<ExceptionRecognizer>ofSingleton(pageExpiredExceptionRecognizer) .addAll(exceptionRecognizerService.getExceptionRecognizers()), ex); val exceptionModel = ExceptionModel.create(commmonContext, recognition, ex); return isSignedIn() ? new ErrorPage(exceptionModel) : newSignInPage(exceptionModel); } /** * Tries to instantiate the configured {@link PageType#SIGN_IN signin page} with the given exception model * * @param exceptionModel A model bringing the information about the occurred problem * @return An instance of the configured signin page */ private IRequestablePage newSignInPage(final ExceptionModel exceptionModel) { Class<? extends Page> signInPageClass = null; if (pageClassRegistry != null) { signInPageClass = pageClassRegistry.getPageClass(PageType.SIGN_IN); } if (signInPageClass == null) { signInPageClass = WicketSignInPage.class; } final PageParameters parameters = new PageParameters(); Page signInPage; try { Constructor<? extends Page> constructor = signInPageClass.getConstructor(PageParameters.class, ExceptionModel.class); signInPage = constructor.newInstance(parameters, exceptionModel); } catch (Exception ex) { try { IPageFactory pageFactory = Application.get().getPageFactory(); signInPage = pageFactory.newPage(signInPageClass, parameters); } catch (Exception x) { throw new WicketRuntimeException("Cannot instantiate the configured sign in page", x); } } return signInPage; } /** * TODO: this is very hacky... * * <p> * Matters should improve once ISIS-299 gets implemented... */ protected boolean isSignedIn() { if(!isInInteraction()) { return false; } return getWicketAuthenticatedWebSession().isSignedIn(); } private boolean userHasSessionWithRememberMe(RequestCycle requestCycle) { val containerRequest = requestCycle.getRequest().getContainerRequest(); if (containerRequest instanceof HttpServletRequest) { val cookies = Can.ofArray(((HttpServletRequest) containerRequest).getCookies()); val cookieKey = _Strings.nullToEmpty( getCommonContext().getConfiguration().getViewer().getWicket().getRememberMe().getCookieKey()); for (val cookie : cookies) { if (cookieKey.equals(cookie.getName())) { return true; } } } return false; } public void setPageClassRegistry(PageClassRegistry pageClassRegistry) { this.pageClassRegistry = pageClassRegistry; } // -- DEPENDENCIES public IsisAppCommonContext getCommonContext() { return commonContext = CommonContextUtils.computeIfAbsent(commonContext); } private ExceptionRecognizerService getExceptionRecognizerService() { return getCommonContext().getServiceRegistry().lookupServiceElseFail(ExceptionRecognizerService.class); } private boolean isInInteraction() { return commonContext.getInteractionTracker().isInInteractionSession(); } private Optional<MessageBroker> getMessageBroker() { return commonContext.getInteractionTracker().currentMessageBroker(); } private AuthenticatedWebSession getWicketAuthenticatedWebSession() { return AuthenticatedWebSession.get(); } }
ISIS-1922: polish the expiry message
viewers/wicket/viewer/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/WebRequestCycleForIsis.java
ISIS-1922: polish the expiry message
<ide><path>iewers/wicket/viewer/src/main/java/org/apache/isis/viewer/wicket/viewer/integration/WebRequestCycleForIsis.java <ide> } else { <ide> getMessageBroker().ifPresent(broker -> { <ide> log.debug("render 'expired' message"); <del> broker.addMessage(translate("Expired session was refreshed.")); <add> broker.addMessage(translate("You have been redirected to the home page " <add> + "as your session expired (no recent activity).")); <ide> }); <ide> } <ide> }
Java
apache-2.0
294ee810093872eba4dcda3cdb2862bb2e2ab290
0
SEARCH-NCJIS/nibrs,SEARCH-NCJIS/nibrs,SEARCH-NCJIS/nibrs,SEARCH-NCJIS/nibrs,SEARCH-NCJIS/nibrs
/******************************************************************************* * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics * * 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.search.nibrs.model.codes; public enum NIBRSErrorCode { _015("015","Structure Check","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Zero-Reporting Segment (Level 0). Although Data Element 2 (Incident Number) should be entered with 12 zeros, a pre-edit found embedded blanks between the first and last significant characters."), _016("016","Structure Check","MUST BE LEFT-JUSTIFIED— BLANK DETECTED IN FIRST POSITION","Zero-Reporting Segment (Level 0). Although Data Element 2 (Incident Number) should be entered with 12 zeros, a pre-edit found a blank in the first position. It must begin in position 1 and must also contain 12 zeros."), _017("017","Structure Check","CANNOT HAVE CHARACTERS OTHER THAN A-Z, 0-9, HYPHENS, AND/OR BLANKS","Zero-Reporting Segment (Level 0). Although Data Element 2 (Incident Number) should be entered with 12 zeros, a pre-edit discovered characters other than A through Z, 0 through 9, hyphens, and/or blanks had been entered."), _050("050","Structure Check","SEGMENT LEVELS ARE OUT OF NUMERICAL ORDER FOR THIS INCIDENT","Segment Levels in a Group A Incident Report must be organized in numerical order. For example, an incident having segments 1, 2, 2, 3, 4, 4, 4, 5 must be written in that order, not as 1, 2, 2, 5, 3, 4, 4, 4."), _051("051","Structure Check","INVALID RECORD LEVEL ON SUBMISSION","Segment Level must contain data values 0–7."), _052("052","Structure Check","NOT A VALID ORI–NOT IN UCR ORI FILE","Data Element 1 (ORI) and Data Element 25C (Officer–ORI Other Jurisdiction) must be a valid nine-character NCIC ORI."), _055("055","Structure Check","CANNOT HAVE A GROUP A INCIDENT REPORT WITHOUT LEVEL 1 SEGMENT","Segment Level 1 (Administrative Segment) with Segment Action Type I=Incident Report must be the first segment submitted for each Group A Incident Report."), _056("056","Structure Check","DUPLICATE INCIDENT– PREVIOUSLY ADDED","Data Element 2 (Incident Number) must be a unique number for each incident submitted. No two incidents can have the same incident number."), _058("058","Structure Check","ALL SEGMENTS IN A SUBMISSION MUST HAVE SAME MONTH AND YEAR OF SUBMISSION","Month of Submission and Year of Submission must contain the same data values for each segment in a NIBRS submission. The first segment processed will be compared with all other segments to check for this condition."), _059("059","Structure Check","ALL SEGMENTS IN SUBMISSION MUST BE FROM SAME STATE","Data Element 1 (ORI) must contain the same state abbreviation code (e.g., SC, MD, etc.) in the first two positions (record positions 17 & 18). For nonfederal LEAs, every segment in a submission must have the same state code in the first two positions of the ORI."), _060("060","Structure Check","PROCESSING DATE PRECEDES MONTH AND YEAR OF SUBMISSION","Month of Submission and Year of Submission must precede the date the FBI receives and processes a NIBRS submission. This edit checks for data submitted for a future month/year."), _065("065","Structure Check","EACH LEVEL 2 OFFENSE MUST HAVE AT LEAST ONE VICTIM","Segment Level 2 (Offense Segment) must have at least one Segment Level 4 (Victim Segment) connected to it by entering the offense code identified in Data Element 6 (UCR Offense Code) in Data Element 24 (Victim Connected to UCR Offense Code)."), _070("070","Structure Check","THE CORRESPONDING OFFENDER RECORD MUST BE PRESENT","Data Element 34 (Offender Numbers To Be Related) has a value that does not have a corresponding Offender Segment. For example, if the field value shown in Data Element 34 is 15, an Offender Segment does not exist with a value of 15 in Data Element 36 (Offender Sequence Number)."), _071("071","Structure Check","CANNOT HAVE ARRESTS WHEN CLEARED EXCEPTIONALLY","Segment Level 6 (Arrestee Segment) with Segment Action Type I=Incident Report cannot be submitted with Data Element 42 (Arrest Date) containing an arrest date on or earlier than the date entered in Data Element 5 (Exceptional Clearance Date) when Data Element 4 (Cleared Exceptionally) contains a data value other than N=Not Applicable (indicating the incident is cleared exceptionally)."), _072("072","Structure Check","RECOVERED PROPERTY MUST FIRST BE REPORTED AS STOLEN","Segment Level 3 (Property Segment) must first be submitted with Data Element 14 (Type Property Loss/Etc.) as 7=Stolen/Etc. before it can be submitted as 5=Recovered for the same property in Data Element 15 (Property Description). Any property being reported as recovered must first be reported as stolen. There are three exceptions to this rule: 1) When recovered property information is submitted as Segment Action Type A=Add and Data Element 2 (Incident Number) is not on file in the national UCR database. This condition may indicate recovered property is being reported for a pre-NIBRS incident; therefore, the stolen property information will not be on file in the national database. 2) When Data Element 6 (UCR Offense Code) contains an offense that allows property to be recovered without first being stolen in that same incident (i.e., 250=Counterfeiting/Forgery and 280=Stolen Property Offenses) 3) When a vehicle was stolen and the recovered property in Data Element 15 (Property Description) is 38=Vehicle Parts/Accessories"), _073("073","Structure Check","NUMBER OF RECOVERED VEHICLES CANNOT BE GREATER THAN THE NUMBER STOLEN","Segment Level 3 (Property Segment) with Segment Action Type I=Incident Report must contain a data value in Data Element 18 (Number of Stolen Motor Vehicles) greater than or equal to the data value entered in Data Element 19 (Number of Recovered Motor Vehicles) within the same incident."), _074("074","Structure Check","PROPERTY SEGMENT MUST EXIST WITH THIS OFFENSE","Segment Level 3 (Property Segment) with Segment Action Type I=Incident Report must be submitted when Data Element 6 (UCR Offense Code) contains an offense of Kidnapping/Abduction , Crimes Against Property, Drug/Narcotic Offenses, or Gambling Offenses."), _075("075","Structure Check","MISSING A MANDATORY SEGMENT LEVEL FOR A COMPLETE INCIDENT","Segment Levels 1, 2, 4, and 5 (Administrative Segment, Offense Segment, Victim Segment, and Offender Segment) with Segment Action Type I=Incident Report must be submitted for each Group A Incident Report; they are mandatory."), _076("076","Structure Check","PROPERTY RECORD (LEVEL 3) CAN NOT EXIST WITH OFFENSES SUBMITTED","Segment Level 3 (Property Segment) with Segment Action Type I=Incident Report cannot be submitted unless Data Element 6 (UCR Offense Code) contains an offense of Kidnapping/Abduction, Crimes Against Property, Drug/Narcotic Offenses, or Gambling Offenses."), _077("077","Structure Check","NEED A PROPERTY LOSS CODE OF 1 OR 8 WHEN THIS OFFENSE IS ATTEMPTED","Data Element 7 (Offense Attempted/Completed) is A=Attempted and Data Element 6 (UCR Offense Code) is a Crime Against Property, Gambling, Kidnapping, or Drug/Narcotic Offense. However, there is no Data Element 14 (Type Property Loss/Etc.) of 1=None or 8=Unknown."), _078("078","Structure Check","A VALID PROPERTY LOSS CODE DOES NOT EXIST FOR THIS COMPLETED OFFENSE","If Data Element 6 (UCR Offense Code) is a Crime Against Property, Kidnaping, Gambling, or Drug/Narcotic Offense, and Data Element 7 (Offense Attempted/Completed) is C=Completed, a Property Segment (Level 3) must be sent with a valid code in Data Element 14 (Type Property Loss/Etc.)."), _080("080","Structure Check","CRIMES AGAINST SOCIETY CAN HAVE ONLY ONE SOCIETY/PUBLIC VICTIM","Segment Level 4 (Victim Segment) can be submitted only once and Data Element 25 (Type of Victim) must be S=Society/Public when Data Element 6 (UCR Offense Code) contains only a Crime Against Society."), _081("081","Structure Check","TYPE PROPERTY LOSS CODE IS NOT VALID WITH THE OFFENSES SUBMITTED","Data Element 14 (Type Property Loss/Etc.) must be 1=None or 8=Unknown when Data Element 6 (UCR Offense Code) contains an offense of Kidnapping/Abduction, Crimes against Property, Drug/Narcotic Offenses, or Gambling Offenses and Data Element 7 (Offense Attempted/Completed) is A=Attempted. Data Element 14 (Type Property Loss/Etc.) must be 1=None or 5=Recovered when Data Element 6 (UCR Offense Code) is 280=Stolen Property Offenses and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 1=None, 5=Recovered, 7=Stolen/Etc., or 8=Unknown when Data Element 6 (UCR Offense Code) is 100=Kidnapping/Abduction, 220=Burglary/ Breaking & Entering, or 510=Bribery and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 1=None or 6=Seized when Data Element 6 (UCR Offense Code) is 35A=Drug/ Narcotic Violations or 35B=Drug Equipment Violations and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 2=Burned when Data Element 6 (UCR Offense Code) is 200=Arson and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 3=Counterfeited/Forged, 5=Recovered, or 6=Seized when Data Element 6 (UCR Offense Code) is 250=Counterfeiting/Forgery and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 4=Destroyed/Damaged/Vandalized when Data Element 6 (UCR Offense Code) is 290=Destruction/Damage/Vandalism of Property and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 5=Recovered or 7=Stolen/Etc. when Data Element 6 (UCR Offense Code) is any of the following and Data Element 7 (Offense Attempted/Completed) is C=Completed: 120=Robbery 210=Extortion/Blackmail 23A=Pocket-picking 23B=Purse Snatching 23C=Shoplifting 23D=Theft from Building 23E=Theft from Coin-Operated Machine or Device 23F=Theft from Motor Vehicle 23G=Theft of Motor Vehicle Parts or Accessories 23H=All other Larceny 240=Motor Vehicle Theft 26A=False Pretenses/Swindle/Confidence Game 26B=Credit Card/Automated Teller Machine Fraud 26C=Impersonation 26D=Welfare Fraud 26E=Wire Fraud270=Embezzlement Data Element 14 (Type Property Loss/Etc.) must be 6=Seized when Data Element 6 (UCR Offense Code) is any of the following and Data Element 7 (Offense Attempted/Completed) is C=Completed: 39A=Betting/W agering 39B=Operating/Promoting/Assisting Gambling 39C=Gambling Equipment Violation 39D=Sports Tampering"), _084("084","Structure Check","RECOVERED PROPERTY VALUE CANNOT BE GREATER THAN THE VALUE WHEN STOLEN","Data Element 16 (Value of Property) for property classified as 7=Stolen/Etc. in Data Element 14 (Type Property Loss/Etc.) must be greater than or equal to the value entered in Data Element 16 (Value of Property) for property classified as 5=Recovered for the same property specified in Data Element 15 (Property Description) in an incident. Note: This edit also applies when a vehicle was stolen and the recovered property in Data Element 15 (Property Description) is 38=Vehicle Parts/Accessories. The value of recovered parts cannot exceed the value of stolen vehicles."), _085("085","Structure Check","EACH VICTIM MUST BE CONNECTED TO AT LEAST TWO OFFENDERS","Segment Level 4 (Victim Segment) with a data value in Data Element 24 (Victim Connected to UCR Offense Code) of a Crime Against Person or Robbery must contain at least two offender sequence numbers in Data Element 34 (Offender Number to be Related) when there are three or more Segment Level 5 (Offender Segment) records submitted for the incident."), _088("088","Structure Check","GROUP A AND GROUP B ARREST REPORTS CANNOT HAVE SAME IDENTIFIER","Segment Level 6 (Arrestee Segment) and Segment Level 7 (Group B Arrest Report Segment) cannot have the same data values entered in Data Element 2 (Incident Number) and Data Element 41 (Arrest Transaction Number), respectively, for the same ORI."), _091("091","Structure Check","ZERO-REPORTING YEAR IS INVALID","A Segment Level 0 was submitted that did not have four numeric digits in positions 40 through 43."), _101("101","Admin Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _104("104","Admin Segment","INVALID DATA VALUE—NOT ON FBI VALIDATION TABLE","The referenced data element must contain a valid data value when it is entered."), _105("105","Admin Segment","INVALID DATA VALUE FOR DATE","The data element in error contains a date that is not entered correctly. Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31days). Also, the date cannot exceed the current date."), _115("115","Admin Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","(Incident Number) Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _116("116","Admin Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","(Incident Number) must be left-justified with blank right-fill. Since the number is less than 12 characters, it must begin in position 1"), _117("117","Admin Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","(Incident Number) can only have character combinations of A through Z, 0 through 9, hyphens, and/or blanks. For example, 89-123-SC is valid, but 89+123*SC is invalid."), _118("118","Admin Segment","DATE CANNOT BE ON OR AFTER THE INACTIVE DATE [yyyymmdd] OF THE ORI","The UCR Program has determined that an ORI will no longer be submitting data to the FBI as of an inactive date. No data from this ORI will be accepted after this date."), _119("119","Admin Segment","CARGO THEFT DATA CAN ONLY BE SUBMITTED FOR SPECIFIC OFFENSES","Data Element 2A (Cargo Theft) must be populated with a valid data value when Data Element 6 (UCR Offense Code) contains a Cargo Theft- related offense."), _122("122","Admin Segment","INCIDENT MUST INCLUDE AT LEAST ONE CARGO THEFT OFFENSE","Data Element 2A (Cargo Theft) can be Y=Yes only when Data Element 6 (UCR Offense Code) includes at least one of the following: 120=Robbery 210=Extortion/Blackmail 220=Burglary/Breaking & Entering 23D=Theft From Building 23F=Theft From Motor Vehicle 24H=All Other Larceny 240=Motor Vehicle Theft 26A=False Pretenses/Swindle/Confidence Game 26B=Credit Card/Automated Teller Machine Fraud 26C=Impersonation 26E=Wire Fraud 270=Embezzlement 510=Bribery"), _151("151","Admin Segment","REPORT INDICATOR MUST BE BLANK OR “R”","This field must be blank if the incident date is known. If the incident date is unknown, then the report date would be entered instead and must be indicated with an “R” in the Report Indicator field within the Administrative Segment."), _152("152","Admin Segment","INVALID HOUR ENTRY","If Hour is entered within Data Element 3 (Incident Date/Hour), it must be 00 through 23. If 00=Midnight is entered, be careful that the Incident Date is entered as if the time was 1 minute past midnight. Note: When an incident occurs exactly at midnight, Data Element 3 (Incident Date) would be entered as if the time is 1 minute past midnight. For example, when a crime occurred exactly at midnight on Thursday, Friday’s date would be entered."), _153("153","Admin Segment","VALUE ENTERED CONFLICTS WITH PRESENCE OF AN ENTRY IN EXCEPTIONAL CLEARANCE DATE","Data Element 4 (Cleared Exceptionally) cannot be N=Not Applicable if Data Element 5 (Exceptional Clearance Date) is entered."), _155("155","Admin Segment","CLEARANCE DATE [yyyymmdd] PREDATES INCIDENT DATE [yyyymmdd]","Data Element 5 (Exceptional Clearance Date) is earlier than Data Element 3 (Incident Date/Hour)."), _156("156","Admin Segment","AN ENTRY MUST BE MADE WHEN CLEARED EXCEPTIONALLY HAS ENTRIES OF A-E","Data Element 5 (Exceptional Clearance Date) must be present if the case was cleared exceptionally. Data Element 4 (Cleared Exceptionally) has an entry of A through E; therefore, the date must also be entered."), _170("170","Admin Segment","INCIDENT DATE CANNOT BE AFTER YEAR [yyyy] AND MONTH [mm] OF ELECTRONIC SUBMISSION","Data Element 3 The date cannot be later than the year and month the electronic submission represents. For example, the May 1999 electronic submission cannot contain incidents happening after this date."), _171("171","Admin Segment","INCIDENT DATE IS OUTSIDE THE BASE DATE CALCULATION","A Group “A” Incident Report was submitted with a date entered into Data Element 3 (Incident Date/Hour) that is earlier than January 1 of the previous year, using the Month of Tape and Year of Tape as a reference point. For example, if the Month of Tape and Year of Tape contain a value of 01/1999, but the incident date is 12/25/1997, the incident will be rejected. Volume 2, section I, provides specifications concerning the FBI’s 2- year database. Note: The exception is when an exceptional clearance is being submitted with a Segment Action Type of W=Time-Window Submission. The incident date may be any past date, but cannot be any earlier than January 1, 1950."), _172("172","Admin Segment","INCIDENT DATE/HOUR FOR “I” RECORDS CANNOT PREDATE 01/01/1991","Data Element 3 (Incident Date) cannot be earlier than 01/01/1991. This edit will preclude dates that are obviously incorrect since the FBI began accepting NIBRS data on this date."), _173("173","Admin Segment","INCIDENT DATE CANNOT BE BEFORE DATE ORI WENT IBR","A Group “A” Incident Report was submitted with Data Element 3 (Incident Date/Hour) containing a date that occurred before the agency converted over to NIBRS. Because of this, the record was rejected. At some point, the participant will convert its local agencies from Summary reporting to Incident-Based Reporting. Once the participant starts to send NIBRS data for a converted agency to the FBI, any data received from this agency that could possibly be interpreted as duplicate reporting within both the Summary System and NIBRS for the same month will be rejected by the FBI. In other words, if the participant sends IBR data for an agency for the first time on September 1999, monthly submittal, dates for incidents, recovered property, and arrests must be within September. The exception is when exceptional clearances occur for a pre-IBR incident. In this case, Data Element 3 (Incident Date/Hour) may be earlier than September 1999, but Data Element 5 (Exceptional Clearance Date) must be within September 1999. The FBI will reject data submitted for prior months. Thereafter, all data coming from this agency must have dates subsequent to the initial start date of September 1999, except as mentioned previously. The Summary System already contains aggregate data for the months prior to NIBRS conversion. If the FBI were to accept IBR data for months previously reported with Summary data, the result would be duplicate reporting for those months."), _175("175","Admin Segment","CANNOT CALCULATE BASE DATE FROM INCIDENT DATE [yyymmdd]","The electronic submission control date (positions 7 through 12, month and year) and Data Element 3 (Incident Date/Hour) must both be valid dates for calculating timeframes."), _178("178","Admin Segment","THIS ADMINISTRATIVE SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Administrative Segment (Level 1) must be 87 characters (not reporting Cargo Theft) or 88 characters (reporting Cargo Theft). All Administrative Segments in a submission must be formatted in only one of these two lengths."), _201("201","Offense Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _202("202","Offense Segment","CONTAINS NONNUMERIC ENTRY","Data Element 10 (Number of Premises Entered) is not a numeric entry of 01 through 99."), _204("204","Offense Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _205("205","Offense Segment","ERROR–INVALID OFFENSE CODE","Data Element 9 (Location Type) Can only be entered when Data Element 6 Offense Code is one of the violations listed below: 210=Extortion/Blackmail 250=Counterfeiting/Forgery 270=Embezzlement 280=Stolen Property Offenses 290=Destruction/Damage/Vandalism of Property 370=Pornography/Obscene Material 510=Bribery 26A =False Pretenses/Swindle/Confidence Game 26B =Credit Card/Automated Teller Machine Fraud 26C =Impersonation 26D =Welfare Fraud 26E =Wire Fraud 26F =Identity Theft 26G =Hacking/Computer Invasion 9A =Betting/Wagering 39B =Operating/Promoting/Assisting Gambling 39D =Gambling Equipment Violations 13C =Intimidation 35A =Drug/Narcotic Violations 35B =Drug Equipment Violations 520=Weapon Law Violations 64A =Human Trafficking, Commercial Sex Acts 64B =Human Trafficking, Involuntary Servitude 40A =Prostitution 40B =Assisting or Promoting Prostitution 40C =Purchasing Prostitution"), _206("206","Offense Segment","ERROR - DUPLICATE VALUE=[value]","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), _207("207","Offense Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","The data element in error can have multiple data values and was entered with multiple values. However, the entry shown cannot be entered with any other data value. Value N=None/Unknown is mutually exclusive with any other information codes."), _215("215","Offense Segment","CANNOT CONTAIN EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _216("216","Offense Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Must be left-justified with blank right-fill if under 12 characters in length."), _217("217","Offense Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _219("219","Offense Segment","DATA CAN ONLY BE ENTERED FOR SPECIFIC OFFENSES","Data Element 12 (Type Criminal Activity/Gang Information) Type criminal activity codes of “B”, “C”, “D”, “E”, “O”, “P”, “T”, or “U” can only be entered when the UCR Offense Code is: 250=Counterfeiting/Forgery 280=Stolen Property Offenses 35A=Drug/Narcotic Violations 35B=Drug Equipment Violations 39C=Gambling Equipment Violations 370=Pornography/Obscene Material 520=Weapon Law Violations (Type Criminal Activity/Gang Information) Gang information codes of “J”, “G”, and “N” can only be entered when the UCR Offense Code is:09A=Murder and Non-negligent Manslaughter 09B=Negligent Manslaughter 100=Kidnapping/Abduction 11A=Rape 11B=Sodomy 11C=Sexual Assault With An Object 11D=Fondling 120=Robbery 13A=Aggravated Assault 13B=Simple Assault 13C=Intimidation (Type Criminal Activity/Gang Information) Criminal Activity codes of “A”, “F”, “I”, and “S” can only be entered when the UCR Offense Code is: 720=Animal Cruelty"), _220("220","Offense Segment","DATA MUST BE ENTERED FOR SPECIFIC OFFENSES","Data Element 12 (Type Criminal Activity/Gang Information) Must be populated with a valid data value and cannot be blank when Data Element 6 (UCR Offense Code) is: 250=Counterfeiting/Forgery 280=Stolen Property Offenses 35A=Drug/Narcotic Violations 35B=Drug Equipment Violations 39C=Gambling Equipment Violations 370=Pornography/Obscene Material 520=Weapon Law Violations 720=Animal Cruelty"), _221("221","Offense Segment","DATA MUST BE ENTERED FOR SPECIFIC OFFENSES","Data Element 13 (Type Weapon/Force Involved) must be populated with a valid data value and cannot be blank when Data Element 6 (UCR Offense Code) is: 09A=Murder and Non-negligent Manslaughter 09B=Negligent Manslaughter 09C=Justifiable Homicide 100=Kidnapping/Abduction 11A=Rape 11B=Sodomy 11C=Sexual Assault With An Object 11D=Fondling 120=Robbery 13A=Aggravated Assault 13B=Simple Assault 210=Extortion/Blackmail 520=Weapon Law Violations 64A=Human Trafficking, Commercial Sex Acts 64B=Human Trafficking, Involuntary Servitude"), _251("251","Offense Segment","INVALID CODE","(Offense Attempted/Completed) Must be a valid code of A=Attempted or C=Completed."), _252("252","Offense Segment","OFFENSE CODE MUST BE 220 WITH A LOCATION TYPE OF 14 OR 19 FOR DATA TO BE ENTERED","When Data Element 10 (Number of Premises Entered) is entered, Data Element 9 (Location Type) must be 14=Hotel/Motel/Etc. or 19=Rental Storage Facility, and Data Element 6 (UCR Offense Code) must be 220 (Burglary)."), _253("253","Offense Segment","MUST BE PRESENT WHEN OFFENSE CODE IS 220","Data Element was not entered; it must be entered when UCR Offense Code of 220=Burglary has been entered."), _254("254","Offense Segment","MUST BE BLANK WHEN OFFENSE IS OTHER THAN 220","Data Element only applies to UCR Offense Code of 220=Burglary. Since a burglary offense was not entered, the Method of Entry should not have been entered."), _255("255","Offense Segment","AUTOMATIC INDICATOR MUST BE BLANK OR “A”","Must be A=Automatic or blank=Not Automatic"), _256("256","Offense Segment","OFFENSE CODES OF 09A, 09B, 09C, 13A, 13B, AND 13C MUST HAVE ENTRY OF “C”","Code must be C=Completed if Data Element 6 (UCR Offense Code) is an Assault or Homicide."), _257("257","Offense Segment","MUST BE PRESENT WITH AN OFFENSE CODE OF 220 AND A LOCATION TYPE OF 14 OR 19","Must be entered if offense code is 220 (Burglary) and if Data Element 9 (Location Type) contains 14=Hotel/Motel/Etc. or 19=Rental Storage Facility."), _258("258","Offense Segment","WEAPON TYPE MUST=11, 12, 13, 14, OR 15 FOR AN “A” IN THE AUTO INDICATOR","In Data Element 13 (Type of Weapon/Force Involved), A=Automatic is the third character of code. It is valid only with the following codes: 11=Firearm (Type Not Stated) 12=Handgun 13=Rifle 14=Shotgun 15=Other Firearm A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm."), _262("262","Offense Segment","DUPLICATE OFFENSE SEGMENT","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. In this case, two Offense Segments were submitted having the same offense in Data Element 6 (UCR Offense Code)."), _263("263","Offense Segment","CANNOT HAVE MORE THAN 10 OFFENSES","Can be submitted only 10 times for each Group A Incident Report; 10 offense codes are allowed for each incident."), _264("264","Offense Segment","GROUP “A” OFFENSE CANNOT CONTAIN A GROUP “B” OFFENSE","Data Element 6 (UCR Offense Code) must be a Group “A” UCR Offense Code, not a Group “B” Offense Code."), _265("265","Offense Segment","INVALID WEAPON [weapon-code] WITH AN OFFENSE OF 13B","If an Offense Segment (Level 2) was submitted for 13B=Simple Assault, Data Element 13 (Type Weapon/Force Involved) can only have codes of 40=Personal Weapons, 90=Other, 95=Unknown, and 99=None. All other codes are not valid because they do not relate to a simple assault."), _266("266","Offense Segment","NO OTHER OFFENSE CAN BE SUBMITTED WITH AN 09C OFFENSE","When a Justifiable Homicide is reported, no other offense may be reported in the Group “A” Incident Report. These should be submitted on another Group “A” Incident Report."), _267("267","Offense Segment","INVALID WEAPON [weapon-code] WITH AN OFFENSE OF [offense]","If a homicide offense is submitted, Data Element 13 (Type Weapon/Force Involved) cannot have 99=None. Some type of weapon/force must be used in a homicide offense."), _268("268","Offense Segment","LARCENY OFFENSE CANNOT HAVE A MOTOR VEHICLE PROPERTY DESCRIPTION ENTERED","Cannot be submitted with a data value for a motor vehicle in Data Element 15 (Property Description) when Data Element 6 (UCR Offense Code) contains an offense of (23A–23H)=Larceny/Theft Offenses; stolen vehicles cannot be reported for a larceny"), _269("269","Offense Segment","POSSIBLE CLASSIFICATION ERROR OF AGGRAVATED ASSAULT 13A CODED AS SIMPLE 13B","If Data Element 6 (UCR Offense Code) is 13B=Simple Assault and the weapon involved is 11=Firearm, 12=Handgun, 13=Rifle, 14=Shotgun, or 15=Other Firearm, then the offense should instead be classified as 13A=Aggravated Assault."), _270("270","Offense Segment","JUSTIFIABLE HOMICIDE MUST BE CODED AS NON-BIAS MOTIVATED","Must be 88=None when Data Element 6 (UCR Offense Code) is 09C=Justifiable Homicide."), _284("284","Offense Segment","THIS OFFENSE SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Offense Segment (Level 2) must be 63 characters (reporting only Bias Motivation #1) or 71 characters (reporting Bias Motivations #2–#5). All Offense Segments in a submission must be formatted in only one of these two lengths."), _301("301","Property Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _302("302","Property Segment","CONTAINS NONNUMERIC ENTRY","Must be numeric entry with zero left-fill. If Data Element 21 (Estimated Quantity) has the error, note that any decimal fractional quantity must be expressed in thousandths as three numeric digits. If no fractional quantity was involved, then all zeros should be entered."), _304("304","Property Segment","INVALID DATA VALUE—NOT ON FBI VALIDATION TABLE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _305("305","Property Segment","DATE RECOVERED IS INVALID","Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31 days). The date cannot be later than that entered within the Month of Electronic Submission and Year of Electronic submission fields on the data record. For example, if Month of Electronic Submission and Year of Electronic Submission are 06/1999, the recovered date cannot contain any date 07/01/1999 or later. Cannot be earlier than Data Element 3 (Incident Date/Hour)."), _306("306","Property Segment","ERROR–DUPLICATE DATA VALUE","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes. There are two exceptions to this rule: 1) When a data value is entered in both Drug Type 1 and Drug Type 2, but different measurement categories are entered in Data Element 22 (Type Drug Measurement); this is allowed. For example, when A=Crack Cocaine is entered in Drug Type 1 and it is also entered in Drug Type 2, Data Element 22 (Type Drug Measurement) must be two different measurement categories (i.e., grams and liters) and not grams and pounds (same weight category). 2) When the data value is U=Unknown; it can be entered only once."), _315("315","Property Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Data Element 2 (Incident Number) Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _316("316","Property Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Data Element 2 (Incident Number) Must be left- justified with blank right-fill if under 12 characters in length."), _317("317","Property Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _320("320","Property Segment","RECOVERED DATE PREDATES STOLEN DATE","The date property is recovered cannot be before the date it is stolen"), _342("342","Property Segment","WARNING - PROPERTY DESC(15) HAD VALUE (16) THAT EXCEEDED THRESHOLD OF [$ value]","When referenced data element contains a value that exceeds an FBI-assigned threshold amount, a warning message will be created. The participant is asked to check to see if the value entered was a data entry error, or if it was intended to be entered. A warning message is always produced when the value is $1,000,000 or greater. For example, if the value of a property is $12,000.99 but is inadvertently entered as $1,200,099 in the computer record sent to the FBI, a warning message will be generated. In this case, the cents were entered as whole dollars."), _343("343","Property Segment","WARNING - 280 OFFENSE HAS RECOVERED VEHICLE BUT 240 DOESN'T SHOW STOLEN","This is a warning message only. This warning is generated when a 280 Stolen Property Offense and a 240 Motor Vehicle Theft are submitted that contain questionable property reporting. When the incident contains a recovered vehicle but does not also have a stolen vehicle, this warning message is created. The incident should be reviewed and if there was indeed a stolen vehicle, the incident should be resubmitted reflecting both stolen and recovered vehicles."), _351("351","Property Segment","PROPERTY VALUE OF ZERO IS NOT ALLOWED","Data Element 16 (Value of Property) Cannot be zero unless Data Element 15 (Property Description) is: Mandatory zero 09=Credit/Debit Cards 22=Nonnegotiable Instruments 48=Documents–Personal or Business 65=Identity Documents 66=Identity–Intangible Optional zero 77=Other 99=(blank)–this data value is not currently used by the FBI.by the FBI"), _352("352","Property Segment","DATA ELEMENTS 15 - 22 MUST BE BLANK WHEN PROPERTY LOSS CODE=1 OR 8","When this error occurs, data were found in one or more of the referenced data elements. These data elements must be blank based on other data element values that prohibit data being entered in these data elements. For example, if Data Element 14 (Type property Loss/Etc.) is 8=Unknown, Data Elements 15 through 22 must be blank. If it is 1=None and offense is 35A, then Data Elements 15 through 19 and 21 through 22 must be blank. If it is 1=None and offense is not 35A, then Data Elements 15 through 22 must be blank. The exception to this rule is when Data Element 6 (UCR Offense Code) is 35A=Drug/ Narcotic Violations and Data Element 14 (Type Property Loss/Etc.) is 1=None; Data Element 20 (Suspected Drug Type) must be entered."), _353("353","Property Segment","PENDING INVENTORY MUST HAVE PROPERTY VALUE OF 1","Data Element 15 (Property Description) is 88=Pending Inventory, but Data Element 16 (Value of Property) is not $1. Determine which of the data elements was entered incorrectly."), _354("354","Property Segment","DATA ELEMENT 15 WAS NOT ENTERED, BUT VALUE ($) WAS","Data Element 16 (Value of Property) contains a value, but Data Element 15 (Property Description) was not entered."), _355("355","Property Segment","PROPERTY LOSS CODE (14) MUST=5 (RECOVERED) FOR DATA TO BE ENTERED","Data Element 14 (Type Property Loss/Etc.) must be 5=Recovered for Data Element 17 (Date Recovered) to be entered."), _356("356","Property Segment","PROPERTY DESCRIPTION (15) AND VALUE (16) MUST BOTH EXIST IF DATA ARE PRESENT","Data Element 17 (Date Recovered) was entered, but Data Elements 15 (Property Description) and/or 16 (Property Value) were not entered."), _357("357","Property Segment","PROPERTY LOSS (14) MUST BE 7 WITH AN OFFENSE CODE OF 240 FOR DATA TO BE ENTERED","Data Element 18 (Number of Stolen Motor Vehicles) was entered. However, Data Element 14 (Type Property Loss/Etc.) 7=Stolen/Etc. was not entered, and/or Data Element 6 (UCR Offense Code) of 240=Motor Vehicle Theft was not entered, and/or Data Element 7 (Offense Attempted/Completed) was A=Attempted."), _358("358","Property Segment","DATA MUST EXIST WITH AN OFFENSE CODE OF 240 AND A PROPERTY","LOSS OF 7 Entry must be made for Data Element 18 (Number of Stolen Motor Vehicles) when Data Element 6 (UCR Offense Code) is 240=Motor Vehicle Theft, Data Element 7 (Offense Attempted/Completed) is C=Completed, and Data Element 14 (Type Property Loss/Etc.) is 7=Stolen/Etc."), _359("359","Property Segment","ALL NONVEHICULAR PROPERTY DESCRIPTIONS WERE ENTERED","Must be one of the following when Data Element 18 (Number of Stolen Motor Vehicles) or Data Element 19 (Number of Recovered Motor Vehicles) contain a data value other than 00=Unknown: 03=Automobiles 05=Buses 24=Other Motor Vehicles 28=Recreational Vehicles 37=Trucks"), _360("360","Property Segment","PROPERTY LOSS (14) MUST BE 5 WITH AN OFFENSE CODE OF 240 FOR DATA TO BE ENTERED","Data Element 19 (Number of Recovered Motor Vehicles) was entered. However, Data Element 14 (Type Property Loss/Etc.) 5=Recovered was not entered, and/or Data Element 6 (UCR Offense Code) of 240=Motor Vehicle Theft was not entered, and/or Data Element 7 (Offense Attempted/Completed) was A=Attempted. The exception to this rule is when recovered property is reported for a pre-NIBRS incident. In this case, Segment Level 3 (Property Segment) will contain A=Add, but the data value in Data Element 2 (Incident Number) will not match an incident already on file in the national UCR database. The segment will be processed, but used only for SRS purposes and will not be included in the agency’s NIBRS figures."), _361("361","Property Segment","DATA MUST EXIST WITH AN OFFENSE CODE OF 240 AND A PROPERTYLOSS OF 5","Entry must be made when Data Element 6 (UCR Offense Code) is 240=Motor Vehicle Theft, Data Element 14 (Type Property Loss/Etc.) is 5=Recovered, and Data Element 15 (Property Description) contains a vehicle code."), _362("362","Property Segment","TWO OTHER CODES MUST BE ENTERED WHEN AN “X” IS PRESENT","Since X=Over 3 Drug Types was entered in Data Element 20 (Suspected Drug Type), two other codes must also be entered. There are less than three codes present."), _363("363","Property Segment","WITH A CODE OF “X” BOTH QUANTITY (21) AND MEASUREMENT (22) MUST BE BLANK","Since Data Element 20 (Suspected Drug Type) contains X=Over 3 Drug Types, Data Element 21 (Estimated Quantity) and 22 (Type Measurement) must be blank"), _364("364","Property Segment","WITH DATA ENTERED BOTH QUANTITY (21) AND MEASUREMENT (22) MUST BE PRESENT","When Data Element 6 (UCR Offense Code) is 35A=Drug/Narcotic Violations, 14 (Type Property Loss/Etc.) is 6=Seized, 15 (Type Property Loss/Etc.) is 10=Drugs, and Data Element 20 (Suspected Drug Type) is entered, both Data Element 21 (Estimated Quantity) and 22 (Type Measurement) must also be entered."), _365("365","Property Segment","OFFENSE=35A AND PROPERTY LOSS=6 AND DESCRIPTION=10 MUST EXIST","Data Element 20 (Suspected Drug Type) was entered, but one or more required data elements were not entered. Data Element 6 (UCR Offense Code) must be 35A=Drug/Narcotic Violations, Data Element 14 (Type Property Loss/Etc.) must be 6=Seized, and Data Element 15 (Property Description) must be 10=Drugs/Narcotics. There could be multiple underlying reasons causing this error to be detected. One of them might be that Data Element 20 (Suspected Drug Type) was entered by mistake. Perhaps the code entered in Data Element 15 (Property Description) should have been 01=Aircraft, but by entering the code as 10=Drugs/Narcotics, someone thought that Data Element 20 must be entered, etc."), _366("366","Property Segment","WITH DATA ENTERED BOTH TYPE (20) AND MEASUREMENT (22) MUST BE PRESENT","Data Element 21 (Estimated Quantity) was entered, but 20 (Suspected Drug Type) and/or 22 (Type Measurement) were not entered; both must be entered."), _367("367","Property Segment","DRUG TYPE MUST BE “E”, “G”, OR “K” FOR A VALUE OF “NP”","Data Element 22 (Type Measurement) was entered with NP in combination with an illogical drug type. Based upon the various ways a drug can be measured, very few edits can be done to check for illogical combinations of drug type and measurement. The only restriction will be to limit NP=Number of Plants to the following drugs: DRUG MEASUREMENT E=Marijuana NP G=Opium NP K=Other Hallucinogens NP All other Data Element 22 (Type Measurement) codes are applicable to any Data Element 20 (Suspected Drug Type) code."), _368("368","Property Segment","WITH DATA ENTERED BOTH TYPE (20) AND QUANTITY (21) MUST BE PRESENT","Data Element 22 (Type Measurement) was entered, but 20 (Suspected Drug Type) and/or 21 (Estimated Quantity) were not entered; both must be entered."), _372("372","Property Segment","DATA ELEMENTS 15-22 WERE ALL BLANK WITH THIS PROPERTY LOSS CODE","If Data Element 14 (Type Property/Loss/Etc.) is 2=Burned, 3=Counterfeited/ Forged, 4=Destroyed/Damaged/Vandalized, 5=Recovered, 6=Seized, or 7=Stolen/Etc., Data Elements 15 through 22 must have applicable entries in the segment."), _375("375","Property Segment","MANDATORY FIELD WITH THE PROPERTY LOSS CODE ENTERED","At least one Data Element 15 (Property Description) code must be entered when Data Element 14 (Type Property Loss/Etc.) contains Property Segment(s) for: 2=Burned 3=Counterfeited/Forged 4=Destroyed/Damaged/Vandalized 5=Recovered 6=Seized 7=Stolen/Etc."), _376("376","Property Segment","DUPLICATE PROPERTY SEGMENT ON ELECTRONIC SUBMISSION (TYPE LOSS=[loss- code])","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. Example, two property segments cannot be submitted having the same entry in Data Element 14 (Type Property Loss/Etc.)."), _382("382","Property Segment","DRUG/NARCOTIC VIOLATIONS OFFENSE MUST BE SUBMITTED FOR SEIZED DRUGS","Segment Level 3 (Property Segment) cannot be submitted with 10=Drugs/Narcotics in Data Element 15 (Property Description) and blanks in Data Element 16 (Value of Property) unless Data Element 6 (UCR Offense Code) is 35A=Drug/Narcotic Violations."), _383("383","Property Segment","PROPERTY VALUE MUST BE BLANK FOR 35A (SINGLE OFFENSE)","Data Element 16 (Value of Property) has a value other than zero entered. Since Data Element 15 (Property Description) code is 10=Drugs/Narcotics and the only Crime Against Property offense submitted is a 35A=Drug/Narcotic Violations, Data Element 16 (Value of Property) must be blank."), _384("384","Property Segment","DRUG QUANTITY MUST BE NONE WHEN DRUG MEASUREMENT IS NOT REPORTED","Data Element 21 (Estimated Drug Quantity) must be 000000001000=None (i.e., 1) when Data Element 22 (Type Drug Measurement) is XX=Not Reported indicating the drugs were sent to a laboratory for analysis. When the drug analysis is received by the LEA, Data Element 21 and Data Element 22 should be updated with the correct data values."), _387("387","Property Segment","WITH A PROPERTY LOSS=6 AND ONLY OFFENSE 35A CANNOT HAVE DESCRIPTION 11or WITH A PROPERTY LOSS=6 AND ONLY OFFENSE 35B CANNOT HAVE DESCRIPTION 10","To ensure that 35A-35B Drug/Narcotic Offenses- Drug Equipment Violations are properly reported, Data Element 15 (Property Description) of 11=Drug/Narcotic Equipment is not allowed with only a 35A Drug/Narcotic Violation. Similarly, 10=Drugs/Narcotics is not allowed with only a 35B Drug Equipment Violation. And Data Element 14 (Type Property Loss/Etc.) is 6=Seized."), _388("388","Property Segment","NUMBER STOLEN IS LESS THAN NUMBER OF VEHICLE CODES","More than one vehicle code was entered in Data Element 15 (Property Description), but the number stolen in Data Element 18 (Number of Stolen Motor Vehicles) is less than this number. For example, if vehicle codes of 03=Automobiles and 05=Buses were entered as being stolen, then the number stolen must be at least 2, unless the number stolen was unknown (00). The exception to this rule is when 00=Unknown is entered in Data Element 18."), _389("389","Property Segment","NUMBER RECOVERED IS LESS THAN NUMBER OF VEHICLE CODES","More than one vehicle code was entered in Data Element 15 (Property Description), but the number recovered in Data Element 19 (Number of Recovered Motor Vehicles) was less than this number. For example, if vehicle codes of 03=Automobiles and 05=Buses were entered as being recovered, then the number recovered must be at least 2, unless the number recovered was unknown (00). The exception to this rule is when 00=Unknown is entered in Data Element 18."), _390("390","Property Segment","ILLOGICAL PROPERTY DESCRIPTION FOR THE OFFENSE SUBMITTED","Data Element 15 (Property Description) must contain a data value that is logical for one or more of the offenses entered in Data Element 6 (UCR Offense Code). Illogical combinations include: 1) Property descriptions for structures are illogical with 220=Burglary/Breaking & Entering or 240=Motor Vehicle Theft 2) Property descriptions for items that would not fit in a purse or pocket (aircraft, vehicles, structures, a person’s identity, watercraft, etc.) are illogical with 23A=Pocket-picking or 23B=Purse- snatching 3) Property descriptions that cannot be shoplifted due to other UCR definitions (aircraft, vehicles, structures, a person’s identity, watercraft, etc.) are illogical with 23C=Shoplifting 4) Property descriptions for vehicles and structures are illogical with 23D=Theft from Building, 23E=Theft from Coin-Operated Machine or Device, 23F=Theft from Motor Vehicle, and 23G=Theft of Motor Vehicle Parts or Accessories Property descriptions for vehicles are illogical with 23H=All Other Larceny"), _391("391","Property Segment","PROPERTY VALUE MUST BE ZERO FOR DESCRIPTION SUBMITTED","Data Element 15 (Property Description) has a code that requires a zero value in Data Element 16 (Value of Property). Either the wrong property description code was entered or the property value was not entered. (This error was formerly error number 340, a warning message.) Data Element 16 (Value of Property) must be zero when Data Element 15 (Property Description) is: 09=Credit/Debit Cards 22=Nonnegotiable Instruments 48=Documents–Personal or Business 65=Identity Documents 66=Identity–Intangible"), _392("392","Property Segment","35A OFFENSE ENTERED AND 1=NONE ENTERED; MISSING SUSPECTED DRUG TYPE (20)","An offense of 35A Drug/Narcotic Violations and Data Element 14 (Type Property Loss/Etc.) with1=None were entered but Data Element 20 (Suspected Drug Type) was not submitted. Since a drug"), _401("401","Victim Segment","MUST BE PRESENT -- MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _402("402","Victim Segment","CONTAINS NONNUMERIC DIGITS","Must contain numeric entry with zero left-fill."), _404("404","Victim Segment","INVALID DATA VALUE -- NOT ON FBI VALIDATION TABLE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _406("406","Victim Segment","NCA07: DUPLICATE VALUE=[value]","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), _407("407","Victim Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 33 (Type Injury) Can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), _408("408","Victim Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 26 (Age of Victim) contains data, but is not left-justified. A single two-character age must be in positions 1 and 2 of the field."), _409("409","Victim Segment","CONTAINS NONNUMERIC ENTRY","Data Element 26 (Age of Victim) contains more than two characters indicating a possible age-range was being attempted. If so, the field must contain numeric entry of four digits."), _410("410","Victim Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 26 (Age of Victim) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _415("415","Victim Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NONBLANK CHARACTERS","Data Element 2 (Incident Number) Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _416("416","Victim Segment","MUST BE LEFT- JUSTIFIED–BLANK DETECTED IN FIRST POSITION","Data Element 2 (Incident Number) Must be left-justified with blank right-fill if under 12 characters in length."), _417("417","Victim Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Data Element 2 (Incident Number)Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _419("419","Victim Segment","DATA CAN ONLY BE ENTERED FOR SPECIFIC OFFENSES","Data Element 31 (Aggravated Assault/Homicide Circumstances) can only be entered when one or more of the offenses in Data Element 24 (Victim Connected to UCR Offense Code) are: 09A=Murder and Non-negligent Manslaughter 09B=Negligent Manslaughter 09C=Justifiable Homicide 13A=Aggravated Assault Data Element 33 (Type Injury) can only be entered when one or more of the offenses in Data Element 24 (Victim Connected to UCR Offense Code) are: 100=Kidnapping/Abduction 11A=Rape 11B=Sodomy 11C=Sexual Assault With An Object 11D=Fondling 120=Robbery 13A=Aggravated Assault 13B=Simple Assault 210=Extortion/Blackmail 64A=Human Trafficking, Commercial Sex Acts 64B=Human Trafficking, Involuntary Servitude"), _422("422","Victim Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 26 (Age of Victim) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _449("449","Victim Segment","WARNING–VICTIM IS SPOUSE, BUT AGE IS LESS THAN 18","Data Element 26 (Age of Victim) cannot be less than 18 years old when Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE = Spouse."), _450("450","Victim Segment","VICTIM IS SPOUSE, BUT AGE IS LESS THAN 14","Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE=Spouse. When this is so, the age of the victim cannot be less than 10 years."), _451("451","Victim Segment","VICTIM NUMBER ALREADY EXISTS","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. In this case, two victim segments were submitted having the same entry in Data Element 23 (Victim Sequence Number)."), _453("453","Victim Segment","MUST BE PRESENT WHEN VICTIM TYPE (25)=I","The Data Element associated with this error must be present when Data Element 25 (Type of Victim) is I=Individual."), _454("454","Victim Segment","MUST BE ENTERED WHEN VICTIM TYPE IS LAW ENFORCEMENT OFFICER","Data Element 25A (Type of Officer Activity/Circumstance), Data Element 25B (Officer Assignment Type), Data Element 26 (Age of Victim), Data Element 27 (Sex of Victim), and Data Element 28 (Race of Victim) must be entered when Data Element 25 (Type of Victim) is L=Law Enforcement Officer."), _455("455","Victim Segment","ADDITIONAL JUSTIFIABLE HOMICIDE IS MANDATORY WITH A 20 OR 21 ENTERED","Data Element 31 (Aggravated Assault/Homicide Circumstances) contains: 20=Criminal Killed by Private Citizen Or 21=Criminal Killed by Police Officer, but Data Element 32 (Additional Justifiable Homicide Circumstances) was not entered."), _456("456","Victim Segment","ONLY ONE VALUE GREATER THAN OR EQUAL TO 10 CAN BE ENTERED","Data Element 31 (Aggravated Assault/Homicide Circumstances) was entered with two entries, but was rejected for one of the following reasons: 1) Value 10=Unknown Circumstances is mutually exclusive with any other value. 2) More than one category (i.e., Aggravated Assault, Negligent Manslaughter, etc.) was entered."), _457("457","Victim Segment","WHEN DATA ELEMENT 32 IS ENTERED, DATA ELEMENT 31 MUST EQUAL 20 OR 21","Data Element 32 (Additional Justifiable Homicide Circumstances) was entered, but Data Element 31 (Aggravated Assault/Homicide Circumstances) does not reflect a justifiable homicide circumstance."), _458("458","Victim Segment","VICTIM TYPE (25) MUST BE “I” OR “L” FOR DATA TO BE ENTERED","The Data Element associated with this error cannot be entered when Data Element 25 (Type of Victim) is not I=Individual or L=Law Enforcement Officer when Data Element 24 (Victim Connected to UCR Offense Code) contains a Crime Against Person."), _459("459","Victim Segment","NEED A CRIME AGAINST PERSON OR ROBBERY FOR DATA TO BE ENTERED","Data Element 34 (Offender Numbers To Be Related) was entered but should only be entered if one or more of the offenses entered into Data Element 24 [Victim Connected to UCR Offense Code(s)] is a Crime Against Person or is a Robbery Offense (120). None of these types of offenses were entered."), _460("460","Victim Segment","RELATIONSHIP MUST BE ENTERED WHEN AN OFFENDER NUMBER (34) EXISTS","Corresponding Data Element 35 (Relationship of Victim to Offenders) data must be entered when Data Element 34 (Offender Numbers To Be Related) is entered with a value greater than 00."), _461("461","Victim Segment","VICTIM TYPE CANNOT EQUAL “S” WITH AN OFFENSE OF 220","Data Element 25 (Type of Victim) cannot have a value of S=Society/Public when the offense is 220=Burglary/Breaking and Entering."), _462("462","Victim Segment","INVALID AGGRAVATED ASSAULT/HOMICIDE FOR 13A OFFENSE","An Offense Segment (Level 2) was submitted for 13A=Aggravated Assault. Accordingly, Data Element 31 (Aggravated Assault/Homicide Circumstances) can only have codes of 01 through 06 and 08 through 10. All other codes, including 07=Mercy Killing, are not valid because they do not relate to an aggravated assault"), _463("463","Victim Segment","INVALID AGGRAVATED ASSAULT/HOMICIDE FOR 09C OFFENSE","When a Justifiable Homicide is reported, Data Element 31 (Aggravated Assault/Homicide Circumstances) can only have codes of 20=Criminal Killed by Private Citizen or 21=Criminal Killed by Police Officer. In this case, a code other than the two mentioned was entered."), _464("464","Victim Segment","ENTRY FOR TYPE OF VICTIM MUST BE 'I' OR 'L' WHEN THIS OFFENSE CODE IS ENTERED","Data Element 24 (Victim Connected to UCR Offense Codes) contains a Crime Against Person, but Data Element 25 (Type of Victim) is not I=Individual or L=Law Enforcement Officer when Data Element 24 (Victim Connected to UCR Offense Code) contains a Crime Against Person."), _465("465","Victim Segment","ENTRY FOR TYPE OF VICTIM MUST BE “S” WHEN THIS OFFENSE CODE IS ENTERED","Data Element 24 (Victim Connected to UCR Offense Codes) contains a Crime Against Society, but Data Element 25 (Type of Victim) is not S=Society."), _466("466","Victim Segment","OFFENSE MUST BE SUBMITTED AS LEVEL 2 RECORD IF VICTIM IS CONNECTED","Each UCR Offense Code entered into Data Element 24 (Victim Connected to UCR Offense Codes) must have the Offense Segment for the value. In this case, the victim was connected to offenses that were not submitted as Offense Segments. A victim cannot be connected to an offense when the offense itself is not present."), _467("467","Victim Segment","ENTRY FOR TYPE OF VICTIM CANNOT BE “S” WHEN THIS OFFENSE CODE IS ENTERED","Data Element 24 (Victim Connected to UCR Offense Codes) contains a Crime Against Property, but Data Element 25 (Type of Victim) is S=Society. This is not an allowable code for Crime Against Property offenses."), _468("468","Victim Segment","RELATIONSHIP CANNOT BE ENTERED WHEN RELATED TO OFFENDER NUMBER '00'","Data Element 35 (Relationship of Victim to Offenders) cannot be entered when Data Element 34 (Offender Number to be Related) is zero. Zero means that the number of offenders is unknown; therefore, the relationship cannot be entered."), _469("469","Victim Segment","VICTIM SEX MUST BE “M” OR “F” FOR AN 11A OR 36B OFFENSE","Data Element 27 (Sex of Victim) must be M=Male or F=Female to be connected to offense codes of 11A=Forcible Rape and 36B=Statutory Rape."), _470("470","Victim Segment","WHEN “VO” RELATIONSHIP IS PRESENT, MUST HAVE TWO OR MORE VICTIMS AND OFFENDERS","Data Element 35 (Relationship of Victim to Offenders) has a relationship of VO=Victim Was Offender. When this code is entered, a minimum of two victim and two offender segments must be submitted. In this case, only one victim and/or one offender segment was submitted. The entry of VO on one or more of the victims indicates situations such as brawls and domestic disputes. In the vast majority of cases, each victim is also the offender; therefore, every victim record would contain a VO code. However, there may be some situations where only one of the victims is also the offender, but where the other victim(s) is not also the offender(s)."), _471("471","Victim Segment","ONLY ONE VO RELATIONSHIP PER VICTIM","Data Element 35 (Relationship of Victim to Offenders) has relationships of VO=Victim Was Offender that point to multiple offenders, which is an impossible situation. A single victim cannot be two offenders."), _472("472","Victim Segment","WHEN OFFENDER AGE/SEX/RACE ARE UNKNOWN, RELATIONSHIP MUST BE “RU”=UNKNOWN","Data Element 35 (Relationship of Victim to Offenders) has a relationship to the offender that is not logical. In this case, the offender was entered with unknown values for age, sex, and race. Under these circumstances, the relationship must be entered as RU=Relationship Unknown."), _474("474","Victim Segment","ONLY ONE VO RELATIONSHIP CAN BE ASSIGNED TO A SPECIFIC OFFENDER","Segment Level 4 (Victim Segment) cannot be submitted multiple times with VO=Victim Was Offender in Data Element 35 (Relationship of Victim to Offender) when Data Element 34 (Offender Number to be Related) contains the same data value (indicating the same offender)."), _475("475","Victim Segment","ONLY ONE “SE”L RELATIONSHIP PER VICTIM","A victim can only have one spousal relationship. In this instance, the victim has a relationship of SE=Spouse to two or more offenders."), _476("476","Victim Segment","ONLY ONE “SE” RELATIONSHIP CAN BE ASSIGNED TO A SPECIFIC OFFENDER","An offender can only have one spousal relationship. In this instance, two or more victims have a relationship of SE=Spouse to the same offender."), _477("477","Victim Segment","INVALID AGGRAVATED ASSAULT/HOMICIDE CIRCUMSTANCES FOR CONNECTED OFFENSE","A victim segment was submitted with Data Element 24 (Victim Connected to UCR Offense Code) having an offense that does not have a permitted code for Data Element 31 (Aggravated Assault/Homicide Circumstances). Only those circumstances listed in Volume 1, Section VI, are valid for the particular offense."), _478("478","Victim Segment","VICTIM CONNECTED TO AN INVALID COMBINATION OF OFFENSES","Mutually Exclusive offenses are ones that cannot occur to the same victim by UCR definitions. A Lesser Included offense is one that is an element of another offense and should not be reported as having happened to the victim along with the other offense. Lesser Included and Mutually Exclusive offenses are defined as follows: 1) Murder-Aggravated assault, simple assault, and intimidation are all lesser included offenses of murder. Negligent manslaughter is mutually exclusive. 2) Aggravated Assault-Simple assault and intimidation are lesser included Note: Aggravated assault is a lesser included offense of murder, forcible rape, forcible sodomy, sexual assault with an object, and robbery. 3) Simple Assault-Intimidation is a lesser included offense of simple assault. Note: Simple assault is a lesser included offense of murder, aggravated assault, forcible rape, forcible sodomy, sexual assault with an object, forcible fondling, and robbery. 4) Intimidation-Intimidation is a lesser included offense of murder, aggravated assault, forcible rape, forcible sodomy, sexual assault with an object, forcible fondling, and robbery. 5) Negligent Manslaughter-Murder, aggravated assault, simple assault, and intimidation are mutually exclusive offenses. Uniform Crime Reporting Handbook, NIBRS Edition, page 17, defines negligent manslaughter as “The killing of another person through negligence.” Page 12 of the same publication shows that assault offenses are characterized by “unlawful attack[s].” offenses of aggravated assault. 6) Forcible Rape-Aggravated assault, simple assault, intimidation, and forcible fondling are lesser included offenses of forcible rape. Incest and statutory rape are mutually exclusive offenses and cannot occur with forcible rape. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. 7) Forcible Sodomy-Aggravated assault, simple assault, intimidation, and forcible fondling are lesser included offenses of forcible sodomy. Incest and statutory rape are mutually exclusive offenses and cannot occur with forcible sodomy. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. 8) Sexual Assault with an Object- Aggravated assault, simple assault, intimidation, and forcible fondling are lesser included offenses of sexual assault with an object. Incest and statutory rape are mutually exclusive offenses and cannot occur with sexual assault with an object. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. 9) Forcible Fondling-Simple assault and intimidation are lesser included offenses of forcible fondling. Incest and statutory rape are mutually exclusive offenses and cannot occur with forcible fondling. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. Note: Forcible fondling is a lesser included offense of forcible rape, forcible sodomy, and sexual assault with an object. 10) Incest-Forcible rape, forcible sodomy, sexual assault with an object, and forcible fondling are mutually exclusive offenses. Incest involves consent, while the prior offenses involve forced sexual relations against the victim’s will. 11) Statutory Rape-Forcible Rape, forcible sodomy, sexual assault with an object, and forcible fondling are mutually exclusive offenses. Statutory rape involves consent, while the prior offenses involve forced sexual relations against the victim’s will. 12) Robbery-Aggravated assault, simple assault, intimidation, and all theft offenses (including motor vehicle theft) are lesser included offenses of robbery."), _479("479","Victim Segment","SIMPLE ASSAULT(13B) CANNOT HAVE MAJOR INJURIES","A Simple Assault (13B) was committed against a victim, but the victim had major injuries/trauma entered for Data Element 33 (Type Injury). Either the offense should have been classified as an Aggravated Assault (13A) or the victim’s injury should not have been entered as major."), _480("480","Victim Segment","WHEN ASSAULT/HOMICIDE (31) IS 08, INCIDENT MUST HAVE TWO OR MORE OFFENSES","Data Element 31 (Aggravated Assault/Homicide Circumstances) has 08=Other Felony Involved but the incident has only one offense. For this code to be used, there must be an Other Felony. Either multiple entries for Data Element 6 (UCR Offense Code) should have been submitted, or multiple individual victims should have been submitted for the incident report."), _481("481","Victim Segment","VICTIM’S AGE MUST BE LESS THAN [maximum for state] FOR STATUTORY RAPE (36B)","Data Element 26 (Age of Victim) should be under 18 when Data Element 24 (Victim Connected to UCR Offense Code) is 36B=Statutory Rape."), _482("482","Victim Segment","LEOKA VICTIM MUST BE CONNECTED TO MURDER OR ASSAULT OFFENSE","Data Element 25 (Type of Victim) cannot be L=Law Enforcement Officer unless Data Element 24 (Victim Connected to UCR Offense Code) is one of the following: 09A=Murder & Non-negligent Manslaughter 13A=Aggravated Assault 13B=Simple Assault 13C=Intimidation"), _483("483","Victim Segment","VICTIM MUST BE LAW ENFORCEMENT OFFICER TO ENTER LEOKA DATA","Data Element 25A (Type of Officer Activity/Circumstance), Data Element 25B (Officer Assignment Type), Data Element 25C (Officer–ORI Other Jurisdiction), Data Element 26 (Age of Victim), Data Element 27 (Sex of Victim), Data Element 28 (Race of Victim), Data Element 29 (Ethnicity of Victim), Data Element 30 (Resident Status of Victim), and Data Element 34 (Offender Number to be Related) can only be entered when Data Element 25 (Type of Victim) is I=Individual or L=Law Enforcement Officer."), _484("484","Victim Segment","THIS VICTIM SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Victim Segment (Level 4) must be 129 characters (not reporting LEOKA) or 141 characters (reporting LEOKA). All Victim Segments in a submission must be formatted in only one of these two lengths."), _501("501","Offender Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _502("502","Offender Segment","CONTAINS NONNUMERIC ENTRY","Data Element 36 (Offender Sequence Number) must contain numeric entry (00 through 99) with zero left-fill."), _504("504","Offender Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _508("508","Offender Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 37 (Age of Offender) contains data but is not left-justified. A single two-character age must be in positions 1 through 2 of the field."), _509("509","Offender Segment","CONTAINS NONNUMERIC ENTRY","Data Element 37 (Age of Offender) contains more than two characters indicating a possible age- range is being attempted. If so, the field must contain a numeric entry of four digits."), _510("510","Offender Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 37 (Age of Offender) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _515("515","Offender Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _516("516","Offender Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Must be left-justified with blank right-fill if under 12 characters in length."), _517("517","Offender Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _522("522","Offender Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 37 (Age of Offender) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _549("549","Offender Segment","WARNING–OFFENDER IS SPOUSE, BUT AGE IS LESS THAN 18","Data Element 37 (Age of Offender) cannot be less than 18 years old when Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE = Spouse."), _550("550","Offender Segment","OFFENDER IS SPOUSE, BUT AGE IS LESS THAN 10","Cannot be less than 10 years old when Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE=Spouse."), _551("551","Offender Segment","DUPLICATE OFFENDER SEGMENT","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. In this case, two Offender Segments were submitted having the same entry in Data Element 36 (Offender Sequence Number)."), _552("552","Offender Segment","CANNOT BE PRESENT WHEN OFFENDER NUMBER IS “00” UNKNOWN","Data Element 37 (Age of Offender) cannot be entered when Data Element 36 (Offender Sequence Number) is 00=Unknown."), _553("553","Offender Segment","SEX OF VICTIM AND OFFENDER DOES NOT REFLECT THE RELATIONSHIP","Data Element 35 (Relationship of Victim to Offenders) has a relationship that is inconsistent with the offender’s sex. The sex of the victim and/or offender must reflect the implied relationship. For example, if the relationship of the victim to offender is Homosexual Relationship, then the victim’s sex must be the same as the offender’s sex. The following relationships must reflect either the Same or Different sex codes depending upon this relationship: Relationship Sex Code BG=Victim was Boyfriend/Girlfriend Different XS=Victim was Ex-Spouse Different SE=Victim was Spouse Different CS=Victim was Common-Law Spouse Different HR=Homosexual Relationship Same"), _554("554","Offender Segment","AGE OF VICTIM AND OFFENDER DOES NOT REFLECT THE RELATIONSHIP","Data Element 35 (Relationship of Victim to Offenders) has a relationship that is inconsistent with the offender’s age. The age of the victim and/or offender must reflect the implied relationship. For example, if the relationship of the victim to offender is PA=Parent, then the victim’s age must be greater than the offender’s age. The following relationships must be consistent with the victim’s age in relation to the offender’s age: Relationship Victim’s Age Is CH=Victim was Child Younger PA=Victim was Parent Older GP=Victim was Grandparent Older GC=Victim was Grandchild Younger"), _555("555","Offender Segment","OFFENDER “00” EXISTS— CANNOT SUBMIT MORE OFFENDERS","When multiple Offender Segments are submitted, none can contain a 00=Unknown value because the presence of 00 indicates that the number of offenders is unknown. In this case, multiple offenders were submitted, but one of the segments contains the 00=Unknown value."), _556("556","Offender Segment","OFFENDER AGE MUST BE NUMERIC DIGITS","Data Element 37 (Age of Offender) must contain numeric entry of 00 through 99"), _557("557","Offender Segment","OFFENDER SEQUENCE NUMBER CANNOT BE UNKNOWN IF INCIDENT CLEARED EXCEPTIONALLY","Data Element 36 (Offender Sequence Number) contains 00 indicating that nothing is known about the offender(s) regarding number and any identifying information. In order to exceptionally clear the incident, the value cannot be 00. The incident was submitted with Data Element 4 (Cleared Exceptionally) having a value of A through E."), _558("558","Offender Segment","AT LEAST ONE OFFENDER MUST HAVE KNOWN VALUES","None of the Offender Segments contain all known values for Age, Sex, and Race. When an Incident is cleared exceptionally (Data Element 4 contains an A through E), one offender must have all known values."), _559("559","Offender Segment","OFFENDER DATA MUST BE PRESENT IF OFFENSE CODE IS 09C, JUSTIFIABLE HOMICIDE","The incident was submitted with Data Element 6 (UCR Offense Code) value of 09C=Justifiable Homicide, but unknown information was submitted for all the offender(s). At least one of the offenders must have known information for Age, Sex, and Race."), _560("560","Offender Segment","VICTIM’S SEX CANNOT BE SAME FOR ALL OFFENDERS FOR OFFENSES OF RAPE","Segment Level 5 (Offender Segment) must contain a data value for at least one offender in Data Element 38 (Sex of Offender) that is not the same sex that is entered in Data Element 27 (Sex of Victim) when Data Element 6 (UCR Offense Code) is 11A=Rape."), _572("572","Offender Segment","RELATIONSHIP UNKNOWN IF OFFENDER INFO MISSING","Data Element 37 (Age of Offender) If Data Element 37 (Age of Offender) is 00=Unknown, Data Element 38 (Sex of Offender) is U=Unknown, and Data Element 39 (Race of Offender) is U=Unknown then Data Element 35 (Relationship of Victim to Offender) must be RU=Relationship Unknown."), _584("584","Offender Segment","THIS OFFENDER SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Offender Segment (Level 5) must be 45 characters (not reporting Offender Ethnicity) or 46 characters (reporting Offender Ethnicity). All Offender Segments in a submission must be formatted in only one of these two lengths."), _601("601","Arrestee Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _602("602","Arrestee Segment","CONTAINS NONNUMERIC ENTRY","Data Element 40 (Arrestee Sequence Number) must be numeric entry of 01 to 99 with zero left- fill."), _604("604","Arrestee Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _605("605","Arrestee Segment","INVALID ARREST DATE","Data Element 42 (Arrest Date) Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31 days). The date cannot exceed the current date. The date cannot be later than that entered within the Month of Electronic submission and Year of Electronic submission fields on the data record. For example, if Month of Electronic submission and Year of Electronic submission are 06/1999, the arrest date cannot contain any date 07/01/1999 or later."), _606("606","Arrestee Segment","ERROR - DUPLICATE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), _607("607","Arrestee Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), _608("608","Arrestee Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) contains data, but is not left-justified. A single two-character age must be in positions 1 through 2 of the field."), _609("609","Arrestee Segment","CONTAINS NONNUMERIC ENTRY","Data Element 47 (Age of Arrestee) contains more than two characters indicating a possible age- range is being attempted. If so, the field must contain a numeric entry of four digits."), _610("610","Arrestee Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 47 (Age of Arrestee) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _615("615","Arrestee Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _616("616","Arrestee Segment","MUST BE LEFT-JUSTIFIED— BLANK DETECTED IN FIRST POSITION","Data Element 2 (Incident Number) and Data Element 41 (Arrest Transaction Number) must be left justified with blank right-fill when less than 12 characters in length."), _617("617","Arrestee Segment","CANNOT HAVE CHARACTERS OTHER THAN A-Z, 0-9, HYPHENS, AND/OR BLANKS","Data Element 2 (Incident Number) Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _618("618","Arrestee Segment","AGENCY IS IN COVERED-BY STATUS","Data Element 42 (Arrest Date) cannot contain a date on or after the date a LEA is placed in Covered-by Status. When data are received for a LEA in Covered-by Status, the FBI will remove the agency from Covered-by Status, process the submission, and notify the agency. Additionally, adjustments to previously- submitted data from an agency now in Covered-by Status will be processed and no error will be generated."), _622("622","Arrestee Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _623("623","Arrestee Segment","CLEARANCE INDICATOR AND CLEARANCE OFFENSE CODE MUST BE BLANK","Clearance Indicator and Clearance Offense Code must be blank when Segment Action Type on Level 6 (Arrestee Segment) is I=Incident."), _640("640","Arrestee Segment","WARNING–NO DISPOSITION FOR POSSIBLE JUVENILE ARRESTEE","Data Element 52 (Disposition of Arrestee Under 18) was not entered, but Data Element 47 (Age of Arrestee) indicates an age-range for a juvenile. The low age is a juvenile and the high age is an adult, but the average age is a juvenile. Note: When an age-range is not entered and the age is a juvenile, then the disposition must be entered. These circumstances were flagged by the computer as a possible discrepancy between age and disposition and should be checked for possible correction by the participant."), _641("641","Arrestee Segment","WARNING - ARRESTEE HAD AN AGE OF 99 OR OLDER","Data Element 47 (Age of Arrestee) was entered with a value of 99 which means the arrestee was over 98 years old. Verify that the submitter of data is not confusing the 99=Over 98 Years Old with 00=Unknown."), _652("652","Arrestee Segment","DISPOSITION MUST BE ENTERED WHEN AGE IS LESS THAN 18","Data Element 52 (Disposition of Juvenile) was not entered, but Data Element 47 (Age of Arrestee) is under 18. Whenever an arrestee’s age indicates a juvenile, the disposition must be entered."), _653("653","Arrestee Segment","FOR AGE GREATER THAN 17 DISPOSITION SHOULD NOT BE ENTERED","Data Element 52 (Disposition of Juvenile) was entered, but Data Element 47 (Age of Arrestee) is 18 or greater. Whenever an arrestee’s age indicates an adult, the juvenile disposition cannot be entered because it does not apply."), _654("654","Arrestee Segment","AUTOMATIC INDICATOR MUST BE BLANK OR “A”","Data Element 46 (Arrestee Was Armed With) does not have A=Automatic or a blank in the third position of field."), _655("655","Arrestee Segment","WEAPON TYPE MUST=11, 12, 13, 14, OR 15 FOR AN “A” IN THE AUTO INDICATOR","In Data Element 46 (Arrestee Was Armed With), A=Automatic is the third character of code. It is valid only with codes: 11=Firearm (Type Not Stated) 12=Handgun 13=Rifle 14=Shotgun 15=Other Firearm A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm."), _656("656","Arrestee Segment","THIS ARRESTEE EXCEEDED THE NUMBER OF OFFENDERS ON THE GROUP 'A' INCIDENT","A Group “A” Incident Report was submitted with more arrestees than offenders. The number (nn) of offenders is shown within the message. The incident must be resubmitted with additional Offender Segments. This message will also occur if an arrestee was submitted and Data Element 36 (Offender Sequence Number) was 00=Unknown. The exception to this rule is when an additional arrest is reported for a pre-NIBRS incident. In this case, Segment Level 6 (Arrestee Segment) will contain A=Add, but the data value in Data Element 2 (Incident Number) will not match an incident already on file in the national UCR database. The segment will be processed, but used only for SRS purposes and will not be included in the agency’s NIBRS figures."), _661("661","Arrestee Segment","ARRESTEE SEQUENCE NUMBER ALREADY EXISTS","Segment Level 6 (Arrestee Segment) cannot contain duplicate data values in Data Element 40 (Arrestee Sequence Number) when two or more Arrestee Segments are submitted for the same incident."), _664("664","Arrestee Segment","ARRESTEE AGE MUST BE NUMERIC DIGITS","Data Element 47 (Age of Arrestee) does not contain a numeric entry of 00 through 99 for an exact age."), _665("665","Arrestee Segment","ARREST DATE CANNOT BE BEFORE THE INCIDENT START DATE","Data Element 42 (Arrest Date) cannot be earlier than Data Element 3 (Incident Date/Hour). A person cannot be arrested before the incident occurred."), _667("667","Arrestee Segment","INVALID ARRESTEE SEX VALUE","Data Element 48 (Sex of Arrestee) does not contain a valid code of M=Male or F=Female. Note: U=Unknown (if entered) is not a valid sex for an arrestee."), _669("669","Arrestee Segment","NO ARRESTEE RECORDS ALLOWED FOR A JUSTIFIABLE HOMICIDE","Group “A” Incident Reports cannot have arrests when Data Element 6 (UCR Offense Code) is 09C=Justifiable Homicide. By definition a justifiable homicide never involves an arrest of the offender (the person who committed the justifiable homicide)."), _670("670","Arrestee Segment","JUSTIFIABLE HOMICIDE CANNOT BE AN ARREST OFFENSE CODE","Data Element 45 (UCR Arrest Offense Code) was entered with 09C=Justifiable Homicide. This is not a valid arrest offense"), _701("701","Group B Arrest Segment","MUST BE POPULATED WITH A VALID DATA VALUE– MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _702("702","Group B Arrest Segment","CONTAINS NONNUMERIC ENTRY","Data Element 40 (Arrestee Sequence Number) must be numeric entry of 01 to 99 with zero left- fill."), _704("704","Group B Arrest Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _705("705","Group B Arrest Segment","INVALID ARREST DATE","Data Element 42 (Arrest Date) Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31 days). The date cannot exceed the current date. The date cannot be later than that entered within the Month of Electronic submission and Year of Electronic submission fields on the data record. For example, if Month of Electronic submission and Year of Electronic submission are 06/1999, the arrest date cannot contain any date 07/01/1999 or later."), _706("706","Group B Arrest Segment","ERROR - DUPLICATE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) cannot contain duplicate data values although more than one data value is allowed."), _707("707","Group B Arrest Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), _708("708","Group B Arrest Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) contains data, but is not left-justified. A single two-character age must be in positions 1 through 2 of the field."), _709("709","Group B Arrest Segment","CONTAINS NONNUMERIC ENTRY","Data Element 47 (Age of Arrestee) contains more than two characters indicating a possible age-range is being attempted. If so, the field must contain numeric entry of four digits."), _710("710","Group B Arrest Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 47 (Age of Arrestee) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _715("715","Group B Arrest Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _716("716","Group B Arrest Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Must be left-justified with blank right-fill if under 12 characters in length."), _717("717","Group B Arrest Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHENS, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _718("718","Group B Arrest Segment","AGENCY IS IN COVERED-BY STATUS","Data Element 42 (Arrest Date) cannot contain a date on or after the date a LEA is placed in Covered-by Status. When data are received for a LEA in Covered-by Status, the FBI will remove the agency from Covered-by Status, process the submission, and notify the agency. Additionally, adjustments to previously submitted data from an agency now in Covered-by Status will be processed and no error will be generated."), _720("720","Group B Arrest Segment","ARREST DATE CANNOT PREDATE BASE DATE","Group “B” Arrest Report (Level 7) submitted with a Segment Action Type of A=Add cannot have Data Element 42 (Arrest Date) earlier than the Base Date."), _722("722","Group B Arrest Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _740("740","Group B Arrest Segment","WARNING–NO DISPOSITION FOR POSSIBLE JUVENILE ARRESTEE","Data Element 52 (Disposition of Arrestee Under 18) was not entered, but Data Element 47 (Age of Arrestee) indicates an age-range for a juvenile. The low age is a juvenile and the high age is an adult, but the average age is a juvenile. Note: When an age-range is not entered and the age is a juvenile, the disposition must be entered. These circumstances were flagged by the computer as a possible discrepancy between age and disposition and should be checked for possible correction by the participant"), _741("741","Group B Arrest Segment","WARNING–ARRESTEE IS OVER AGE 98","Data Element 47 (Age of Arrestee) was entered with a value of 99, which means the arrestee is over 98 years old. The submitter should verify that 99=Over 98 Years Old is not being confused the with 00=Unknown."), _751("751","Group B Arrest Segment","ARRESTEE SEQUENCE NUMBER ALREADY EXISTS","When a Group “B” Arrest Report (Level 7) has two or more arrestees, the individual segments comprising the report cannot contain duplicates. In this case, two arrestee segments were submitted having the same entry in Data Element 40 (Arrestee Sequence Number)."), _752("752","Group B Arrest Segment","DISPOSITION MUST BE ENTERED WHEN AGE IS LESS THAN 18","Data Element 52 (Disposition of Juvenile) was not entered, but Data Element 47 (Age of Arrestee) is under 18. Whenever an arrestee’s age indicates a juvenile, the disposition must be entered."), _753("753","Group B Arrest Segment","FOR AGE GREATER THAN 17 DISPOSITION SHOULD NOT BE ENTERED","Data Element 52 (Disposition of Juvenile) was entered, but Data Element 47 (Age of Arrestee) is 18 or greater. Whenever an arrestee’s age indicates an adult, the juvenile disposition cannot be entered because it does not apply."), _754("754","Group B Arrest Segment","AUTOMATIC INDICATOR MUST BE BLANK OR “A”","Data Element 46 (Arrestee Was Armed With) does not have A=Automatic or a blank in the third position of field."), _755("755","Group B Arrest Segment","WEAPON TYPE MUST=11, 12, 13, 14, OR 15 FOR AN “A” IN THE AUTO INDICATOR","If Data Element 46 (Arrestee Was Armed With) weapon is an Automatic, add A as the third character of code; valid only with codes of: 11=Firearm (Type Not Stated) 12=Handgun 13=Rifle 14=Shotgun 15=Other Firearm A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm."), _757("757","Group B Arrest Segment","ARRESTEE AGE MUST BE NUMERIC DIGITS","Data Element 47 (Age of Arrestee) does not contain a numeric entry of 00 through 99 for an exact age."), _758("758","Group B Arrest Segment","INVALID ARRESTEE SEX VALUE","Data Element 48 (Sex of Arrestee) does not contain a valid code of M=Male or F=Female. Note that U=Unknown (if entered) is not a valid sex for an arrestee."), _759("759","Group B Arrest Segment","DUPLICATE GROUP “B” ARREST REPORT SEGMENT ON FILE","The Group “B” Arrest Report (Level 7) submitted as an Add is currently active in the FBI’s database; therefore, it was rejected. If multiple arrestees are involved in the incident, ensure that Data Element 40 (Arrestee Sequence Number) is unique for each Arrestee Segment submitted so that duplication does not occur."), _760("760","Group B Arrest Segment","LEVEL 7 ARRESTS MUST HAVE A GROUP “B” OFFENSE","Group “B” Arrest Reports (Level 7) must contain a Group “B” Offense Code in Data Element 45 (UCR Arrest Offense). The offense code submitted is not a Group “B” offense code."), _761("761","Group B Arrest Segment","ARRESTEE AGE MUST BE 01–17 FOR A RUNAWAY OFFENSE","Data Element 47 (Age of Arrestee) must be 01 through 17 for offense code of 90I=Runaway on a Group “B” Arrest Report."), _001("001","Zero Report Segment","MUST BE POPULATED WITH A VALID DATA VALUE– MANDATORY FIELD","Mandatory Data Elements (Mandatory=Yes) must be populated with a valid data value and cannot be blank."), _090_StructureCheck("090","Structure Check","ZERO-REPORTING MONTH IS NOT 01-12","A Segment Level 0 was submitted that had an invalid reporting month in positions 38 through 39. The data entered must be a valid month of 01 through 12."), _092_StructureCheck("092","Structure Check","ZERO-REPORTING INCIDENT NUMBER MUST BE ALL ZEROS","A Segment Level 0 was submitted, but the incident number entered into positions 26 through 37 was not all zeros."), _093_StructureCheck("093","Structure Check","ZERO-REPORTING MONTH/YEAR WAS PRIOR TO THE BASE DATE","A Segment Level 0 was submitted with a month and year entered into positions 38 through 43 that is earlier than January 1 of the previous year or before the date the agency converted over to NIBRS."), _094_StructureCheck("094","Structure Check","ZERO-REPORTING MONTH/YEAR EXCEEDED MONTH/YEAR OF ELECTRONIC SUBMISSION","A Segment Level 0 was submitted with a month and year entered into positions 38 through 43 that was later than the Month of Electronic submission and Year of Electronic submission entered into positions 7 through 12. Note: Error Numbers 001, 015, 016, and 017 are also Zero-Reporting segment errors."), _090_ZeroReport("090","Zero Report Segment","ZERO REPORT MONTH IS NOT 01–12","Zero Report Month must be a valid month, data values 01 through 12."), _092_ZeroReport("092","Zero Report Segment","ZERO REPORT INCIDENT NUMBER MUST BE ALL ZEROS","Data Element 2 (Incident Number) in the Zero Report Segment (Level 0) must contain 12 zeros."), _093_ZeroReport("093","Zero Report Segment","ZERO REPORT MONTH/YEAR IS PRIOR TO AGENCY CONVERSION TO THE NIBRS","Zero Report Month and Zero Report Year must be later than the month and year in the date the LEA converted to the NIBRS."), _094_ZeroReport("094","Zero Report Segment","ZERO REPORT MONTH/YEAR EXCEEDED MONTH/YEAR OF SUBMISSION","Zero Report Month and Zero Report Year must be earlier than Month of Submission and Year of Submission."); public String code; public String type; public String message; public String description; private NIBRSErrorCode(String code, String type, String message, String description) { this.code = code; this.type = type; this.message = message; this.description = description; } }
tools/nibrs-common/src/main/java/org/search/nibrs/model/codes/NIBRSErrorCode.java
/******************************************************************************* * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics * * 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.search.nibrs.model.codes; public enum NIBRSErrorCode { _015("015","Structure Check","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Zero-Reporting Segment (Level 0). Although Data Element 2 (Incident Number) should be entered with 12 zeros, a pre-edit found embedded blanks between the first and last significant characters."), _016("016","Structure Check","MUST BE LEFT-JUSTIFIED— BLANK DETECTED IN FIRST POSITION","Zero-Reporting Segment (Level 0). Although Data Element 2 (Incident Number) should be entered with 12 zeros, a pre-edit found a blank in the first position. It must begin in position 1 and must also contain 12 zeros."), _017("017","Structure Check","CANNOT HAVE CHARACTERS OTHER THAN A-Z, 0-9, HYPHENS, AND/OR BLANKS","Zero-Reporting Segment (Level 0). Although Data Element 2 (Incident Number) should be entered with 12 zeros, a pre-edit discovered characters other than A through Z, 0 through 9, hyphens, and/or blanks had been entered."), _050("050","Structure Check","SEGMENT LEVELS ARE OUT OF NUMERICAL ORDER FOR THIS INCIDENT","Segment Levels in a Group A Incident Report must be organized in numerical order. For example, an incident having segments 1, 2, 2, 3, 4, 4, 4, 5 must be written in that order, not as 1, 2, 2, 5, 3, 4, 4, 4."), _051("051","Structure Check","INVALID RECORD LEVEL ON SUBMISSION","Segment Level must contain data values 0–7."), _052("052","Structure Check","NOT A VALID ORI–NOT IN UCR ORI FILE","Data Element 1 (ORI) and Data Element 25C (Officer–ORI Other Jurisdiction) must be a valid nine-character NCIC ORI."), _055("055","Structure Check","CANNOT HAVE A GROUP A INCIDENT REPORT WITHOUT LEVEL 1 SEGMENT","Segment Level 1 (Administrative Segment) with Segment Action Type I=Incident Report must be the first segment submitted for each Group A Incident Report."), _056("056","Structure Check","DUPLICATE INCIDENT– PREVIOUSLY ADDED","Data Element 2 (Incident Number) must be a unique number for each incident submitted. No two incidents can have the same incident number."), _058("058","Structure Check","ALL SEGMENTS IN A SUBMISSION MUST HAVE SAME MONTH AND YEAR OF SUBMISSION","Month of Submission and Year of Submission must contain the same data values for each segment in a NIBRS submission. The first segment processed will be compared with all other segments to check for this condition."), _059("059","Structure Check","ALL SEGMENTS IN SUBMISSION MUST BE FROM SAME STATE","Data Element 1 (ORI) must contain the same state abbreviation code (e.g., SC, MD, etc.) in the first two positions (record positions 17 & 18). For nonfederal LEAs, every segment in a submission must have the same state code in the first two positions of the ORI."), _060("060","Structure Check","PROCESSING DATE PRECEDES MONTH AND YEAR OF SUBMISSION","Month of Submission and Year of Submission must precede the date the FBI receives and processes a NIBRS submission. This edit checks for data submitted for a future month/year."), _065("065","Structure Check","EACH LEVEL 2 OFFENSE MUST HAVE AT LEAST ONE VICTIM","Segment Level 2 (Offense Segment) must have at least one Segment Level 4 (Victim Segment) connected to it by entering the offense code identified in Data Element 6 (UCR Offense Code) in Data Element 24 (Victim Connected to UCR Offense Code)."), _070("070","Structure Check","THE CORRESPONDING OFFENDER RECORD MUST BE PRESENT","Data Element 34 (Offender Numbers To Be Related) has a value that does not have a corresponding Offender Segment. For example, if the field value shown in Data Element 34 is 15, an Offender Segment does not exist with a value of 15 in Data Element 36 (Offender Sequence Number)."), _071("071","Structure Check","CANNOT HAVE ARRESTS WHEN CLEARED EXCEPTIONALLY","Segment Level 6 (Arrestee Segment) with Segment Action Type I=Incident Report cannot be submitted with Data Element 42 (Arrest Date) containing an arrest date on or earlier than the date entered in Data Element 5 (Exceptional Clearance Date) when Data Element 4 (Cleared Exceptionally) contains a data value other than N=Not Applicable (indicating the incident is cleared exceptionally)."), _072("072","Structure Check","RECOVERED PROPERTY MUST FIRST BE REPORTED AS STOLEN","Segment Level 3 (Property Segment) must first be submitted with Data Element 14 (Type Property Loss/Etc.) as 7=Stolen/Etc. before it can be submitted as 5=Recovered for the same property in Data Element 15 (Property Description). Any property being reported as recovered must first be reported as stolen. There are three exceptions to this rule: 1) When recovered property information is submitted as Segment Action Type A=Add and Data Element 2 (Incident Number) is not on file in the national UCR database. This condition may indicate recovered property is being reported for a pre-NIBRS incident; therefore, the stolen property information will not be on file in the national database. 2) When Data Element 6 (UCR Offense Code) contains an offense that allows property to be recovered without first being stolen in that same incident (i.e., 250=Counterfeiting/Forgery and 280=Stolen Property Offenses) 3) When a vehicle was stolen and the recovered property in Data Element 15 (Property Description) is 38=Vehicle Parts/Accessories"), _073("073","Structure Check","NUMBER OF RECOVERED VEHICLES CANNOT BE GREATER THAN THE NUMBER STOLEN","Segment Level 3 (Property Segment) with Segment Action Type I=Incident Report must contain a data value in Data Element 18 (Number of Stolen Motor Vehicles) greater than or equal to the data value entered in Data Element 19 (Number of Recovered Motor Vehicles) within the same incident."), _074("074","Structure Check","PROPERTY SEGMENT MUST EXIST WITH THIS OFFENSE","Segment Level 3 (Property Segment) with Segment Action Type I=Incident Report must be submitted when Data Element 6 (UCR Offense Code) contains an offense of Kidnapping/Abduction , Crimes Against Property, Drug/Narcotic Offenses, or Gambling Offenses."), _075("075","Structure Check","MISSING A MANDATORY SEGMENT LEVEL FOR A COMPLETE INCIDENT","Segment Levels 1, 2, 4, and 5 (Administrative Segment, Offense Segment, Victim Segment, and Offender Segment) with Segment Action Type I=Incident Report must be submitted for each Group A Incident Report; they are mandatory."), _076("076","Structure Check","PROPERTY RECORD (LEVEL 3) CAN NOT EXIST WITH OFFENSES SUBMITTED","Segment Level 3 (Property Segment) with Segment Action Type I=Incident Report cannot be submitted unless Data Element 6 (UCR Offense Code) contains an offense of Kidnapping/Abduction, Crimes Against Property, Drug/Narcotic Offenses, or Gambling Offenses."), _077("077","Structure Check","NEED A PROPERTY LOSS CODE OF 1 OR 8 WHEN THIS OFFENSE IS ATTEMPTED","Data Element 7 (Offense Attempted/Completed) is A=Attempted and Data Element 6 (UCR Offense Code) is a Crime Against Property, Gambling, Kidnapping, or Drug/Narcotic Offense. However, there is no Data Element 14 (Type Property Loss/Etc.) of 1=None or 8=Unknown."), _078("078","Structure Check","A VALID PROPERTY LOSS CODE DOES NOT EXIST FOR THIS COMPLETED OFFENSE","If Data Element 6 (UCR Offense Code) is a Crime Against Property, Kidnaping, Gambling, or Drug/Narcotic Offense, and Data Element 7 (Offense Attempted/Completed) is C=Completed, a Property Segment (Level 3) must be sent with a valid code in Data Element 14 (Type Property Loss/Etc.)."), _080("080","Structure Check","CRIMES AGAINST SOCIETY CAN HAVE ONLY ONE SOCIETY/PUBLIC VICTIM","Segment Level 4 (Victim Segment) can be submitted only once and Data Element 25 (Type of Victim) must be S=Society/Public when Data Element 6 (UCR Offense Code) contains only a Crime Against Society."), _081("081","Structure Check","TYPE PROPERTY LOSS CODE IS NOT VALID WITH THE OFFENSES SUBMITTED","Data Element 14 (Type Property Loss/Etc.) must be 1=None or 8=Unknown when Data Element 6 (UCR Offense Code) contains an offense of Kidnapping/Abduction, Crimes against Property, Drug/Narcotic Offenses, or Gambling Offenses and Data Element 7 (Offense Attempted/Completed) is A=Attempted. Data Element 14 (Type Property Loss/Etc.) must be 1=None or 5=Recovered when Data Element 6 (UCR Offense Code) is 280=Stolen Property Offenses and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 1=None, 5=Recovered, 7=Stolen/Etc., or 8=Unknown when Data Element 6 (UCR Offense Code) is 100=Kidnapping/Abduction, 220=Burglary/ Breaking & Entering, or 510=Bribery and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 1=None or 6=Seized when Data Element 6 (UCR Offense Code) is 35A=Drug/ Narcotic Violations or 35B=Drug Equipment Violations and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 2=Burned when Data Element 6 (UCR Offense Code) is 200=Arson and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 3=Counterfeited/Forged, 5=Recovered, or 6=Seized when Data Element 6 (UCR Offense Code) is 250=Counterfeiting/Forgery and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 4=Destroyed/Damaged/Vandalized when Data Element 6 (UCR Offense Code) is 290=Destruction/Damage/Vandalism of Property and Data Element 7 (Offense Attempted/Completed) is C=Completed. Data Element 14 (Type Property Loss/Etc.) must be 5=Recovered or 7=Stolen/Etc. when Data Element 6 (UCR Offense Code) is any of the following and Data Element 7 (Offense Attempted/Completed) is C=Completed: 120=Robbery 210=Extortion/Blackmail 23A=Pocket-picking 23B=Purse Snatching 23C=Shoplifting 23D=Theft from Building 23E=Theft from Coin-Operated Machine or Device 23F=Theft from Motor Vehicle 23G=Theft of Motor Vehicle Parts or Accessories 23H=All other Larceny 240=Motor Vehicle Theft 26A=False Pretenses/Swindle/Confidence Game 26B=Credit Card/Automated Teller Machine Fraud 26C=Impersonation 26D=Welfare Fraud 26E=Wire Fraud270=Embezzlement Data Element 14 (Type Property Loss/Etc.) must be 6=Seized when Data Element 6 (UCR Offense Code) is any of the following and Data Element 7 (Offense Attempted/Completed) is C=Completed: 39A=Betting/W agering 39B=Operating/Promoting/Assisting Gambling 39C=Gambling Equipment Violation 39D=Sports Tampering"), _084("084","Structure Check","RECOVERED PROPERTY VALUE CANNOT BE GREATER THAN THE VALUE WHEN STOLEN","Data Element 16 (Value of Property) for property classified as 7=Stolen/Etc. in Data Element 14 (Type Property Loss/Etc.) must be greater than or equal to the value entered in Data Element 16 (Value of Property) for property classified as 5=Recovered for the same property specified in Data Element 15 (Property Description) in an incident. Note: This edit also applies when a vehicle was stolen and the recovered property in Data Element 15 (Property Description) is 38=Vehicle Parts/Accessories. The value of recovered parts cannot exceed the value of stolen vehicles."), _085("085","Structure Check","EACH VICTIM MUST BE CONNECTED TO AT LEAST TWO OFFENDERS","Segment Level 4 (Victim Segment) with a data value in Data Element 24 (Victim Connected to UCR Offense Code) of a Crime Against Person or Robbery must contain at least two offender sequence numbers in Data Element 34 (Offender Number to be Related) when there are three or more Segment Level 5 (Offender Segment) records submitted for the incident."), _088("088","Structure Check","GROUP A AND GROUP B ARREST REPORTS CANNOT HAVE SAME IDENTIFIER","Segment Level 6 (Arrestee Segment) and Segment Level 7 (Group B Arrest Report Segment) cannot have the same data values entered in Data Element 2 (Incident Number) and Data Element 41 (Arrest Transaction Number), respectively, for the same ORI."), _091("091","Structure Check","ZERO-REPORTING YEAR IS INVALID","A Segment Level 0 was submitted that did not have four numeric digits in positions 40 through 43."), _101("101","Admin Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _104("104","Admin Segment","INVALID DATA VALUE—NOT ON FBI VALIDATION TABLE","The referenced data element must contain a valid data value when it is entered."), _105("105","Admin Segment","INVALID DATA VALUE FOR DATE","The data element in error contains a date that is not entered correctly. Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31days). Also, the date cannot exceed the current date."), _115("115","Admin Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","(Incident Number) Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _116("116","Admin Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","(Incident Number) must be left-justified with blank right-fill. Since the number is less than 12 characters, it must begin in position 1"), _117("117","Admin Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","(Incident Number) can only have character combinations of A through Z, 0 through 9, hyphens, and/or blanks. For example, 89-123-SC is valid, but 89+123*SC is invalid."), _118("118","Admin Segment","DATE CANNOT BE ON OR AFTER THE INACTIVE DATE [yyyymmdd] OF THE ORI","The UCR Program has determined that an ORI will no longer be submitting data to the FBI as of an inactive date. No data from this ORI will be accepted after this date."), _119("119","Admin Segment","CARGO THEFT DATA CAN ONLY BE SUBMITTED FOR SPECIFIC OFFENSES","Data Element 2A (Cargo Theft) must be populated with a valid data value when Data Element 6 (UCR Offense Code) contains a Cargo Theft- related offense."), _122("122","Admin Segment","INCIDENT MUST INCLUDE AT LEAST ONE CARGO THEFT OFFENSE","Data Element 2A (Cargo Theft) can be Y=Yes only when Data Element 6 (UCR Offense Code) includes at least one of the following: 120=Robbery 210=Extortion/Blackmail 220=Burglary/Breaking & Entering 23D=Theft From Building 23F=Theft From Motor Vehicle 24H=All Other Larceny 240=Motor Vehicle Theft 26A=False Pretenses/Swindle/Confidence Game 26B=Credit Card/Automated Teller Machine Fraud 26C=Impersonation 26E=Wire Fraud 270=Embezzlement 510=Bribery"), _151("151","Admin Segment","REPORT INDICATOR MUST BE BLANK OR “R”","This field must be blank if the incident date is known. If the incident date is unknown, then the report date would be entered instead and must be indicated with an “R” in the Report Indicator field within the Administrative Segment."), _152("152","Admin Segment","INVALID HOUR ENTRY","If Hour is entered within Data Element 3 (Incident Date/Hour), it must be 00 through 23. If 00=Midnight is entered, be careful that the Incident Date is entered as if the time was 1 minute past midnight. Note: When an incident occurs exactly at midnight, Data Element 3 (Incident Date) would be entered as if the time is 1 minute past midnight. For example, when a crime occurred exactly at midnight on Thursday, Friday’s date would be entered."), _153("153","Admin Segment","VALUE ENTERED CONFLICTS WITH PRESENCE OF AN ENTRY IN EXCEPTIONAL CLEARANCE DATE","Data Element 4 (Cleared Exceptionally) cannot be N=Not Applicable if Data Element 5 (Exceptional Clearance Date) is entered."), _155("155","Admin Segment","CLEARANCE DATE [yyyymmdd] PREDATES INCIDENT DATE [yyyymmdd]","Data Element 5 (Exceptional Clearance Date) is earlier than Data Element 3 (Incident Date/Hour)."), _156("156","Admin Segment","AN ENTRY MUST BE MADE WHEN CLEARED EXCEPTIONALLY HAS ENTRIES OF A-E","Data Element 5 (Exceptional Clearance Date) must be present if the case was cleared exceptionally. Data Element 4 (Cleared Exceptionally) has an entry of A through E; therefore, the date must also be entered."), _170("170","Admin Segment","INCIDENT DATE CANNOT BE AFTER YEAR [yyyy] AND MONTH [mm] OF ELECTRONIC SUBMISSION","Data Element 3 The date cannot be later than the year and month the electronic submission represents. For example, the May 1999 electronic submission cannot contain incidents happening after this date."), _171("171","Admin Segment","INCIDENT DATE IS OUTSIDE THE BASE DATE CALCULATION","A Group “A” Incident Report was submitted with a date entered into Data Element 3 (Incident Date/Hour) that is earlier than January 1 of the previous year, using the Month of Tape and Year of Tape as a reference point. For example, if the Month of Tape and Year of Tape contain a value of 01/1999, but the incident date is 12/25/1997, the incident will be rejected. Volume 2, section I, provides specifications concerning the FBI’s 2- year database. Note: The exception is when an exceptional clearance is being submitted with a Segment Action Type of W=Time-Window Submission. The incident date may be any past date, but cannot be any earlier than January 1, 1950."), _172("172","Admin Segment","INCIDENT DATE/HOUR FOR “I” RECORDS CANNOT PREDATE 01/01/1991","Data Element 3 (Incident Date) cannot be earlier than 01/01/1991. This edit will preclude dates that are obviously incorrect since the FBI began accepting NIBRS data on this date."), _173("173","Admin Segment","INCIDENT DATE CANNOT BE BEFORE DATE ORI WENT IBR","A Group “A” Incident Report was submitted with Data Element 3 (Incident Date/Hour) containing a date that occurred before the agency converted over to NIBRS. Because of this, the record was rejected. At some point, the participant will convert its local agencies from Summary reporting to Incident-Based Reporting. Once the participant starts to send NIBRS data for a converted agency to the FBI, any data received from this agency that could possibly be interpreted as duplicate reporting within both the Summary System and NIBRS for the same month will be rejected by the FBI. In other words, if the participant sends IBR data for an agency for the first time on September 1999, monthly submittal, dates for incidents, recovered property, and arrests must be within September. The exception is when exceptional clearances occur for a pre-IBR incident. In this case, Data Element 3 (Incident Date/Hour) may be earlier than September 1999, but Data Element 5 (Exceptional Clearance Date) must be within September 1999. The FBI will reject data submitted for prior months. Thereafter, all data coming from this agency must have dates subsequent to the initial start date of September 1999, except as mentioned previously. The Summary System already contains aggregate data for the months prior to NIBRS conversion. If the FBI were to accept IBR data for months previously reported with Summary data, the result would be duplicate reporting for those months."), _175("175","Admin Segment","CANNOT CALCULATE BASE DATE FROM INCIDENT DATE [yyymmdd]","The electronic submission control date (positions 7 through 12, month and year) and Data Element 3 (Incident Date/Hour) must both be valid dates for calculating timeframes."), _178("178","Admin Segment","THIS ADMINISTRATIVE SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Administrative Segment (Level 1) must be 87 characters (not reporting Cargo Theft) or 88 characters (reporting Cargo Theft). All Administrative Segments in a submission must be formatted in only one of these two lengths."), _201("201","Offense Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _202("202","Offense Segment","CONTAINS NONNUMERIC ENTRY","Data Element 10 (Number of Premises Entered) is not a numeric entry of 01 through 99."), _204("204","Offense Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _205("205","Offense Segment","ERROR–INVALID OFFENSE CODE","Data Element 9 (Location Type) Can only be entered when Data Element 6 Offense Code is one of the violations listed below: 210=Extortion/Blackmail 250=Counterfeiting/Forgery 270=Embezzlement 280=Stolen Property Offenses 290=Destruction/Damage/Vandalism of Property 370=Pornography/Obscene Material 510=Bribery 26A =False Pretenses/Swindle/Confidence Game 26B =Credit Card/Automated Teller Machine Fraud 26C =Impersonation 26D =Welfare Fraud 26E =Wire Fraud 26F =Identity Theft 26G =Hacking/Computer Invasion 9A =Betting/Wagering 39B =Operating/Promoting/Assisting Gambling 39D =Gambling Equipment Violations 13C =Intimidation 35A =Drug/Narcotic Violations 35B =Drug Equipment Violations 520=Weapon Law Violations 64A =Human Trafficking, Commercial Sex Acts 64B =Human Trafficking, Involuntary Servitude 40A =Prostitution 40B =Assisting or Promoting Prostitution 40C =Purchasing Prostitution"), _206("206","Offense Segment","ERROR - DUPLICATE VALUE=[value]","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), _207("207","Offense Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","The data element in error can have multiple data values and was entered with multiple values. However, the entry shown cannot be entered with any other data value. Value N=None/Unknown is mutually exclusive with any other information codes."), _215("215","Offense Segment","CANNOT CONTAIN EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _216("216","Offense Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Must be left-justified with blank right-fill if under 12 characters in length."), _217("217","Offense Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _219("219","Offense Segment","DATA CAN ONLY BE ENTERED FOR SPECIFIC OFFENSES","Data Element 12 (Type Criminal Activity/Gang Information) Type criminal activity codes of “B”, “C”, “D”, “E”, “O”, “P”, “T”, or “U” can only be entered when the UCR Offense Code is: 250=Counterfeiting/Forgery 280=Stolen Property Offenses 35A=Drug/Narcotic Violations 35B=Drug Equipment Violations 39C=Gambling Equipment Violations 370=Pornography/Obscene Material 520=Weapon Law Violations (Type Criminal Activity/Gang Information) Gang information codes of “J”, “G”, and “N” can only be entered when the UCR Offense Code is:09A=Murder and Non-negligent Manslaughter 09B=Negligent Manslaughter 100=Kidnapping/Abduction 11A=Rape 11B=Sodomy 11C=Sexual Assault With An Object 11D=Fondling 120=Robbery 13A=Aggravated Assault 13B=Simple Assault 13C=Intimidation (Type Criminal Activity/Gang Information) Criminal Activity codes of “A”, “F”, “I”, and “S” can only be entered when the UCR Offense Code is: 720=Animal Cruelty"), _220("220","Offense Segment","DATA MUST BE ENTERED FOR SPECIFIC OFFENSES","Data Element 12 (Type Criminal Activity/Gang Information) Must be populated with a valid data value and cannot be blank when Data Element 6 (UCR Offense Code) is: 250=Counterfeiting/Forgery 280=Stolen Property Offenses 35A=Drug/Narcotic Violations 35B=Drug Equipment Violations 39C=Gambling Equipment Violations 370=Pornography/Obscene Material 520=Weapon Law Violations 720=Animal Cruelty"), _221("221","Offense Segment","DATA MUST BE ENTERED FOR SPECIFIC OFFENSES","Data Element 13 (Type Weapon/Force Involved) must be populated with a valid data value and cannot be blank when Data Element 6 (UCR Offense Code) is: 09A=Murder and Non-negligent Manslaughter 09B=Negligent Manslaughter 09C=Justifiable Homicide 100=Kidnapping/Abduction 11A=Rape 11B=Sodomy 11C=Sexual Assault With An Object 11D=Fondling 120=Robbery 13A=Aggravated Assault 13B=Simple Assault 210=Extortion/Blackmail 520=Weapon Law Violations 64A=Human Trafficking, Commercial Sex Acts 64B=Human Trafficking, Involuntary Servitude"), _251("251","Offense Segment","INVALID CODE","(Offense Attempted/Completed) Must be a valid code of A=Attempted or C=Completed."), _252("252","Offense Segment","OFFENSE CODE MUST BE 220 WITH A LOCATION TYPE OF 14 OR 19 FOR DATA TO BE ENTERED","When Data Element 10 (Number of Premises Entered) is entered, Data Element 9 (Location Type) must be 14=Hotel/Motel/Etc. or 19=Rental Storage Facility, and Data Element 6 (UCR Offense Code) must be 220 (Burglary)."), _253("253","Offense Segment","MUST BE PRESENT WHEN OFFENSE CODE IS 220","Data Element was not entered; it must be entered when UCR Offense Code of 220=Burglary has been entered."), _254("254","Offense Segment","MUST BE BLANK WHEN OFFENSE IS OTHER THAN 220","Data Element only applies to UCR Offense Code of 220=Burglary. Since a burglary offense was not entered, the Method of Entry should not have been entered."), _255("255","Offense Segment","AUTOMATIC INDICATOR MUST BE BLANK OR “A”","Must be A=Automatic or blank=Not Automatic"), _256("256","Offense Segment","OFFENSE CODES OF 09A, 09B, 09C, 13A, 13B, AND 13C MUST HAVE ENTRY OF “C”","Code must be C=Completed if Data Element 6 (UCR Offense Code) is an Assault or Homicide."), _257("257","Offense Segment","MUST BE PRESENT WITH AN OFFENSE CODE OF 220 AND A LOCATION TYPE OF 14 OR 19","Must be entered if offense code is 220 (Burglary) and if Data Element 9 (Location Type) contains 14=Hotel/Motel/Etc. or 19=Rental Storage Facility."), _258("258","Offense Segment","WEAPON TYPE MUST=11, 12, 13, 14, OR 15 FOR AN “A” IN THE AUTO INDICATOR","In Data Element 13 (Type of Weapon/Force Involved), A=Automatic is the third character of code. It is valid only with the following codes: 11=Firearm (Type Not Stated) 12=Handgun 13=Rifle 14=Shotgun 15=Other Firearm A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm."), _262("262","Offense Segment","DUPLICATE OFFENSE SEGMENT","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. In this case, two Offense Segments were submitted having the same offense in Data Element 6 (UCR Offense Code)."), _263("263","Offense Segment","CANNOT HAVE MORE THAN 10 OFFENSES","Can be submitted only 10 times for each Group A Incident Report; 10 offense codes are allowed for each incident."), _264("264","Offense Segment","GROUP “A” OFFENSE CANNOT CONTAIN A GROUP “B” OFFENSE","Data Element 6 (UCR Offense Code) must be a Group “A” UCR Offense Code, not a Group “B” Offense Code."), _265("265","Offense Segment","INVALID WEAPON [weapon-code] WITH AN OFFENSE OF 13B","If an Offense Segment (Level 2) was submitted for 13B=Simple Assault, Data Element 13 (Type Weapon/Force Involved) can only have codes of 40=Personal Weapons, 90=Other, 95=Unknown, and 99=None. All other codes are not valid because they do not relate to a simple assault."), _266("266","Offense Segment","NO OTHER OFFENSE CAN BE SUBMITTED WITH AN 09C OFFENSE","When a Justifiable Homicide is reported, no other offense may be reported in the Group “A” Incident Report. These should be submitted on another Group “A” Incident Report."), _267("267","Offense Segment","INVALID WEAPON [weapon-code] WITH AN OFFENSE OF [offense]","If a homicide offense is submitted, Data Element 13 (Type Weapon/Force Involved) cannot have 99=None. Some type of weapon/force must be used in a homicide offense."), _268("268","Offense Segment","LARCENY OFFENSE CANNOT HAVE A MOTOR VEHICLE PROPERTY DESCRIPTION ENTERED","Cannot be submitted with a data value for a motor vehicle in Data Element 15 (Property Description) when Data Element 6 (UCR Offense Code) contains an offense of (23A–23H)=Larceny/Theft Offenses; stolen vehicles cannot be reported for a larceny"), _269("269","Offense Segment","POSSIBLE CLASSIFICATION ERROR OF AGGRAVATED ASSAULT 13A CODED AS SIMPLE 13B","If Data Element 6 (UCR Offense Code) is 13B=Simple Assault and the weapon involved is 11=Firearm, 12=Handgun, 13=Rifle, 14=Shotgun, or 15=Other Firearm, then the offense should instead be classified as 13A=Aggravated Assault."), _270("270","Offense Segment","JUSTIFIABLE HOMICIDE MUST BE CODED AS NON-BIAS MOTIVATED","Must be 88=None when Data Element 6 (UCR Offense Code) is 09C=Justifiable Homicide."), _284("284","Offense Segment","THIS OFFENSE SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Offense Segment (Level 2) must be 63 characters (reporting only Bias Motivation #1) or 71 characters (reporting Bias Motivations #2–#5). All Offense Segments in a submission must be formatted in only one of these two lengths."), _301("301","Property Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _302("302","Property Segment","CONTAINS NONNUMERIC ENTRY","Must be numeric entry with zero left-fill. If Data Element 21 (Estimated Quantity) has the error, note that any decimal fractional quantity must be expressed in thousandths as three numeric digits. If no fractional quantity was involved, then all zeros should be entered."), _304("304","Property Segment","INVALID DATA VALUE—NOT ON FBI VALIDATION TABLE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _305("305","Property Segment","DATE RECOVERED IS INVALID","Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31 days). The date cannot be later than that entered within the Month of Electronic Submission and Year of Electronic submission fields on the data record. For example, if Month of Electronic Submission and Year of Electronic Submission are 06/1999, the recovered date cannot contain any date 07/01/1999 or later. Cannot be earlier than Data Element 3 (Incident Date/Hour)."), _306("306","Property Segment","ERROR–DUPLICATE DATA VALUE","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes. There are two exceptions to this rule: 1) When a data value is entered in both Drug Type 1 and Drug Type 2, but different measurement categories are entered in Data Element 22 (Type Drug Measurement); this is allowed. For example, when A=Crack Cocaine is entered in Drug Type 1 and it is also entered in Drug Type 2, Data Element 22 (Type Drug Measurement) must be two different measurement categories (i.e., grams and liters) and not grams and pounds (same weight category). 2) When the data value is U=Unknown; it can be entered only once."), _315("315","Property Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Data Element 2 (Incident Number) Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _316("316","Property Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Data Element 2 (Incident Number) Must be left- justified with blank right-fill if under 12 characters in length."), _317("317","Property Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _320("320","Property Segment","RECOVERED DATE PREDATES STOLEN DATE","The date property is recovered cannot be before the date it is stolen"), _342("342","Property Segment","WARNING - PROPERTY DESC(15) HAD VALUE (16) THAT EXCEEDED THRESHOLD OF [$ value]","When referenced data element contains a value that exceeds an FBI-assigned threshold amount, a warning message will be created. The participant is asked to check to see if the value entered was a data entry error, or if it was intended to be entered. A warning message is always produced when the value is $1,000,000 or greater. For example, if the value of a property is $12,000.99 but is inadvertently entered as $1,200,099 in the computer record sent to the FBI, a warning message will be generated. In this case, the cents were entered as whole dollars."), _343("343","Property Segment","WARNING - 280 OFFENSE HAS RECOVERED VEHICLE BUT 240 DOESN'T SHOW STOLEN","This is a warning message only. This warning is generated when a 280 Stolen Property Offense and a 240 Motor Vehicle Theft are submitted that contain questionable property reporting. When the incident contains a recovered vehicle but does not also have a stolen vehicle, this warning message is created. The incident should be reviewed and if there was indeed a stolen vehicle, the incident should be resubmitted reflecting both stolen and recovered vehicles."), _351("351","Property Segment","PROPERTY VALUE OF ZERO IS NOT ALLOWED","Data Element 16 (Value of Property) Cannot be zero unless Data Element 15 (Property Description) is: Mandatory zero 09=Credit/Debit Cards 22=Nonnegotiable Instruments 48=Documents–Personal or Business 65=Identity Documents 66=Identity–Intangible Optional zero 77=Other 99=(blank)–this data value is not currently used by the FBI.by the FBI"), _352("352","Property Segment","DATA ELEMENTS 15 - 22 MUST BE BLANK WHEN PROPERTY LOSS CODE=1 OR 8","When this error occurs, data were found in one or more of the referenced data elements. These data elements must be blank based on other data element values that prohibit data being entered in these data elements. For example, if Data Element 14 (Type property Loss/Etc.) is 8=Unknown, Data Elements 15 through 22 must be blank. If it is 1=None and offense is 35A, then Data Elements 15 through 19 and 21 through 22 must be blank. If it is 1=None and offense is not 35A, then Data Elements 15 through 22 must be blank. The exception to this rule is when Data Element 6 (UCR Offense Code) is 35A=Drug/ Narcotic Violations and Data Element 14 (Type Property Loss/Etc.) is 1=None; Data Element 20 (Suspected Drug Type) must be entered."), _353("353","Property Segment","PENDING INVENTORY MUST HAVE PROPERTY VALUE OF 1","Data Element 15 (Property Description) is 88=Pending Inventory, but Data Element 16 (Value of Property) is not $1. Determine which of the data elements was entered incorrectly."), _354("354","Property Segment","DATA ELEMENT 15 WAS NOT ENTERED, BUT VALUE ($) WAS","Data Element 16 (Value of Property) contains a value, but Data Element 15 (Property Description) was not entered."), _355("355","Property Segment","PROPERTY LOSS CODE (14) MUST=5 (RECOVERED) FOR DATA TO BE ENTERED","Data Element 14 (Type Property Loss/Etc.) must be 5=Recovered for Data Element 17 (Date Recovered) to be entered."), _356("356","Property Segment","PROPERTY DESCRIPTION (15) AND VALUE (16) MUST BOTH EXIST IF DATA ARE PRESENT","Data Element 17 (Date Recovered) was entered, but Data Elements 15 (Property Description) and/or 16 (Property Value) were not entered."), _357("357","Property Segment","PROPERTY LOSS (14) MUST BE 7 WITH AN OFFENSE CODE OF 240 FOR DATA TO BE ENTERED","Data Element 18 (Number of Stolen Motor Vehicles) was entered. However, Data Element 14 (Type Property Loss/Etc.) 7=Stolen/Etc. was not entered, and/or Data Element 6 (UCR Offense Code) of 240=Motor Vehicle Theft was not entered, and/or Data Element 7 (Offense Attempted/Completed) was A=Attempted."), _358("358","Property Segment","DATA MUST EXIST WITH AN OFFENSE CODE OF 240 AND A PROPERTY","LOSS OF 7 Entry must be made for Data Element 18 (Number of Stolen Motor Vehicles) when Data Element 6 (UCR Offense Code) is 240=Motor Vehicle Theft, Data Element 7 (Offense Attempted/Completed) is C=Completed, and Data Element 14 (Type Property Loss/Etc.) is 7=Stolen/Etc."), _359("359","Property Segment","ALL NONVEHICULAR PROPERTY DESCRIPTIONS WERE ENTERED","Must be one of the following when Data Element 18 (Number of Stolen Motor Vehicles) or Data Element 19 (Number of Recovered Motor Vehicles) contain a data value other than 00=Unknown: 03=Automobiles 05=Buses 24=Other Motor Vehicles 28=Recreational Vehicles 37=Trucks"), _360("360","Property Segment","PROPERTY LOSS (14) MUST BE 5 WITH AN OFFENSE CODE OF 240 FOR DATA TO BE ENTERED","Data Element 19 (Number of Recovered Motor Vehicles) was entered. However, Data Element 14 (Type Property Loss/Etc.) 5=Recovered was not entered, and/or Data Element 6 (UCR Offense Code) of 240=Motor Vehicle Theft was not entered, and/or Data Element 7 (Offense Attempted/Completed) was A=Attempted. The exception to this rule is when recovered property is reported for a pre-NIBRS incident. In this case, Segment Level 3 (Property Segment) will contain A=Add, but the data value in Data Element 2 (Incident Number) will not match an incident already on file in the national UCR database. The segment will be processed, but used only for SRS purposes and will not be included in the agency’s NIBRS figures."), _361("361","Property Segment","DATA MUST EXIST WITH AN OFFENSE CODE OF 240 AND A PROPERTYLOSS OF 5","Entry must be made when Data Element 6 (UCR Offense Code) is 240=Motor Vehicle Theft, Data Element 14 (Type Property Loss/Etc.) is 5=Recovered, and Data Element 15 (Property Description) contains a vehicle code."), _362("362","Property Segment","TWO OTHER CODES MUST BE ENTERED WHEN AN “X” IS PRESENT","Since X=Over 3 Drug Types was entered in Data Element 20 (Suspected Drug Type), two other codes must also be entered. There are less than three codes present."), _363("363","Property Segment","WITH A CODE OF “X” BOTH QUANTITY (21) AND MEASUREMENT (22) MUST BE BLANK","Since Data Element 20 (Suspected Drug Type) contains X=Over 3 Drug Types, Data Element 21 (Estimated Quantity) and 22 (Type Measurement) must be blank"), _364("364","Property Segment","WITH DATA ENTERED BOTH QUANTITY (21) AND MEASUREMENT (22) MUST BE PRESENT","When Data Element 6 (UCR Offense Code) is 35A=Drug/Narcotic Violations, 14 (Type Property Loss/Etc.) is 6=Seized, 15 (Type Property Loss/Etc.) is 10=Drugs, and Data Element 20 (Suspected Drug Type) is entered, both Data Element 21 (Estimated Quantity) and 22 (Type Measurement) must also be entered."), _365("365","Property Segment","OFFENSE=35A AND PROPERTY LOSS=6 AND DESCRIPTION=10 MUST EXIST","Data Element 20 (Suspected Drug Type) was entered, but one or more required data elements were not entered. Data Element 6 (UCR Offense Code) must be 35A=Drug/Narcotic Violations, Data Element 14 (Type Property Loss/Etc.) must be 6=Seized, and Data Element 15 (Property Description) must be 10=Drugs/Narcotics. There could be multiple underlying reasons causing this error to be detected. One of them might be that Data Element 20 (Suspected Drug Type) was entered by mistake. Perhaps the code entered in Data Element 15 (Property Description) should have been 01=Aircraft, but by entering the code as 10=Drugs/Narcotics, someone thought that Data Element 20 must be entered, etc."), _366("366","Property Segment","WITH DATA ENTERED BOTH TYPE (20) AND MEASUREMENT (22) MUST BE PRESENT","Data Element 21 (Estimated Quantity) was entered, but 20 (Suspected Drug Type) and/or 22 (Type Measurement) were not entered; both must be entered."), _367("367","Property Segment","DRUG TYPE MUST BE “E”, “G”, OR “K” FOR A VALUE OF “NP”","Data Element 22 (Type Measurement) was entered with NP in combination with an illogical drug type. Based upon the various ways a drug can be measured, very few edits can be done to check for illogical combinations of drug type and measurement. The only restriction will be to limit NP=Number of Plants to the following drugs: DRUG MEASUREMENT E=Marijuana NP G=Opium NP K=Other Hallucinogens NP All other Data Element 22 (Type Measurement) codes are applicable to any Data Element 20 (Suspected Drug Type) code."), _368("368","Property Segment","WITH DATA ENTERED BOTH TYPE (20) AND QUANTITY (21) MUST BE PRESENT","Data Element 22 (Type Measurement) was entered, but 20 (Suspected Drug Type) and/or 21 (Estimated Quantity) were not entered; both must be entered."), _372("372","Property Segment","DATA ELEMENTS 15-22 WERE ALL BLANK WITH THIS PROPERTY LOSS CODE","If Data Element 14 (Type Property/Loss/Etc.) is 2=Burned, 3=Counterfeited/ Forged, 4=Destroyed/Damaged/Vandalized, 5=Recovered, 6=Seized, or 7=Stolen/Etc., Data Elements 15 through 22 must have applicable entries in the segment."), _375("375","Property Segment","MANDATORY FIELD WITH THE PROPERTY LOSS CODE ENTERED","At least one Data Element 15 (Property Description) code must be entered when Data Element 14 (Type Property Loss/Etc.) contains Property Segment(s) for: 2=Burned 3=Counterfeited/Forged 4=Destroyed/Damaged/Vandalized 5=Recovered 6=Seized 7=Stolen/Etc."), _376("376","Property Segment","DUPLICATE PROPERTY SEGMENT ON ELECTRONIC SUBMISSION (TYPE LOSS=[loss- code])","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. Example, two property segments cannot be submitted having the same entry in Data Element 14 (Type Property Loss/Etc.)."), _382("382","Property Segment","DRUG/NARCOTIC VIOLATIONS OFFENSE MUST BE SUBMITTED FOR SEIZED DRUGS","Segment Level 3 (Property Segment) cannot be submitted with 10=Drugs/Narcotics in Data Element 15 (Property Description) and blanks in Data Element 16 (Value of Property) unless Data Element 6 (UCR Offense Code) is 35A=Drug/Narcotic Violations."), _383("383","Property Segment","PROPERTY VALUE MUST BE BLANK FOR 35A (SINGLE OFFENSE)","Data Element 16 (Value of Property) has a value other than zero entered. Since Data Element 15 (Property Description) code is 10=Drugs/Narcotics and the only Crime Against Property offense submitted is a 35A=Drug/Narcotic Violations, Data Element 16 (Value of Property) must be blank."), _384("384","Property Segment","DRUG QUANTITY MUST BE NONE WHEN DRUG MEASUREMENT IS NOT REPORTED","Data Element 21 (Estimated Drug Quantity) must be 000000001000=None (i.e., 1) when Data Element 22 (Type Drug Measurement) is XX=Not Reported indicating the drugs were sent to a laboratory for analysis. When the drug analysis is received by the LEA, Data Element 21 and Data Element 22 should be updated with the correct data values."), _387("387","Property Segment","WITH A PROPERTY LOSS=6 AND ONLY OFFENSE 35A CANNOT HAVE DESCRIPTION 11or WITH A PROPERTY LOSS=6 AND ONLY OFFENSE 35B CANNOT HAVE DESCRIPTION 10","To ensure that 35A-35B Drug/Narcotic Offenses- Drug Equipment Violations are properly reported, Data Element 15 (Property Description) of 11=Drug/Narcotic Equipment is not allowed with only a 35A Drug/Narcotic Violation. Similarly, 10=Drugs/Narcotics is not allowed with only a 35B Drug Equipment Violation. And Data Element 14 (Type Property Loss/Etc.) is 6=Seized."), _388("388","Property Segment","NUMBER STOLEN IS LESS THAN NUMBER OF VEHICLE CODES","More than one vehicle code was entered in Data Element 15 (Property Description), but the number stolen in Data Element 18 (Number of Stolen Motor Vehicles) is less than this number. For example, if vehicle codes of 03=Automobiles and 05=Buses were entered as being stolen, then the number stolen must be at least 2, unless the number stolen was unknown (00). The exception to this rule is when 00=Unknown is entered in Data Element 18."), _389("389","Property Segment","NUMBER RECOVERED IS LESS THAN NUMBER OF VEHICLE CODES","More than one vehicle code was entered in Data Element 15 (Property Description), but the number recovered in Data Element 19 (Number of Recovered Motor Vehicles) was less than this number. For example, if vehicle codes of 03=Automobiles and 05=Buses were entered as being recovered, then the number recovered must be at least 2, unless the number recovered was unknown (00). The exception to this rule is when 00=Unknown is entered in Data Element 18."), _390("390","Property Segment","ILLOGICAL PROPERTY DESCRIPTION FOR THE OFFENSE SUBMITTED","Data Element 15 (Property Description) must contain a data value that is logical for one or more of the offenses entered in Data Element 6 (UCR Offense Code). Illogical combinations include: 1) Property descriptions for structures are illogical with 220=Burglary/Breaking & Entering or 240=Motor Vehicle Theft 2) Property descriptions for items that would not fit in a purse or pocket (aircraft, vehicles, structures, a person’s identity, watercraft, etc.) are illogical with 23A=Pocket-picking or 23B=Purse- snatching 3) Property descriptions that cannot be shoplifted due to other UCR definitions (aircraft, vehicles, structures, a person’s identity, watercraft, etc.) are illogical with 23C=Shoplifting 4) Property descriptions for vehicles and structures are illogical with 23D=Theft from Building, 23E=Theft from Coin-Operated Machine or Device, 23F=Theft from Motor Vehicle, and 23G=Theft of Motor Vehicle Parts or Accessories Property descriptions for vehicles are illogical with 23H=All Other Larceny"), _391("391","Property Segment","PROPERTY VALUE MUST BE ZERO FOR DESCRIPTION SUBMITTED","Data Element 15 (Property Description) has a code that requires a zero value in Data Element 16 (Value of Property). Either the wrong property description code was entered or the property value was not entered. (This error was formerly error number 340, a warning message.) Data Element 16 (Value of Property) must be zero when Data Element 15 (Property Description) is: 09=Credit/Debit Cards 22=Nonnegotiable Instruments 48=Documents–Personal or Business 65=Identity Documents 66=Identity–Intangible"), _392("392","Property Segment","35A OFFENSE ENTERED AND 1=NONE ENTERED; MISSING SUSPECTED DRUG TYPE (20)","An offense of 35A Drug/Narcotic Violations and Data Element 14 (Type Property Loss/Etc.) with1=None were entered but Data Element 20 (Suspected Drug Type) was not submitted. Since a drug"), _401("401","Victim Segment","MUST BE PRESENT -- MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _402("402","Victim Segment","CONTAINS NONNUMERIC DIGITS","Must contain numeric entry with zero left-fill."), _404("404","Victim Segment","INVALID DATA VALUE— NOT ON FBI VALIDATION TABLE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _406("406","Victim Segment","NCA07: DUPLICATE VALUE=[value]","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), _407("407","Victim Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 33 (Type Injury) Can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), _408("408","Victim Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 26 (Age of Victim) contains data, but is not left-justified. A single two-character age must be in positions 1 and 2 of the field."), _409("409","Victim Segment","CONTAINS NONNUMERIC ENTRY","Data Element 26 (Age of Victim) contains more than two characters indicating a possible age-range was being attempted. If so, the field must contain numeric entry of four digits."), _410("410","Victim Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 26 (Age of Victim) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _415("415","Victim Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NONBLANK CHARACTERS","Data Element 2 (Incident Number) Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _416("416","Victim Segment","MUST BE LEFT- JUSTIFIED–BLANK DETECTED IN FIRST POSITION","Data Element 2 (Incident Number) Must be left-justified with blank right-fill if under 12 characters in length."), _417("417","Victim Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Data Element 2 (Incident Number)Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _419("419","Victim Segment","DATA CAN ONLY BE ENTERED FOR SPECIFIC OFFENSES","Data Element 31 (Aggravated Assault/Homicide Circumstances) can only be entered when one or more of the offenses in Data Element 24 (Victim Connected to UCR Offense Code) are: 09A=Murder and Non-negligent Manslaughter 09B=Negligent Manslaughter 09C=Justifiable Homicide 13A=Aggravated Assault Data Element 33 (Type Injury) can only be entered when one or more of the offenses in Data Element 24 (Victim Connected to UCR Offense Code) are: 100=Kidnapping/Abduction 11A=Rape 11B=Sodomy 11C=Sexual Assault With An Object 11D=Fondling 120=Robbery 13A=Aggravated Assault 13B=Simple Assault 210=Extortion/Blackmail 64A=Human Trafficking, Commercial Sex Acts 64B=Human Trafficking, Involuntary Servitude"), _422("422","Victim Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 26 (Age of Victim) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _449("449","Victim Segment","WARNING–VICTIM IS SPOUSE, BUT AGE IS LESS THAN 18","Data Element 26 (Age of Victim) cannot be less than 18 years old when Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE = Spouse."), _450("450","Victim Segment","VICTIM IS SPOUSE, BUT AGE IS LESS THAN 14","Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE=Spouse. When this is so, the age of the victim cannot be less than 10 years."), _451("451","Victim Segment","VICTIM NUMBER ALREADY EXISTS","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. In this case, two victim segments were submitted having the same entry in Data Element 23 (Victim Sequence Number)."), _453("453","Victim Segment","MUST BE PRESENT WHEN VICTIM TYPE (25)=I","The Data Element associated with this error must be present when Data Element 25 (Type of Victim) is I=Individual."), _454("454","Victim Segment","MUST BE ENTERED WHEN VICTIM TYPE IS LAW ENFORCEMENT OFFICER","Data Element 25A (Type of Officer Activity/Circumstance), Data Element 25B (Officer Assignment Type), Data Element 26 (Age of Victim), Data Element 27 (Sex of Victim), and Data Element 28 (Race of Victim) must be entered when Data Element 25 (Type of Victim) is L=Law Enforcement Officer."), _455("455","Victim Segment","ADDITIONAL JUSTIFIABLE HOMICIDE IS MANDATORY WITH A 20 OR 21 ENTERED","Data Element 31 (Aggravated Assault/Homicide Circumstances) contains: 20=Criminal Killed by Private Citizen Or 21=Criminal Killed by Police Officer, but Data Element 32 (Additional Justifiable Homicide Circumstances) was not entered."), _456("456","Victim Segment","ONLY ONE VALUE GREATER THAN OR EQUAL TO 10 CAN BE ENTERED","Data Element 31 (Aggravated Assault/Homicide Circumstances) was entered with two entries, but was rejected for one of the following reasons: 1) Value 10=Unknown Circumstances is mutually exclusive with any other value. 2) More than one category (i.e., Aggravated Assault, Negligent Manslaughter, etc.) was entered."), _457("457","Victim Segment","WHEN DATA ELEMENT 32 IS ENTERED, DATA ELEMENT 31 MUST EQUAL 20 OR 21","Data Element 32 (Additional Justifiable Homicide Circumstances) was entered, but Data Element 31 (Aggravated Assault/Homicide Circumstances) does not reflect a justifiable homicide circumstance."), _458("458","Victim Segment","VICTIM TYPE (25) MUST BE “I” OR “L” FOR DATA TO BE ENTERED","The Data Element associated with this error cannot be entered when Data Element 25 (Type of Victim) is not I=Individual or L=Law Enforcement Officer when Data Element 24 (Victim Connected to UCR Offense Code) contains a Crime Against Person."), _459("459","Victim Segment","NEED A CRIME AGAINST PERSON OR ROBBERY FOR DATA TO BE ENTERED","Data Element 34 (Offender Numbers To Be Related) was entered but should only be entered if one or more of the offenses entered into Data Element 24 [Victim Connected to UCR Offense Code(s)] is a Crime Against Person or is a Robbery Offense (120). None of these types of offenses were entered."), _460("460","Victim Segment","RELATIONSHIP MUST BE ENTERED WHEN AN OFFENDER NUMBER (34) EXISTS","Corresponding Data Element 35 (Relationship of Victim to Offenders) data must be entered when Data Element 34 (Offender Numbers To Be Related) is entered with a value greater than 00."), _461("461","Victim Segment","VICTIM TYPE CANNOT EQUAL “S” WITH AN OFFENSE OF 220","Data Element 25 (Type of Victim) cannot have a value of S=Society/Public when the offense is 220=Burglary/Breaking and Entering."), _462("462","Victim Segment","INVALID AGGRAVATED ASSAULT/HOMICIDE FOR 13A OFFENSE","An Offense Segment (Level 2) was submitted for 13A=Aggravated Assault. Accordingly, Data Element 31 (Aggravated Assault/Homicide Circumstances) can only have codes of 01 through 06 and 08 through 10. All other codes, including 07=Mercy Killing, are not valid because they do not relate to an aggravated assault"), _463("463","Victim Segment","INVALID AGGRAVATED ASSAULT/HOMICIDE FOR 09C OFFENSE","When a Justifiable Homicide is reported, Data Element 31 (Aggravated Assault/Homicide Circumstances) can only have codes of 20=Criminal Killed by Private Citizen or 21=Criminal Killed by Police Officer. In this case, a code other than the two mentioned was entered."), _464("464","Victim Segment","ENTRY FOR TYPE OF VICTIM MUST BE 'I' OR 'L' WHEN THIS OFFENSE CODE IS ENTERED","Data Element 24 (Victim Connected to UCR Offense Codes) contains a Crime Against Person, but Data Element 25 (Type of Victim) is not I=Individual or L=Law Enforcement Officer when Data Element 24 (Victim Connected to UCR Offense Code) contains a Crime Against Person."), _465("465","Victim Segment","ENTRY FOR TYPE OF VICTIM MUST BE “S” WHEN THIS OFFENSE CODE IS ENTERED","Data Element 24 (Victim Connected to UCR Offense Codes) contains a Crime Against Society, but Data Element 25 (Type of Victim) is not S=Society."), _466("466","Victim Segment","OFFENSE MUST BE SUBMITTED AS LEVEL 2 RECORD IF VICTIM IS CONNECTED","Each UCR Offense Code entered into Data Element 24 (Victim Connected to UCR Offense Codes) must have the Offense Segment for the value. In this case, the victim was connected to offenses that were not submitted as Offense Segments. A victim cannot be connected to an offense when the offense itself is not present."), _467("467","Victim Segment","ENTRY FOR TYPE OF VICTIM CANNOT BE “S” WHEN THIS OFFENSE CODE IS ENTERED","Data Element 24 (Victim Connected to UCR Offense Codes) contains a Crime Against Property, but Data Element 25 (Type of Victim) is S=Society. This is not an allowable code for Crime Against Property offenses."), _468("468","Victim Segment","RELATIONSHIP CANNOT BE ENTERED WHEN RELATED TO OFFENDER NUMBER '00'","Data Element 35 (Relationship of Victim to Offenders) cannot be entered when Data Element 34 (Offender Number to be Related) is zero. Zero means that the number of offenders is unknown; therefore, the relationship cannot be entered."), _469("469","Victim Segment","VICTIM SEX MUST BE “M” OR “F” FOR AN 11A OR 36B OFFENSE","Data Element 27 (Sex of Victim) must be M=Male or F=Female to be connected to offense codes of 11A=Forcible Rape and 36B=Statutory Rape."), _470("470","Victim Segment","WHEN “VO” RELATIONSHIP IS PRESENT, MUST HAVE TWO OR MORE VICTIMS AND OFFENDERS","Data Element 35 (Relationship of Victim to Offenders) has a relationship of VO=Victim Was Offender. When this code is entered, a minimum of two victim and two offender segments must be submitted. In this case, only one victim and/or one offender segment was submitted. The entry of VO on one or more of the victims indicates situations such as brawls and domestic disputes. In the vast majority of cases, each victim is also the offender; therefore, every victim record would contain a VO code. However, there may be some situations where only one of the victims is also the offender, but where the other victim(s) is not also the offender(s)."), _471("471","Victim Segment","ONLY ONE VO RELATIONSHIP PER VICTIM","Data Element 35 (Relationship of Victim to Offenders) has relationships of VO=Victim Was Offender that point to multiple offenders, which is an impossible situation. A single victim cannot be two offenders."), _472("472","Victim Segment","WHEN OFFENDER AGE/SEX/RACE ARE UNKNOWN, RELATIONSHIP MUST BE “RU”=UNKNOWN","Data Element 35 (Relationship of Victim to Offenders) has a relationship to the offender that is not logical. In this case, the offender was entered with unknown values for age, sex, and race. Under these circumstances, the relationship must be entered as RU=Relationship Unknown."), _474("474","Victim Segment","ONLY ONE VO RELATIONSHIP CAN BE ASSIGNED TO A SPECIFIC OFFENDER","Segment Level 4 (Victim Segment) cannot be submitted multiple times with VO=Victim Was Offender in Data Element 35 (Relationship of Victim to Offender) when Data Element 34 (Offender Number to be Related) contains the same data value (indicating the same offender)."), _475("475","Victim Segment","ONLY ONE “SE”L RELATIONSHIP PER VICTIM","A victim can only have one spousal relationship. In this instance, the victim has a relationship of SE=Spouse to two or more offenders."), _476("476","Victim Segment","ONLY ONE “SE” RELATIONSHIP CAN BE ASSIGNED TO A SPECIFIC OFFENDER","An offender can only have one spousal relationship. In this instance, two or more victims have a relationship of SE=Spouse to the same offender."), _477("477","Victim Segment","INVALID AGGRAVATED ASSAULT/HOMICIDE CIRCUMSTANCES FOR CONNECTED OFFENSE","A victim segment was submitted with Data Element 24 (Victim Connected to UCR Offense Code) having an offense that does not have a permitted code for Data Element 31 (Aggravated Assault/Homicide Circumstances). Only those circumstances listed in Volume 1, Section VI, are valid for the particular offense."), _478("478","Victim Segment","VICTIM CONNECTED TO AN INVALID COMBINATION OF OFFENSES","Mutually Exclusive offenses are ones that cannot occur to the same victim by UCR definitions. A Lesser Included offense is one that is an element of another offense and should not be reported as having happened to the victim along with the other offense. Lesser Included and Mutually Exclusive offenses are defined as follows: 1) Murder-Aggravated assault, simple assault, and intimidation are all lesser included offenses of murder. Negligent manslaughter is mutually exclusive. 2) Aggravated Assault-Simple assault and intimidation are lesser included Note: Aggravated assault is a lesser included offense of murder, forcible rape, forcible sodomy, sexual assault with an object, and robbery. 3) Simple Assault-Intimidation is a lesser included offense of simple assault. Note: Simple assault is a lesser included offense of murder, aggravated assault, forcible rape, forcible sodomy, sexual assault with an object, forcible fondling, and robbery. 4) Intimidation-Intimidation is a lesser included offense of murder, aggravated assault, forcible rape, forcible sodomy, sexual assault with an object, forcible fondling, and robbery. 5) Negligent Manslaughter-Murder, aggravated assault, simple assault, and intimidation are mutually exclusive offenses. Uniform Crime Reporting Handbook, NIBRS Edition, page 17, defines negligent manslaughter as “The killing of another person through negligence.” Page 12 of the same publication shows that assault offenses are characterized by “unlawful attack[s].” offenses of aggravated assault. 6) Forcible Rape-Aggravated assault, simple assault, intimidation, and forcible fondling are lesser included offenses of forcible rape. Incest and statutory rape are mutually exclusive offenses and cannot occur with forcible rape. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. 7) Forcible Sodomy-Aggravated assault, simple assault, intimidation, and forcible fondling are lesser included offenses of forcible sodomy. Incest and statutory rape are mutually exclusive offenses and cannot occur with forcible sodomy. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. 8) Sexual Assault with an Object- Aggravated assault, simple assault, intimidation, and forcible fondling are lesser included offenses of sexual assault with an object. Incest and statutory rape are mutually exclusive offenses and cannot occur with sexual assault with an object. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. 9) Forcible Fondling-Simple assault and intimidation are lesser included offenses of forcible fondling. Incest and statutory rape are mutually exclusive offenses and cannot occur with forcible fondling. The prior two offenses involve consent, while the latter involves forced action against the victim’s will. Note: Forcible fondling is a lesser included offense of forcible rape, forcible sodomy, and sexual assault with an object. 10) Incest-Forcible rape, forcible sodomy, sexual assault with an object, and forcible fondling are mutually exclusive offenses. Incest involves consent, while the prior offenses involve forced sexual relations against the victim’s will. 11) Statutory Rape-Forcible Rape, forcible sodomy, sexual assault with an object, and forcible fondling are mutually exclusive offenses. Statutory rape involves consent, while the prior offenses involve forced sexual relations against the victim’s will. 12) Robbery-Aggravated assault, simple assault, intimidation, and all theft offenses (including motor vehicle theft) are lesser included offenses of robbery."), _479("479","Victim Segment","SIMPLE ASSAULT(13B) CANNOT HAVE MAJOR INJURIES","A Simple Assault (13B) was committed against a victim, but the victim had major injuries/trauma entered for Data Element 33 (Type Injury). Either the offense should have been classified as an Aggravated Assault (13A) or the victim’s injury should not have been entered as major."), _480("480","Victim Segment","WHEN ASSAULT/HOMICIDE (31) IS 08, INCIDENT MUST HAVE TWO OR MORE OFFENSES","Data Element 31 (Aggravated Assault/Homicide Circumstances) has 08=Other Felony Involved but the incident has only one offense. For this code to be used, there must be an Other Felony. Either multiple entries for Data Element 6 (UCR Offense Code) should have been submitted, or multiple individual victims should have been submitted for the incident report."), _481("481","Victim Segment","VICTIM’S AGE MUST BE LESS THAN [maximum for state] FOR STATUTORY RAPE (36B)","Data Element 26 (Age of Victim) should be under 18 when Data Element 24 (Victim Connected to UCR Offense Code) is 36B=Statutory Rape."), _482("482","Victim Segment","LEOKA VICTIM MUST BE CONNECTED TO MURDER OR ASSAULT OFFENSE","Data Element 25 (Type of Victim) cannot be L=Law Enforcement Officer unless Data Element 24 (Victim Connected to UCR Offense Code) is one of the following: 09A=Murder & Non-negligent Manslaughter 13A=Aggravated Assault 13B=Simple Assault 13C=Intimidation"), _483("483","Victim Segment","VICTIM MUST BE LAW ENFORCEMENT OFFICER TO ENTER LEOKA DATA","Data Element 25A (Type of Officer Activity/Circumstance), Data Element 25B (Officer Assignment Type), Data Element 25C (Officer–ORI Other Jurisdiction), Data Element 26 (Age of Victim), Data Element 27 (Sex of Victim), Data Element 28 (Race of Victim), Data Element 29 (Ethnicity of Victim), Data Element 30 (Resident Status of Victim), and Data Element 34 (Offender Number to be Related) can only be entered when Data Element 25 (Type of Victim) is I=Individual or L=Law Enforcement Officer."), _484("484","Victim Segment","THIS VICTIM SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Victim Segment (Level 4) must be 129 characters (not reporting LEOKA) or 141 characters (reporting LEOKA). All Victim Segments in a submission must be formatted in only one of these two lengths."), _501("501","Offender Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _502("502","Offender Segment","CONTAINS NONNUMERIC ENTRY","Data Element 36 (Offender Sequence Number) must contain numeric entry (00 through 99) with zero left-fill."), _504("504","Offender Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _508("508","Offender Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 37 (Age of Offender) contains data but is not left-justified. A single two-character age must be in positions 1 through 2 of the field."), _509("509","Offender Segment","CONTAINS NONNUMERIC ENTRY","Data Element 37 (Age of Offender) contains more than two characters indicating a possible age- range is being attempted. If so, the field must contain a numeric entry of four digits."), _510("510","Offender Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 37 (Age of Offender) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _515("515","Offender Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _516("516","Offender Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Must be left-justified with blank right-fill if under 12 characters in length."), _517("517","Offender Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHEN, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _522("522","Offender Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 37 (Age of Offender) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _549("549","Offender Segment","WARNING–OFFENDER IS SPOUSE, BUT AGE IS LESS THAN 18","Data Element 37 (Age of Offender) cannot be less than 18 years old when Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE = Spouse."), _550("550","Offender Segment","OFFENDER IS SPOUSE, BUT AGE IS LESS THAN 10","Cannot be less than 10 years old when Data Element 35 (Relationship of Victim to Offender) contains a relationship of SE=Spouse."), _551("551","Offender Segment","DUPLICATE OFFENDER SEGMENT","When a Group “A” Incident Report is submitted, the individual segments comprising the incident cannot contain duplicates. In this case, two Offender Segments were submitted having the same entry in Data Element 36 (Offender Sequence Number)."), _552("552","Offender Segment","CANNOT BE PRESENT WHEN OFFENDER NUMBER IS “00” UNKNOWN","Data Element 37 (Age of Offender) cannot be entered when Data Element 36 (Offender Sequence Number) is 00=Unknown."), _553("553","Offender Segment","SEX OF VICTIM AND OFFENDER DOES NOT REFLECT THE RELATIONSHIP","Data Element 35 (Relationship of Victim to Offenders) has a relationship that is inconsistent with the offender’s sex. The sex of the victim and/or offender must reflect the implied relationship. For example, if the relationship of the victim to offender is Homosexual Relationship, then the victim’s sex must be the same as the offender’s sex. The following relationships must reflect either the Same or Different sex codes depending upon this relationship: Relationship Sex Code BG=Victim was Boyfriend/Girlfriend Different XS=Victim was Ex-Spouse Different SE=Victim was Spouse Different CS=Victim was Common-Law Spouse Different HR=Homosexual Relationship Same"), _554("554","Offender Segment","AGE OF VICTIM AND OFFENDER DOES NOT REFLECT THE RELATIONSHIP","Data Element 35 (Relationship of Victim to Offenders) has a relationship that is inconsistent with the offender’s age. The age of the victim and/or offender must reflect the implied relationship. For example, if the relationship of the victim to offender is PA=Parent, then the victim’s age must be greater than the offender’s age. The following relationships must be consistent with the victim’s age in relation to the offender’s age: Relationship Victim’s Age Is CH=Victim was Child Younger PA=Victim was Parent Older GP=Victim was Grandparent Older GC=Victim was Grandchild Younger"), _555("555","Offender Segment","OFFENDER “00” EXISTS— CANNOT SUBMIT MORE OFFENDERS","When multiple Offender Segments are submitted, none can contain a 00=Unknown value because the presence of 00 indicates that the number of offenders is unknown. In this case, multiple offenders were submitted, but one of the segments contains the 00=Unknown value."), _556("556","Offender Segment","OFFENDER AGE MUST BE NUMERIC DIGITS","Data Element 37 (Age of Offender) must contain numeric entry of 00 through 99"), _557("557","Offender Segment","OFFENDER SEQUENCE NUMBER CANNOT BE UNKNOWN IF INCIDENT CLEARED EXCEPTIONALLY","Data Element 36 (Offender Sequence Number) contains 00 indicating that nothing is known about the offender(s) regarding number and any identifying information. In order to exceptionally clear the incident, the value cannot be 00. The incident was submitted with Data Element 4 (Cleared Exceptionally) having a value of A through E."), _558("558","Offender Segment","AT LEAST ONE OFFENDER MUST HAVE KNOWN VALUES","None of the Offender Segments contain all known values for Age, Sex, and Race. When an Incident is cleared exceptionally (Data Element 4 contains an A through E), one offender must have all known values."), _559("559","Offender Segment","OFFENDER DATA MUST BE PRESENT IF OFFENSE CODE IS 09C, JUSTIFIABLE HOMICIDE","The incident was submitted with Data Element 6 (UCR Offense Code) value of 09C=Justifiable Homicide, but unknown information was submitted for all the offender(s). At least one of the offenders must have known information for Age, Sex, and Race."), _560("560","Offender Segment","VICTIM’S SEX CANNOT BE SAME FOR ALL OFFENDERS FOR OFFENSES OF RAPE","Segment Level 5 (Offender Segment) must contain a data value for at least one offender in Data Element 38 (Sex of Offender) that is not the same sex that is entered in Data Element 27 (Sex of Victim) when Data Element 6 (UCR Offense Code) is 11A=Rape."), _572("572","Offender Segment","RELATIONSHIP UNKNOWN IF OFFENDER INFO MISSING","Data Element 37 (Age of Offender) If Data Element 37 (Age of Offender) is 00=Unknown, Data Element 38 (Sex of Offender) is U=Unknown, and Data Element 39 (Race of Offender) is U=Unknown then Data Element 35 (Relationship of Victim to Offender) must be RU=Relationship Unknown."), _584("584","Offender Segment","THIS OFFENDER SEGMENT HAS A CONFLICTING LENGTH","Segment Length for the Offender Segment (Level 5) must be 45 characters (not reporting Offender Ethnicity) or 46 characters (reporting Offender Ethnicity). All Offender Segments in a submission must be formatted in only one of these two lengths."), _601("601","Arrestee Segment","MUST BE PRESENT— MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _602("602","Arrestee Segment","CONTAINS NONNUMERIC ENTRY","Data Element 40 (Arrestee Sequence Number) must be numeric entry of 01 to 99 with zero left- fill."), _604("604","Arrestee Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _605("605","Arrestee Segment","INVALID ARREST DATE","Data Element 42 (Arrest Date) Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31 days). The date cannot exceed the current date. The date cannot be later than that entered within the Month of Electronic submission and Year of Electronic submission fields on the data record. For example, if Month of Electronic submission and Year of Electronic submission are 06/1999, the arrest date cannot contain any date 07/01/1999 or later."), _606("606","Arrestee Segment","ERROR - DUPLICATE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), _607("607","Arrestee Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), _608("608","Arrestee Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) contains data, but is not left-justified. A single two-character age must be in positions 1 through 2 of the field."), _609("609","Arrestee Segment","CONTAINS NONNUMERIC ENTRY","Data Element 47 (Age of Arrestee) contains more than two characters indicating a possible age- range is being attempted. If so, the field must contain a numeric entry of four digits."), _610("610","Arrestee Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 47 (Age of Arrestee) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _615("615","Arrestee Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _616("616","Arrestee Segment","MUST BE LEFT-JUSTIFIED— BLANK DETECTED IN FIRST POSITION","Data Element 2 (Incident Number) and Data Element 41 (Arrest Transaction Number) must be left justified with blank right-fill when less than 12 characters in length."), _617("617","Arrestee Segment","CANNOT HAVE CHARACTERS OTHER THAN A-Z, 0-9, HYPHENS, AND/OR BLANKS","Data Element 2 (Incident Number) Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _618("618","Arrestee Segment","AGENCY IS IN COVERED-BY STATUS","Data Element 42 (Arrest Date) cannot contain a date on or after the date a LEA is placed in Covered-by Status. When data are received for a LEA in Covered-by Status, the FBI will remove the agency from Covered-by Status, process the submission, and notify the agency. Additionally, adjustments to previously- submitted data from an agency now in Covered-by Status will be processed and no error will be generated."), _622("622","Arrestee Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _623("623","Arrestee Segment","CLEARANCE INDICATOR AND CLEARANCE OFFENSE CODE MUST BE BLANK","Clearance Indicator and Clearance Offense Code must be blank when Segment Action Type on Level 6 (Arrestee Segment) is I=Incident."), _640("640","Arrestee Segment","WARNING–NO DISPOSITION FOR POSSIBLE JUVENILE ARRESTEE","Data Element 52 (Disposition of Arrestee Under 18) was not entered, but Data Element 47 (Age of Arrestee) indicates an age-range for a juvenile. The low age is a juvenile and the high age is an adult, but the average age is a juvenile. Note: When an age-range is not entered and the age is a juvenile, then the disposition must be entered. These circumstances were flagged by the computer as a possible discrepancy between age and disposition and should be checked for possible correction by the participant."), _641("641","Arrestee Segment","WARNING - ARRESTEE HAD AN AGE OF 99 OR OLDER","Data Element 47 (Age of Arrestee) was entered with a value of 99 which means the arrestee was over 98 years old. Verify that the submitter of data is not confusing the 99=Over 98 Years Old with 00=Unknown."), _652("652","Arrestee Segment","DISPOSITION MUST BE ENTERED WHEN AGE IS LESS THAN 18","Data Element 52 (Disposition of Juvenile) was not entered, but Data Element 47 (Age of Arrestee) is under 18. Whenever an arrestee’s age indicates a juvenile, the disposition must be entered."), _653("653","Arrestee Segment","FOR AGE GREATER THAN 17 DISPOSITION SHOULD NOT BE ENTERED","Data Element 52 (Disposition of Juvenile) was entered, but Data Element 47 (Age of Arrestee) is 18 or greater. Whenever an arrestee’s age indicates an adult, the juvenile disposition cannot be entered because it does not apply."), _654("654","Arrestee Segment","AUTOMATIC INDICATOR MUST BE BLANK OR “A”","Data Element 46 (Arrestee Was Armed With) does not have A=Automatic or a blank in the third position of field."), _655("655","Arrestee Segment","WEAPON TYPE MUST=11, 12, 13, 14, OR 15 FOR AN “A” IN THE AUTO INDICATOR","In Data Element 46 (Arrestee Was Armed With), A=Automatic is the third character of code. It is valid only with codes: 11=Firearm (Type Not Stated) 12=Handgun 13=Rifle 14=Shotgun 15=Other Firearm A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm."), _656("656","Arrestee Segment","THIS ARRESTEE EXCEEDED THE NUMBER OF OFFENDERS ON THE GROUP 'A' INCIDENT","A Group “A” Incident Report was submitted with more arrestees than offenders. The number (nn) of offenders is shown within the message. The incident must be resubmitted with additional Offender Segments. This message will also occur if an arrestee was submitted and Data Element 36 (Offender Sequence Number) was 00=Unknown. The exception to this rule is when an additional arrest is reported for a pre-NIBRS incident. In this case, Segment Level 6 (Arrestee Segment) will contain A=Add, but the data value in Data Element 2 (Incident Number) will not match an incident already on file in the national UCR database. The segment will be processed, but used only for SRS purposes and will not be included in the agency’s NIBRS figures."), _661("661","Arrestee Segment","ARRESTEE SEQUENCE NUMBER ALREADY EXISTS","Segment Level 6 (Arrestee Segment) cannot contain duplicate data values in Data Element 40 (Arrestee Sequence Number) when two or more Arrestee Segments are submitted for the same incident."), _664("664","Arrestee Segment","ARRESTEE AGE MUST BE NUMERIC DIGITS","Data Element 47 (Age of Arrestee) does not contain a numeric entry of 00 through 99 for an exact age."), _665("665","Arrestee Segment","ARREST DATE CANNOT BE BEFORE THE INCIDENT START DATE","Data Element 42 (Arrest Date) cannot be earlier than Data Element 3 (Incident Date/Hour). A person cannot be arrested before the incident occurred."), _667("667","Arrestee Segment","INVALID ARRESTEE SEX VALUE","Data Element 48 (Sex of Arrestee) does not contain a valid code of M=Male or F=Female. Note: U=Unknown (if entered) is not a valid sex for an arrestee."), _669("669","Arrestee Segment","NO ARRESTEE RECORDS ALLOWED FOR A JUSTIFIABLE HOMICIDE","Group “A” Incident Reports cannot have arrests when Data Element 6 (UCR Offense Code) is 09C=Justifiable Homicide. By definition a justifiable homicide never involves an arrest of the offender (the person who committed the justifiable homicide)."), _670("670","Arrestee Segment","JUSTIFIABLE HOMICIDE CANNOT BE AN ARREST OFFENSE CODE","Data Element 45 (UCR Arrest Offense Code) was entered with 09C=Justifiable Homicide. This is not a valid arrest offense"), _701("701","Group B Arrest Segment","MUST BE POPULATED WITH A VALID DATA VALUE– MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _702("702","Group B Arrest Segment","CONTAINS NONNUMERIC ENTRY","Data Element 40 (Arrestee Sequence Number) must be numeric entry of 01 to 99 with zero left- fill."), _704("704","Group B Arrest Segment","INVALID DATA VALUE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), _705("705","Group B Arrest Segment","INVALID ARREST DATE","Data Element 42 (Arrest Date) Each component of the date must be valid; that is, months must be 01 through 12, days must be 01 through 31, and year must include the century (i.e., 19xx, 20xx). In addition, days cannot exceed maximum for the month (e.g., June cannot have 31 days). The date cannot exceed the current date. The date cannot be later than that entered within the Month of Electronic submission and Year of Electronic submission fields on the data record. For example, if Month of Electronic submission and Year of Electronic submission are 06/1999, the arrest date cannot contain any date 07/01/1999 or later."), _706("706","Group B Arrest Segment","ERROR - DUPLICATE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) cannot contain duplicate data values although more than one data value is allowed."), _707("707","Group B Arrest Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 46 (Arrestee Was Armed With) can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), _708("708","Group B Arrest Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) contains data, but is not left-justified. A single two-character age must be in positions 1 through 2 of the field."), _709("709","Group B Arrest Segment","CONTAINS NONNUMERIC ENTRY","Data Element 47 (Age of Arrestee) contains more than two characters indicating a possible age-range is being attempted. If so, the field must contain numeric entry of four digits."), _710("710","Group B Arrest Segment","FIRST AGE MUST BE LESS THAN SECOND FOR AGE RANGE","Data Element 47 (Age of Arrestee) was entered as an age-range. Accordingly, the first age component must be less than the second age."), _715("715","Group B Arrest Segment","CANNOT HAVE EMBEDDED BLANKS BETWEEN FIRST AND LAST NON-BLANK CHARACTERS","Must be blank right-fill if under 12 characters in length. Cannot have embedded blanks between the first and last characters entered."), _716("716","Group B Arrest Segment","MUST BE LEFT-JUSTIFIED– BLANK DETECTED IN FIRST POSITION","Must be left-justified with blank right-fill if under 12 characters in length."), _717("717","Group B Arrest Segment","CANNOT HAVE CHARACTERS OTHER THAN A–Z, 0–9, AND/OR HYPHENS, AND/OR BLANKS","Must contain a valid character combination of the following: A–Z (capital letters only) 0–9 Hyphen Example: 11-123-SC is valid, but 11+123*SC is not valid."), _718("718","Group B Arrest Segment","AGENCY IS IN COVERED-BY STATUS","Data Element 42 (Arrest Date) cannot contain a date on or after the date a LEA is placed in Covered-by Status. When data are received for a LEA in Covered-by Status, the FBI will remove the agency from Covered-by Status, process the submission, and notify the agency. Additionally, adjustments to previously submitted data from an agency now in Covered-by Status will be processed and no error will be generated."), _720("720","Group B Arrest Segment","ARREST DATE CANNOT PREDATE BASE DATE","Group “B” Arrest Report (Level 7) submitted with a Segment Action Type of A=Add cannot have Data Element 42 (Arrest Date) earlier than the Base Date."), _722("722","Group B Arrest Segment","AGE RANGE CANNOT HAVE “00” IN FIRST TWO POSITIONS","Data Element 47 (Age of Arrestee) was entered as an age-range. Therefore, the first age component cannot be 00 (unknown)."), _740("740","Group B Arrest Segment","WARNING–NO DISPOSITION FOR POSSIBLE JUVENILE ARRESTEE","Data Element 52 (Disposition of Arrestee Under 18) was not entered, but Data Element 47 (Age of Arrestee) indicates an age-range for a juvenile. The low age is a juvenile and the high age is an adult, but the average age is a juvenile. Note: When an age-range is not entered and the age is a juvenile, the disposition must be entered. These circumstances were flagged by the computer as a possible discrepancy between age and disposition and should be checked for possible correction by the participant"), _741("741","Group B Arrest Segment","WARNING–ARRESTEE IS OVER AGE 98","Data Element 47 (Age of Arrestee) was entered with a value of 99, which means the arrestee is over 98 years old. The submitter should verify that 99=Over 98 Years Old is not being confused the with 00=Unknown."), _751("751","Group B Arrest Segment","ARRESTEE SEQUENCE NUMBER ALREADY EXISTS","When a Group “B” Arrest Report (Level 7) has two or more arrestees, the individual segments comprising the report cannot contain duplicates. In this case, two arrestee segments were submitted having the same entry in Data Element 40 (Arrestee Sequence Number)."), _752("752","Group B Arrest Segment","DISPOSITION MUST BE ENTERED WHEN AGE IS LESS THAN 18","Data Element 52 (Disposition of Juvenile) was not entered, but Data Element 47 (Age of Arrestee) is under 18. Whenever an arrestee’s age indicates a juvenile, the disposition must be entered."), _753("753","Group B Arrest Segment","FOR AGE GREATER THAN 17 DISPOSITION SHOULD NOT BE ENTERED","Data Element 52 (Disposition of Juvenile) was entered, but Data Element 47 (Age of Arrestee) is 18 or greater. Whenever an arrestee’s age indicates an adult, the juvenile disposition cannot be entered because it does not apply."), _754("754","Group B Arrest Segment","AUTOMATIC INDICATOR MUST BE BLANK OR “A”","Data Element 46 (Arrestee Was Armed With) does not have A=Automatic or a blank in the third position of field."), _755("755","Group B Arrest Segment","WEAPON TYPE MUST=11, 12, 13, 14, OR 15 FOR AN “A” IN THE AUTO INDICATOR","If Data Element 46 (Arrestee Was Armed With) weapon is an Automatic, add A as the third character of code; valid only with codes of: 11=Firearm (Type Not Stated) 12=Handgun 13=Rifle 14=Shotgun 15=Other Firearm A weapon code other than those mentioned was entered with the automatic indicator. An automatic weapon is, by definition, a firearm."), _757("757","Group B Arrest Segment","ARRESTEE AGE MUST BE NUMERIC DIGITS","Data Element 47 (Age of Arrestee) does not contain a numeric entry of 00 through 99 for an exact age."), _758("758","Group B Arrest Segment","INVALID ARRESTEE SEX VALUE","Data Element 48 (Sex of Arrestee) does not contain a valid code of M=Male or F=Female. Note that U=Unknown (if entered) is not a valid sex for an arrestee."), _759("759","Group B Arrest Segment","DUPLICATE GROUP “B” ARREST REPORT SEGMENT ON FILE","The Group “B” Arrest Report (Level 7) submitted as an Add is currently active in the FBI’s database; therefore, it was rejected. If multiple arrestees are involved in the incident, ensure that Data Element 40 (Arrestee Sequence Number) is unique for each Arrestee Segment submitted so that duplication does not occur."), _760("760","Group B Arrest Segment","LEVEL 7 ARRESTS MUST HAVE A GROUP “B” OFFENSE","Group “B” Arrest Reports (Level 7) must contain a Group “B” Offense Code in Data Element 45 (UCR Arrest Offense). The offense code submitted is not a Group “B” offense code."), _761("761","Group B Arrest Segment","ARRESTEE AGE MUST BE 01–17 FOR A RUNAWAY OFFENSE","Data Element 47 (Age of Arrestee) must be 01 through 17 for offense code of 90I=Runaway on a Group “B” Arrest Report."), _001("001","Zero Report Segment","MUST BE POPULATED WITH A VALID DATA VALUE– MANDATORY FIELD","Mandatory Data Elements (Mandatory=Yes) must be populated with a valid data value and cannot be blank."), _090_StructureCheck("090","Structure Check","ZERO-REPORTING MONTH IS NOT 01-12","A Segment Level 0 was submitted that had an invalid reporting month in positions 38 through 39. The data entered must be a valid month of 01 through 12."), _092_StructureCheck("092","Structure Check","ZERO-REPORTING INCIDENT NUMBER MUST BE ALL ZEROS","A Segment Level 0 was submitted, but the incident number entered into positions 26 through 37 was not all zeros."), _093_StructureCheck("093","Structure Check","ZERO-REPORTING MONTH/YEAR WAS PRIOR TO THE BASE DATE","A Segment Level 0 was submitted with a month and year entered into positions 38 through 43 that is earlier than January 1 of the previous year or before the date the agency converted over to NIBRS."), _094_StructureCheck("094","Structure Check","ZERO-REPORTING MONTH/YEAR EXCEEDED MONTH/YEAR OF ELECTRONIC SUBMISSION","A Segment Level 0 was submitted with a month and year entered into positions 38 through 43 that was later than the Month of Electronic submission and Year of Electronic submission entered into positions 7 through 12. Note: Error Numbers 001, 015, 016, and 017 are also Zero-Reporting segment errors."), _090_ZeroReport("090","Zero Report Segment","ZERO REPORT MONTH IS NOT 01–12","Zero Report Month must be a valid month, data values 01 through 12."), _092_ZeroReport("092","Zero Report Segment","ZERO REPORT INCIDENT NUMBER MUST BE ALL ZEROS","Data Element 2 (Incident Number) in the Zero Report Segment (Level 0) must contain 12 zeros."), _093_ZeroReport("093","Zero Report Segment","ZERO REPORT MONTH/YEAR IS PRIOR TO AGENCY CONVERSION TO THE NIBRS","Zero Report Month and Zero Report Year must be later than the month and year in the date the LEA converted to the NIBRS."), _094_ZeroReport("094","Zero Report Segment","ZERO REPORT MONTH/YEAR EXCEEDED MONTH/YEAR OF SUBMISSION","Zero Report Month and Zero Report Year must be earlier than Month of Submission and Year of Submission."); public String code; public String type; public String message; public String description; private NIBRSErrorCode(String code, String type, String message, String description) { this.code = code; this.type = type; this.message = message; this.description = description; } }
Fix the 404 error short description.
tools/nibrs-common/src/main/java/org/search/nibrs/model/codes/NIBRSErrorCode.java
Fix the 404 error short description.
<ide><path>ools/nibrs-common/src/main/java/org/search/nibrs/model/codes/NIBRSErrorCode.java <ide> _392("392","Property Segment","35A OFFENSE ENTERED AND 1=NONE ENTERED; MISSING SUSPECTED DRUG TYPE (20)","An offense of 35A Drug/Narcotic Violations and Data Element 14 (Type Property Loss/Etc.) with1=None were entered but Data Element 20 (Suspected Drug Type) was not submitted. Since a drug"), <ide> _401("401","Victim Segment","MUST BE PRESENT -- MANDATORY FIELD","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), <ide> _402("402","Victim Segment","CONTAINS NONNUMERIC DIGITS","Must contain numeric entry with zero left-fill."), <del> _404("404","Victim Segment","INVALID DATA VALUE— NOT ON FBI VALIDATION TABLE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), <add> _404("404","Victim Segment","INVALID DATA VALUE -- NOT ON FBI VALIDATION TABLE","The referenced data element in a Group A Incident Report must be populated with a valid data value and cannot be blank."), <ide> _406("406","Victim Segment","NCA07: DUPLICATE VALUE=[value]","The referenced data element in error is one that contains multiple data values. When more than one code is entered, none can be duplicate codes."), <ide> _407("407","Victim Segment","ERROR - MUTUALLY EXCLUSIVE VALUE=[value]","Data Element 33 (Type Injury) Can have multiple data values and was entered with multiple values. However, the entry shown between the brackets in [value] above cannot be entered with any other data value."), <ide> _408("408","Victim Segment","EXACT AGE MUST BE IN FIRST TWO POSITIONS","Data Element 26 (Age of Victim) contains data, but is not left-justified. A single two-character age must be in positions 1 and 2 of the field."),